AJAX: How to use returned array? - javascript

I have an ajax POST that sends data to a controller function and that function returns a string array back to the ajax call as the default 1st parameter in the ajax success method. When I tried to use the returned data, it won't let me print the 1st element to an alert box. How come?
i.e.
$.ajax(
{
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
success: function (response)
{
alert(response[0]);
}
});
In fact, I don't think it even recognize it as a string array.

You need to specify dataType. Read more here.
$.ajax({
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
dataType: 'json',
success: function (response)
{
alert(response[0]);
}
});

Looks like the data is being returned as a raw sting.
Use dataType property for your ajax request
dataType: 'json'
Also avoid using alert as it stops the execution flow. Use console.log instead

Related

AJAX request sometimes out of order

I'm having trouble with POST and GET request. On my server side right up until the moment before I send I have what I expect but then on my client side I get things out of order. For example these two should be in the reverse order I have here:
Sending from server{"grid":["","","","","","","","",""],"winner":""}
Received at server: {"grid":["X","","","","","","","",""],"winner":""}
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
gives me:
Also after receiving {"grid":["X","","","","","","","",""],"winner":""}
Receved at client: {"grid":["X","O","","","","","","",""],"winner":""}
I think this may two different problems. One for getting things out of order and another for why my grid doesnt reflect the changes after my success clause function in my GET request.
You're making a common mistake. You need to use a function reference without the parens here for receiveData. Change this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData()
});
}
to this:
function sendData(json) {
$.ajax({
type: "POST",
url: "/ttt",
data: json,
dataType: "json",
success: receiveData // no parens here
});
}
When you include the parens, it calls the function IMMEDIATELY and puts the return value from the function as the success handler and thus you see them run out of order. You want to pass a function reference to it can be called later. A function reference is the function's name without the parens.
It also appears like you have another mistake in receiveData(). You are using the wrong thing for the response. The response is not returns from $.ajax(). The response is passed to the success handler.
I don't know exactly what your response is supposed to look like, but change this:
function receiveData() {
var response = $.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(){
grid = response.responseJSON;
console.log("Receved at client: " + JSON.stringify(grid));
}
});
console.log("Also after receiving " + JSON.stringify(grid));
}
to something like this:
function receiveData() {
$.ajax({
type: "GET",
url: "/ttt",
dataType: "json",
success: function(response){
grid = response.responseJSON;
console.log("Received at client: " + JSON.stringify(grid));
console.log("Also after receiving " + JSON.stringify(grid));
}
});
}
And, because your ajax calls are asynchronous, you also had this statement console.log("Also after receiving " + JSON.stringify(grid)); in the wrong place. If you want to see the results of the grid after you've modified it, then you have to put that inside the success handler.
Summary of Fixes
Change success: receiveData() to success: receiveData.
Use response as it is passed to the success handler.
Put console.log() to see final results inside the success handler.
It appears that you may not fully understand how ajax calls are asynchronous and what that really means for your programming. I'd suggest doing some searching and reading on that topic. Learning that now will save you a lot of agony as you develop.

value missing on AJAX response

I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';

Submitting a form using jQuery and Ajax changing the action

I have a form, which I am trying to submit using jQuery and AJAX. I am triggering the submit by clicking on a link, which I've added an onclick method. Below are two code samples to submit the same form - the first works, but isn't AJAX, while the second method gives me a 404 error.
function submitmyform(formid) {
$(formid).submit();
}
The second example attempts to use AJAX, given the same parameters:
function submitmyformajax(formid) {
$.post({
type: "POST",
url: $(formid).attr('action'),
data: $(formid).serialize(),
success: function(data) { alert(data); }
});
}
An alternate way I tried with the submitmyformajax is:
function submitmyformajax(formid) {
$.post({
type: "POST",
url: 'somehardcoded/url',
data: $(formid).serialize(),
success: function(data) { alert(data); }
});
}
For some reason, this continues to give me a 404 error, though the action on the form is correct (the URL it shows me is not the same as the action on the form).
I checked the error console, and it shows the 404 error as pointing to somehardcoded/[object%20Object] instead of what I specified in the method.
What am I doing wrong?
I think you are getting $.post and $.ajax mixed up. $.post is short hand for $.ajax, as such takes a string url as first parameter, an object as the data, and a function as the callback. $.ajax on the otherhand takes an object as configuration, as you are doing
i.e. Post signature is
$.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
which is shorthand for
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
You seem to be using a mixture of both, and hence getting strange behavior, as it is calling toString on the first parameter you are passing in to the $.post which is [object Object] and then that is url encoded to [object%20Object]
Either use
$.post($(formid).attr('action'),
$(formid).serialize(),
function(data) { alert(data); })
or
$.ajax({
type: "POST",
url: $(formid).attr('action'),
data: $(formid).serialize(),
success: function(data) { alert(data); }
});
use this instead..
$.post(
'somehardcoded/url',
{data:$(formid).serialize()},
function(data) {
alert(data);
}
);

jQuery .ajax call never calling method

In this SO post I learned how to get a return value from an AJAX call:
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
This function calls its web service wich does return true. The problem is that inside the following callUpdateGrid, the logging shows that that web service method is not getting called from the $.ajax call:
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
Anyone know what is wrong?
It is always a good idea to include an error handler function as one of the options passed to $.ajax. For example, add this code after your success functions:
,
error: function(jqXHR, textStatus, errThrown) {
console.log("AJAX call failed");
console.log(errThrown);
}
That will log at least a bit of information if the $.ajax call doesn't succeed.
EDIT
According to your comment, this logs
SyntaxError: Invalid character
And in fact, I now see that you are giving a plain JavaScript object as the data option passed to $.ajax, but indicating that it is a JSON object in the dataType field. You need to actually convert the input object into JSON yourself, like so:
data: JSON.stringify(input),
dataType: 'json',
Alternatively, you could simply format input as a JSON object in first place, like so:
var input = { "requestGUID": "<%=guid %>" };
The quotes around the field name requestGUID are sufficient, in this case, to give you a JSON object.

How do I access a returned value from a .ajax request within the done() function

Here's my function which returns a name of a person.
function getName(ID){
return $.ajax({
url:url,
data: ID,
type: 'get',
dataType: 'json'
});
}
And here is where I am attempting to use the .done() function.
getName("1").done() // How do I ref the returned var in our done function?
I am confused on how to reference the returned value from my getName function within my done function.
I know I could do this using success: within the .ajax, but I am trying to move away from that and used deferred objects.
Thanks!
it look slike done requires a callback function that takes a parameter with the data recieved from teh request.
http://api.jquery.com/jQuery.ajax/
getName("1").done(function(response) {
alert(response);
});
It's right there in the documentation:
//Example: Save some data to the server and notify the user once it's complete.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
//Example: Retrieve the latest version of an HTML page.
$.ajax({
url: "test.html",
cache: false
}).done(function( html ) {
$("#results").append(html);
});
Also, make sure you read this, because, depending on the Datatype you might actually "receive" not a simple string/id but possibly an object parsed from a JSON/XML result or...

Categories