AJAX/JS Syntax passing with arrays, Syntax Error - javascript

Background
I have a javascript code which passes three values dynamically into JSON for processing... After discussing a previous problem I had with a colleague, he has proposed that the best way to pass multiple variables into JSON would be to define them as an array in javascript, and then pass the object directly into the ajax/JSON. However, after a little trial and error coding, it appears the methodology is not being run correctly by the JSON processor. My question is as follows, in the following two examples, are they functionally the same, and if so, then why would the syntax fail.
Working Code
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'xyz.php',
type: 'POST',
data: {id : data_id, action: data_action, column: column},
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});
Not Working Code
/* old Syntax: */
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'xyz.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
alert("Information Passed Correctly");},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);}
});

The reason your non-working code is not working..
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObject["column"] = $(this).data('column');
dataObj["action"] = "get";
You create an object, dataObj - thats fine. You assign a property on dataObject (does not exist, you mean dataObject, but the JS interpreter does not know that), which for obvious reasons wont work.
Try this instead.
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["column"] = $(this).data('column');
dataObj["action"] = "get";

Related

Jquery not passing array via ajax

I am trying to send javascript array to php via ajax, but it is not sending, here is my code
var ArrayAmounts = new Array();
ArrayAmounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr:ArrayAmounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});
but when I am making array like this:
var ArrayAmounts = new Array();
ArrayAmounts[0] = "16150";
it is passing the array, but I want the key as alphanumeric.
please help.
So you don't need an array here, you'll need to use an object like this :
var Amounts = {};
Amounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr: Amounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});
Your problem is related to the kind of data you are sending because as the documentation says:
"It is converted to a query string, if not already a string. It's
appended to the url for GET-requests. Object must be Key/Value
pairs. If value is an Array, jQuery serializes multiple values with
same key based on the value of the traditional setting"
Official documentation for more details
you can declare the array like this:
var ArrayAmounts = new Array();
ArrayAmounts = ["16150"];
and then your ajax call work normally
Use like this
var ArrayAmounts = {};
ArrayAmounts.P1 = "16150";
var dataArray = {Arr: ArrayAmounts};
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data: dataArray ,
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
});

Assigning JSON value to a Variable that Resides Outside JavaScript Function

I have a question regarding JSON Web Services and AJAX Function. I have declared a JavaScript Function below.
function setJsonSer(){
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
alert("This is Set JSON In "+JSON.stringify(data));
}
});
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
data: formData,
complete: function(data) {
alert("This is Get JSON Out "+JSON.stringify(data));
}
});
}
As you can see I have alert the JSON.stingify(data) statement and it gave me the result as I expected.
Now I want to get that JSON response out of that particular function SetJsonSer() to assign to avariable that resides out side the SetJsonSer() function.
I already tried return JSON.stringify(data)) and JSON.stringify(data) statements but they did not put the result out from the SetJsonSer() function.
The output must grab from a variable like the below.
function Load(){
//-----------------------------------------------
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
This variable will be used as the query to draw a chart using HighCharts. So could you someone give me a clue how to get the result of the SetJsonSer() function?
Thanks and regards,
Chiranthaka
You're getting a bit mixed up with asynchronous nature of AJAX.
The AJAX event is being fired, but it won't be causing any pause in the execution of your code, as such, you need to implement a callback.
This code isn't particularly nice, but it should give you an idea of how the data needs to be handled.
function setJSONSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
console.log("Successfullly set JSON!");
getJSONSer();
}
});
}
function getJSONSer()
{
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
complete: function(data) {
//alert("This is Get JSON Out "+JSON.stringify(data));#
Load(data);
}
});
}
function BeginLoad()
{
setJSONSer();
}
function Load(data)
{
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
}
BeginLoad();

how to print values in array of deferred objects?

I have the following requests:
var req1 = $.ajax({
type: "GET",
url: url,
dataType : "xml"
});
req1.done(function (resp1) {
$(resp1).find('interest').each(function() {
var interest_id = $(this).find('id').text();
var interest_name = $(this).find('name').text();
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
});
requestsArray.push(request);
});
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
});
But when i get inside of
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
I dont know how to reach the individual responses in requestsArray. how can i do that? i have tried and tried but nothing seems to work.
You can use the arguments object to access an unknown number of values passed to a function:
$.when.apply($, requestsArray).done(function(){
console.log(arguments); //plain arguments object
console.log([].slice.call(arguments)); //arguments turned into real array
});
See MDN docs on the arguments object
Since you are pushing $.ajaxs into your array you might consider getting rid of the additional arguments they will pass like:
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
}).then(function(data, textStatus, jqXHR){
return data; //this will make sure textStatus and jqXHR aren't passed any further
});

Jquery AJAX function - how can I use a variable for JSON?

I want to be able to supply the JSON variable name and its value via variables, instead of hard-coding it:
data: {
inputVar : inputVal
},
but doing it like that and defining
inputVar = 'myInputVar';
doesn't work, instead entering the POST variable name directly only works:
'myInputVar' : inputVal
In the end, what I'd like to accomplish is to create a function that allows me to just call it to make an AJAX call in the JSON format, by supplying the JSON formatted AJAX variable and value in the function call:
makeAjaxJsonCall(fileName, postVar, postVal) {
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: {
inputVar : inputVal
},
success : function(data) {
.
.
.
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
.
.
.
}
});
}
Any ideas?
PS. I really don't know too much about JavaScript programming, so please be precise with full code when replying - thanks!
Do you want something like this?:
makeAjaxJsonCall(fileName, postVar, postVal) {
var data = {};
data[postVar] = postVal;
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: data,
success : function(data) {
.
.
.
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
.
.
.
}
});
}
You can set object values like this.
var obj = {};
//This is the same as...
obj.value1 = 'one';
//This...
var varName = 'value1'
obj[varName] = 'one';
A small explanation of the last two answers:
You can define elements of an object in this way:
var myObj = {};
myObj.element = 1;
// And using a variable just like you want:
var key = 'myKey';
myObj[key] = 2;
console.log(myObj.key); // 2
So, you can build your data object first, and then pass it to the ajax hash:
// ...
var myData = {};
myData[inputVal] = 'my value';
//...
makeAjaxJsonCall(fileName, postVar, postVal) {
$.ajax({
type : 'POST',
url : fileName,
dataType : 'json',
data: myData, // <-------------
success : function(data) {
// ...
Hope this helps.
Regards.

Invalid JSON Primitive when using a variable

I have code that makes an AJAX call to an MVC controller method and it'll work without a hitch if I do this:
var obj = '{"titlename":"whatever"}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
But if I do this:
var stringed="whatever"
var obj = '{"titlename":stringed}';
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
It craps out on me with an "invalid JSON primitive" error. I keep trying various single and double quote permutations, but they all keep giving me the same error. How can I insert a string variable into a JSON object?
Try this:
var stringed = "whatever";
var obj = '{"titlename": "' + stringed + '"}';
Also you may want to take a look at a JSON2 library, which can stringify your data automatically.
Why are you declaring your object as a String?
Have you tried doing:
var stringed="whatever";
var obj = {
"titlename":stringed
};
var obj = {"titlename":stringed};
This is probably what you need.
Try this:
var stringed="whatever";
var obj = {"titlename": stringed};
$.ajax({
type: "POST",
url: "/Titles/Yo",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: obj,
success: function (result) {
$("#title_field").html(result.TitleName);
}
});
What you had was just a string that contained the the string "stringed", you need a object literal.
jQuery can take an object and it'll take care of sending the json string to the server instead.
You should do:
var stringed="whatever";
var obj_as_object = {titlename: stringed};
var obj_as_string = JSON.stringify(obj_as_object);
...
data: obj_as_string //This goes in your ajax call
With this, we're auto encoding the obj with JSON.
JSON.stringify will work in modern browsers. If you want support to an older browser (for example, IE6) you should use a library such as json2 from http://json.org.
Hope this helps. Cheers
This isn't a great way to do it but..
var stringed="whatever"
var obj = '{"titlename":'+stringed+'}';
Or
var obj = {
"titlename":stringed
}

Categories

Resources