Javascript/jQuery set variable to object property for multiple $.ajax calls - javascript

I am looking to send a number of different queries via $.ajax as JSON.
I have stored these queries in an object using the following:
var objectName = {
"name1": {
"queryName": "longname1",
"queryAction": "JSONtoSend"
},
"name2": {
"queryName": "longname2",
"queryAction": "JSONtoSend"
},
};
I am then going through the queryActions and setting them:
for (var i = 0, len = Object.keys(objectName).length; i < len; ++i) {
var indexName = Object.keys(objectName)[i];
objectName[indexName].queryAction = "";
var JSONtoTransfer = objectName[indexName].queryAction;
}
$.ajax({
type: "POST",
url: 'URL',
data: JSONtoTransfer,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(dataReturn){
alert(dataReturn.blah);
}
});
I am unable to set the var JSONtoTransfer. It gives me an unexpected [ error. How do I get around this? I get the same error if I enter it straight into the data parameter of $.ajax.
The code I am using is storing the queries in the object correctly, but I need a way to iterate through them all and send via $.ajax.
Thank you for the help. This code is probably not the most efficient way of doing things, so if anyone has any advice, it's more than welcome too :-)
So I wrote the original code wrong, the $.ajax call should be included in the for statement. So it actually iterates....
Anyway, what I found to work was creating an array, pushing the queryAction into it and then stringifying it...

Few problems:
JSONtoTransfer is out of scope of your ajax call. If you want to populate JSONtoTransfer on every iteration and make an ajax request with this different value each time - put the ajax call inside the for loop (although I would seriously consider refactoring this so that you make one ajax call, and deserialize it differently (if it's your server-side code handling it))
You're setting objectName[indexName].queryAction to an empty string, then assigning this value to JSONtoTransfer (now always going to be an empty string)
You have your for syntax a bit muddled up. Best practice would be to change
for (var i = 0, len = Object.keys(objectName).length; i < len; ++i) {
to
for (var i = 0; i < Object.keys(objectName).length; ++i) {
i.e. there's no need to keep initialising len to the same value. NOTE: This is more for readability, not (so much) performance. If you had another use for len inside the loop this advice wouldn't apply.

Your variable objectName is in fact JSON data already. I might be wrong but I think this should work (with less code):
var jsonData = {
"name1": {
"queryName": "longname1",
"queryAction": "JSONtoSend"
},
"name2": {
"queryName": "longname2",
"queryAction": "JSONtoSend"
},
};
//Post with AJAX
$.post('url.php', jsonData, 'json')
.done(function(data) {
alert('Succes!')
})
.fail(function(data) {
alert('Failed!')
});
//This does the same (Post with AJAX)
$.ajax({
url: 'url.php', //Get action attribute of the form
type: "POST",
data: jsonData,
dataType: "json",
.done(function() { //or success: function() {
alert( "success" );
})
.fail(function() { //or error: function() {
alert( "error" );
})
.always(function() { //or beforeSend: function() {
alert( "complete" );
});
});

I am not sure what you want but as pointed out by others there are many issues with your code, but i think you want to execute ajax call one after the other iteratively. if that is what you want then take a look at jQuery deffered -docs are here.Hope that helps

Related

Multiple ajax calls fired simultaneously not working properly

I created a site which load every few seconds data from multiple sources via AJAX. However I experience some strange behavior. Here is the code:
function worker1() {
var currentUrl = 'aaa.php?var=1';
$.ajax({
cache: false,
url: currentUrl,
success: function(data) {
alert(data)
},
complete: function() {
setTimeout(worker1, 2000);
}
});
}
function worker2() {
var currentUrl = 'aaa.php?var=2';
$.ajax({
cache: false,
url: currentUrl,
success: function(data) {
alert(data)
},
complete: function() {
setTimeout(worker2, 2000);
}
});
}
The problem is that many times, one of the workers returns NaN. If I change the frequency of calls for, lets say, 2000 and 1900, then everything is working ok and I got almost no NaN results. When those frequencies are same, I get over 80% NaN results for one of the calls. It seems like the browser cannot handle two requests called at exact same time. I use only those two workers, so the browser shouldn't be overloaded by AJAX requests. Where is the problem?
Note that the aaa.php works with the mySql database and do some simple queries base on parameters in url.
All you need is $.each and the two parameter form of $.ajax
var urls = ['/url/one','/url/two', ....];
$.each(urls, function(i,u){
$.ajax(u,
{ type: 'POST',
data: {
answer_service: answer,
expertise_service: expertise,
email_service: email,
},
success: function (data) {
$(".anydivclass").text(data);
}
}
);
});
Note: The messages generated by the success callback will overwrite
each other as shown. You'll probably want to use
$('#divid').append() or similar in the success function.
Maybe, don't use these workers and use promises instead like below? Can't say anything about the errors being returned though without looking at the server code. Below is working code for what it looks like you are trying to do.
This is a simple example but you could use different resolvers for each url with an object ({url:resolverFunc}) and then iterate using Object.keys.
var urls = [
'http://jsonplaceholder.typicode.com/users/1',
'http://jsonplaceholder.typicode.com/users/2',
'http://jsonplaceholder.typicode.com/users/3',
'http://jsonplaceholder.typicode.com/users/4',
'http://jsonplaceholder.typicode.com/users/5',
'http://jsonplaceholder.typicode.com/users/6',
'http://jsonplaceholder.typicode.com/users/7'
]
function multiGet(arr) {
var promises = [];
for (var i = 0, len = arr.length; i < len; i++) {
promises.push($.get(arr[i])
.then(function(res) {
// Do something with each response
console.log(res);
})
);
}
return $.when(promises);
}
multiGet(urls);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

Javascript value is returned from webservice but will not show unless a breakpoint is used

I have a javascript function that calls a web service. The data comeback (I see the Jason return in FireBug) the value is blank when I attempt to use it unless I set a break point. With a break point set the value can be used, without it is not available.
Here is a snippet of the offending call.
function getTheNote(noteCode){
var _myNote = "";
var theID = $('#CustNo').val();
var myDTO = { 'theID': theID, 'noteCode': noteCode, };
var toPass = JSON.stringify(myDTO);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "AR_Cust_Mgt.aspx/getNote",
data: toPass,
success: function (data) {
_myNote = data.d;
}
});
//setTimeout(_myNote += _myNote, 120000);
//for(var x = 0; x < 200000; x++){}
//return _myNote;
alert(_myNote);
}
Originally I was sending the value back to a calling function the return statement is where I would set my break point and the data would be returned, without nothing. Now you can see I attempted to use an alert inside the function with the same results.
With a break point I get a value without I get nothing, I have even attempted to use some delays.
Please help.
The ajax call is asynchronous. Anything you want to do with the result needs to be in your anonymous function success: function(data) { ... or the anonymous function needs to call other functions to do stuff.
As it is coded now, $.ajax will be called, the script execution continues on before the ajax call returns.
small change, big difference: you are not calling alert IN the succes function
success: function (data) {
_myNote = data.d;
alert(_myNote);
}

Prototype to jQuery conversion AJAX Syntax

Looking for some advice on whether my syntax is correct for this Prototype to jQuery conversion.
I have both frameworks loading at the same time and would like to convert all scripts to jQuery to reduce page load weight and speed.
Prototype
Looking to replicate this in jQuery:
if (snapshots.items.length < snapshots.total_entries) {
new Ajax.Request(snapshots.url, {
method: 'GET',
parameters: {
page: snapshots.current_page + 1,
per_page: snapshots.per_page
},
onSuccess: function(response) {
var start = snapshots.items.length;
snapshots.items = snapshots.items.concat(eval(response.responseText));
for (i = start; i < snapshots.items.length; i++) {
$('snapshots').appendChild(render_snapshot(snapshots.items[i].snapshot));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides.push($('slide_' + snapshots.items[i].snapshot.id));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides[i]._index = i;
}
snapshots.current_page++;
Photo.Filmstrip.currentSnapshot(currentSnapshot);
}
});
}
to jQuery
if (snapshots.items.length < snapshots.total_entries) {
$j.ajax({
url: snapshots.url,
data: {
page: snapshots.current_page + 1,
per_page: snapshots.per_page
},
success: function (response) {
var start = snapshots.items.length;
snapshots.items = snapshots.items.concat(eval(response.responseText));
for (i = start; i < snapshots.items.length; i++) {
$j('.snapshots').append(render_snapshot(snapshots.items[i].snapshot));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides.push($j('slide_' + snapshots.items[i].snapshot.id));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides[i]._index = i;
}
snapshots.current_page++;
Photo.Filmstrip.currentSnapshot(currentSnapshot);
}
});
}
Yes, this looks right - I know jQuery much better than Prototype, so I'm guessing a little, but it makes sense (assuming you've used $.noConflict to assign jQuery to $j). The only issue here, as #Greg pointed out in his comment, is the eval - I assume you're returning JSON data, so if you include the config option:
dataType: 'json'
jQuery will parse this automatically, in a way that's safer than a plain eval. In fact, I'm pretty sure that in most cases if you leave this option out, jQuery will sniff your response body and guess intelligently whether to parse it as JSON, XML, HTML, script, or text, in which case your eval would be unnecessary.

JavaScript auto-incrementing a variable in jQuery and AJAX

I have JavaScript using jQuery and AJAX which creates a dynamic array, which has some values used for AJAX request as below;
<script type="text/javascript">
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
var i = 0;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "testdata", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
i++;
}
</script>
The script is suppose to submit values in the array in array[i] for each AJAX request. I made a variable var i which auto increments.. But the script is not working.. The script works well if array[i] is replaced by array[0] or array[1] etc..
How can I solve the syntax error?
Every time you call updateBackground() i = 0 (again). May be you must initialize i outside of the function.
What happens if i > array.length? And I would rename the variable.
You don't have an iterator. Your variable i gets set to 0 every time the function runs. The increment at the end is useless.
Maybe you need something like this?
var array = Array("y","y","x","y","y","y");
function updateBackground(cellId, titleId) {
for( var i = 0; i < array.length; i++ ) {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
filename: Array(array[i], "<?php echo $dir; ?>", $("#"+titleId).html())
},
success: function(response){
$("#"+cellId).css("background-image", "url('pdfthumb/" + response + "')");
}
});
}
}
Each time you call updateBackground() function, the i variable is being reinitialized. It's just a local variable and as soon as the function finishes it's being destroyed by GC. You could do something like this:
var UpdateBackground = {
array: [..],
counter: 0,
doUpdate: function(cellId, titleId) {
// AJAX request
this.counter++;
}
};
UpdateBackground.doUpdate(1, 1);
UpdateBackground.doUpdate(1, 1);
I think that you should send the whole array maybe as a commaseparated string and instead and make just one ajax request, because http-requests are expensive and change the server side code accordingly. And fetch the cellids as an array.
If you think that you have a long list or a table it can be like a lot of requests. Do the stuff in client code and do the stuff in server code and keep the number of http-requests as few as possible.
And use the join method on the array.
var arr = [ 'y', 'y' ];
arr.join(',');
// outputs y, y
I fixed it... Thank you so much #Jed, #Pointy, #Crozin, and #Lord Vader for helping me to figure it out.... :)
I just take var i = 0; outside the loop.... above var array like;
var i = 0;
var array = Array("y","y","x","y","y","x");

Categories

Resources