Return does not return Object - javascript

I've two javascript classes (Controller.js & Events.js).
From Events.js i call a XML Parser in Controller.js. The Parser works but does not return anything:
SceneEvent.prototype.handleKeyDown = function (keyCode) {
switch (keyCode) {
case sf.key.ENTER:
var itemList = null;
itemList = Controller.ParseXML("app/data/Event.xml");
alert("itemList = " + itemList);
}
};
Controller.js looks like that:
Controller.ParseXML = function (url) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
});
return itemList;
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
}
});
};
When I print out the itemList in Controller.js everything works fine.
Any suggestions?

You have to return the value at the end of the ParseXML function, not at the end of the success function.
Controller.ParseXML = function (url) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
});
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
}
});
return itemList;
};

You might want to consider making your ajax call async and add a callback to your ParseXML function. Something like this in event handler:
itemList = Controller.ParseXML("app/data/Event.xml", function(itemList){
alert("itemList = " + itemList);
});
And in ParseXML:
Controller.ParseXML = function (url, callback) {
var itemList = null;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
async: true,
success: function(xml) {
$(xml).find("event").each(function() {
var _id = $(this).attr("id");
var _eventItemDay = $(this).find("eventItemDay").text();
...
var _eventItemLocation = $(this).find("eventItemLocation").text();
itemList = {
id: _id,
eventItemDay: _eventItemDay,
eventItemLocation: _eventItemLocation,
...
eventItemLocation: _eventItemLocation
};
callback( itemList );
});
},
error: function(xhr, ajaxOptions, thrownError){
alert("XML ERROR");
alert(xhr.status);
alert(thrownError);
callback( "XML ERROR " + xhr.status + " " + thrownError );
}
});
};
You'll want to check the value in the callback for errors of course.

Related

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

Calling ajax request after page redirect

How to call ajax request after page redirecting? I'm trying with setInterval function, but it doesn't work.
$("#list").on('click', 'tr', function () {
var data = table.row( this ).data();
var id = data[0];
var url = 'redirect.html?=id';
window.location.href = url + id;
return false;
var getRequest = setInterval (function(id) {
$.ajax({url: "/list?id=" + id,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
error: function (xhr, status) {
alert(status);
},
success: function (listsdata) {
oTable = $('#table2').DataTable({
data: listsdata,
columns: [
{ title: "Column1" },
{ title: "Column2" },
]
});
}
});
}, 3000);
});
getRequest() method cannot be executed

jquery Ajax doesn't show any message(neither success nor failure)

I want to submit a form with jquery Ajax. But it does not show any kind of message. I have followed this question and this question. But I didn't get my solution. My jquery code is:
$(document).ready(function () {
$("#btnSave").submit(function (e) {
e.preventDefault();
var myTableArray = [];
$("table#vouchTable tr").not(':first').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
}); ///This Part works fine
///But this part does not work
$.ajax({
url: '/Accounts/VoucherEntry',
type: 'POST',
data: JSON.stringify(myTableArray),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
////////////////////
});
});
Try this:
Missing end brackets for : $(document).ready(function () {
Missing end brackets for : $("#btnSave").submit(function (e) {
$(document).ready(function () {
$("#btnSave").submit(function (e) {
e.preventDefault();
var myTableArray = [];
$("table#vouchTable tr").not(':first').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var data = JSON.stringify(myTableArray);
$.ajax({
url: '/Accounts/VoucherEntry',
type: 'POST',
data: data,
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}); // <----- Missing brackets!!!
}); // <----- Missing brackets!!!
Format you data like:
data: {data:myTableArray},
in c# get the data by the key data

JSON Post to API

I am trying to make a JSON Post to the Simpleconsign API, and I keep receiving a 0 error from the browser. Here is my code:
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
type: 'POST',
key: "apikey,
url: 'https://user.traxia.com/app/api/inventory',
contentType: "application/json",
success: function(result){
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
I am a beginner at posting to the REST API's, so any help would be much appreciated. Thank you!
I don't see any data in your Ajax POST? This code should have work
var postData = {
"key": "Your API Key Here",
"query": "some query",
"consignorId": "123456",
"includeItemsWithQuantityZero": "false"
};
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
type: 'POST',
data: postData,
url: 'https://user.traxia.com/app/api/inventory',
contentType: "application/json",
success: function(result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
http://wiki.traxia.com/display/guide/List+and+Search+Inventory

Error unexpected token when posting JSON string to JSP

Here's my code:
var polylineStringified = JSON.stringify(polyPath.getArray());
$.ajax({
type: 'POST',
url: 'jsonposttest.jsp',
data: { Polyline: polylineStringified },
dataType: 'json',
success: function(json) {
alert('json from post test: ' + JSON.stringify(json));
}, error: function(xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
And serverside:
<%
String test;
test = getRequest(pageContext, "Polyline");
response.setContentType("application/json");
%>
[
{"val": "Got it: <%=test%>" }
]
polylineStringified looks something like this:
[{"d":41.919372021888826,"e":-87.69811456091702},{"d":41.90506457136218,"e":-87.23119561560452},{"d":41.80277524389252,"e":-87.23668877966702},{"d":41.74747099702249,"e":-87.35479180701077}]
And the error I'm getting in the console is is unexpected token d. Any ideas?
I think you are unnecessarily stringifying your javascript object. What happens if you use the following?
var polylineArray = [{
"d": 41.919372021888826,
"e": -87.69811456091702
}, {
"d": 41.90506457136218,
"e": -87.23119561560452
}, {
"d": 41.80277524389252,
"e": -87.23668877966702
}, {
"d": 41.74747099702249,
"e": -87.35479180701077
}];
$.ajax({
type: 'POST',
url: 'jsonposttest.jsp',
data: { Polyline: polylineArray },
dataType: 'json',
success: function(json) {
alert('json from post test: ' + JSON.stringify(json));
}, error: function(xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
});
EDIT: Here's another example, which you can try at jsFiddle.
It should be quite straightforward, so you can compare it to yours at each step to find what is wrong in your situation.
jQuery(document).ready(function ($) {
var Q = function (d, e) {
this.d = d;
this.e = e;
}
var data = [];
for (var i = 0; i < 5; i++) {
var r1 = 100 * (2*Math.random() - 1);
var r2 = 100 * (2*Math.random() - 1);
data.push(new Q(r1, r2));
}
console.log("About to send data", data);
$.ajax({
type: 'POST',
url: '/echo/json/',
data: {
Polyline: data
},
dataType: 'json',
//processData: false,
success: function (data, textStatus, jqXHR) {
console.log("success", data, textStatus, jqXHR);
//alert('json from post test: ' + JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error", xhr, ajaxOptions, thrownError);
//alert('Error xhr : ' + xhr.status);
//alert('Error thrown error: ' + thrownError);
}
});
});

Categories