Sorry this is a duplicate from here asked in SO but I'm new to this so I would like to know how to do it?
This is my ajax call:
$("#btnprocess").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetFilenames",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d[0]);
alert(response.d[1]);
}
});
});
Individually I'm able to get the response but I need to loop them.
Can anyone say me how do I do this?
You couldn't directly return an array from AJAX, it must have converted in the valid format. In this case, you can either use XML or JSON format. In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.
Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });
success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine. However, . complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - . complete() will still get called.
Use $.each()
.
$.each(response.d, function(key, value) {
//For example
console.log(key + value)
})
Look here to learn about it. (EDIT: Or here - it's a video tutorial if you prefer that.)
if response.d
is an array you could place it in a for loop like so:
for ( var i = 0; i < response.d.length; i++ ) {
// do action here
}
This method is preferred over the jQuery $.each()
function due to its speedier nature. Check out this Fiddle for a comparison of for
vs $.each()
.
You could do;
for (var i=0; i<response.d.length; i++) {
alert(response.d[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With