Javascript won't post into DIV? - java

So the console shows that the data is being sent and received but for some reason (probably the conditional) nothing is posted in the specified div tag
var var_IDdatacheck = <?php echo $javaid; ?>;
var var_IDcheck = parseInt(var_IDdatacheck);
//datacheck
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck() {
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck, javaid: var_IDcheck},
success: function (check) {
console.log(check);
var verify = JSON.parse(check);
if (var_IDcheck < verify.id) {
var_IDcheck = verify.id;
for (var i=0;i<var_IDcheck;i++){
$('#datacheck').html(verify[i]);
}
}
setTimeout(activitycheck(),5000);
},
error: function(check) {
console.log(check);
setTimeout(activitycheck(),5000);
}
});
}
$(document).ready(function() {
activitycheck();
}); // document ready

Your id from the JSON is a string, and you are comparing it with an integer
try
var verify = JSON.parse(check);
if (var_IDcheck < parseInt(verify.id)) {
var_IDcheck = parseInt(verify.id);
for (var i=0;i<var_IDcheck;i++){

Related

Configure multiple base url's in Karate [duplicate]

I have more than 6 environments against which i have to run the same set of rest api scripts. For that reason i have stored all that test data and the end points/resource paths in a json file. I then try to read this json file into my karate-config.js file, this is because i want to fetch the data corresponding to the environment that is being passed from the command line (karate.env), which am reading into my karate-config.js file
Below is my json file sample
[
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
}
},
{
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
]
and below is my karate-config.js file
function() {
// var env = karate.env; // get system property 'karate.env'
var env = 'qa';
var cm = 'ON';
var envData = call read('classpath:env_data.json'); //require("./env_data.json");
// write logic to read data from the json file _ Done, need testing
karate.log('karate.env system property was:', env);
switch(env) {
case "qa":
if(cm === 'ON'){
config.adminusername_cm_on = getData().username_cm_on;
config.adminpassword_cm_on = "";
config.nonadminusername_cm_on = getData().nonadmin_username_cm_on;
config.nonadminpassword_cm_on = "";
}else if(cm === "OFF") {
config.adminusername_cm_off = getData().username_cm_off;
config.adminpassword_cm_off = "";
config.nonadminusername_cm_off = getData().nonadmin_username_cm_off;
config.nonadminpassword_cm_off = "";
}
break;
case "uat":
break;
default:
break;
}
// This method will return the data from the env_data.json file
var getData = function() {
for(var i = 0; i < obj.length; i++) {
for(var e in obj[i]){
var username_cm_on = obj[i][e]['username_cm_on'];
var nonadmin_username_cm_on = obj[i][e]['nonadmin_username_cm_on'];
var username_cm_off = obj[i][e]['username_cm_off'];
var nonadmin_username_cm_off = obj[i][e]['nonadmin_username_cm_off'];
return {
username_cm_on: username_cm_on,
nonadmin_username_cm_on: nonadmin_username_cm_on,
username_cm_off: username_cm_off,
nonadmin_username_cm_off: nonadmin_username_cm_off
}
}
}
}
var config = {
env: env,
data: getData(),
}
return config;
}
I tried several ways to load the env-data.json file into karate-config.js as below
var envData = call read('classpath:env_data.json');
I know the above is not valid from this stackover flow answer Karate - How to import json data by Peter Thomas
So,tried with the below ones
var envData = read('classpath:env_data.json');
var envData = require("./env_data.json");
var envData = require('./env_data.json');
But, still facing issues with reading the json file. Appreciate help on this.
I think you over-complicated your JSON. You just need one object and no top-level array. Just use this as env_data.json:
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
},
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
And then this karate-config.js will work:
function() {
var env = 'qa'; // karate.env
var temp = read('classpath:env_data.json');
return temp[env];
}
And your tests can be more readable:
Given url zuul_urls['home-sec-uri']
If you have trouble understanding how this works, refer to this answer: https://stackoverflow.com/a/59162760/143475

Springboot controller expect to load .jsp instead of return data

I have a page which contain a combo boxes. onChange of first combo box makes a url call and collect data and generate another combo box with these data.
This is my onchange function:
function seatValue() {
var postid = $('#postid').val();
var dsgid = $('#dsgid').val();
var html2 = '<option value="0" selected>--select--</option>';
$.ajax({
url : 'loadSeat?postid='+postid+'&dsgid='+dsgid, //data
type : 'POST',
dataType : 'json',
success : function(data) {
alert("success!");
for (var i = 0, len = data.length; i < data.length; ++i) {
var item = data[i];
html2 = html2
+ "<option value='"+item.postId+"'>"
+ item.postName + "</option>";
}
$("#postid").html(html2);
$("#scheduleButton").css("display","block");
},
error : function() {
alert("Error!")
}
});
}
Controller :
#RequestMapping(value = { "/loadSeat" }, method = RequestMethod.POST)
public List<SeatValuesModel> LoadSeat(#RequestParam("postid") String postid,
#RequestParam("dsgid") String dsgid) {
List<SeatValuesModel> seatvalues = new ArrayList<>();
seatvalues= employeeService.getSeat(postid, dsgid);
System.out.println("seatvalues "+seatvalues.get(0).getPostName());
return seatvalues;
}
this is the response I'm getting in the console
why this expecting a .jsp . and on my ajax call it always error what is printing. There is some issue with my controller. Pls do help...

How to get value from jquery each loop when controller returns list

I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});

Cannot retrieve data sent by restfulwebservice in Java

I sent Json as post request from Javascript by restfulwebservice but the break point never breaks in Java file which is post type and consumes application/json
HTML:
var url = "http://localhost:8080/RestfulInEMS/user/admin";
empJson = {Username:x[1],IdentityNo:x[2]};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(empJson);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= xmlhttp.responseText;
}
}
JAVA:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void AddEmployee(JSONObj input)
//here JSONObj is class with data variables same as key name in JSON object sent
I got the Solution :
Problem:
xmlhttp.send(empJson);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= xmlhttp.responseText;
}
}
Solution:
xmlhttp.send(JSON.stringify(empJson));
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= JSON.parse(xmlhttp.responseText);
}
}
Explanation:
I need to convert it to string to pass as Json and used Jackson libraries for mapping it to class directly and while recieving it i recieve as text and use Json.parse to parse into a object.

Unable to get value in Ajax response

The servlet which receives request --
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
LoginBean loginInfo = getInfo(userId,userPwd);
//System.out.println("00000000-----------"+loginInfo.userId);
JsonElement loginObj = gson.toJsonTree(loginInfo);
if(loginInfo.getUserId() == "GUEST!"){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("login", loginObj);
System.out.println(":::::"+myObj.get("success"));
out.println(myObj.toString());
out.close();
Here is the js file -----
function loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
loadScript("js/json2.js", myJSCode);
var myJSCode = $(document).ready(function() {
$("#loginForm").submit(function(e){
e.preventDefault();
});
$("#login").click(function(e){
dataString = $("#loginForm").serialize();
var id = $("input#id").val();
var pwd = $("input#pwd").val();
dataString = "id=" + id + "&pwd="+pwd;
$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
dataType: "json",
success: function( data, textStatus, jqXHR) {
if(data.success){
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<b>Welcome</b> " + data.login.id + "<br>");
//alert("#ajaxResponse" + data.login.id);
alert(data['id']);
alert(data['pwd']);
}
else {
$("#ajaxResponse").html("<div><b>Login Credentials are invalid!</b></div>");
}
}
});
I am getting the ajaxResponse if I am going with 1 element i.e 'id' but when I tried to get both the response I am getting value as undefined. I have tried with data.login.id & data[id] but unable to get desired output. Any help will be appreciated. Even I have tried with JSON.Stringify().
$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
...
This has data passed to ajax is not the same as the data in
success: function( data, textStatus, jqXHR) {
if(data.success){
...
In this success callback data is response from the server and it has a different (or same structure) based on data that server returns to you.
if you want to print the value from ajax call, you need to use just id
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
I see you are trying to use "data.login.id" can you check what is real structure of data in response? add console.log(data) or put breakpoint that callback, or simple add debugger; code, it will stop code in that line for you without adding breakpoint.
Thanks Alex. I will give you +1 for the line
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
Though it is working when I use:
data: {
id: $('#id').val(),
pwd: $('#pwd').val()
},
Without changing my code to this one the line was not working. Thanks for the suggestion.

Categories