I can't convert my ajax $.get to $.ajax - javascript

I try to convert an ajax function that I do not understand. Here the original function :
$.get(page, function (data) {
$('.former-students__list').append(data.student
$('#load-more').data('next-page', data.next_page);
})
I'd like to convert it to make it more readable (with $ .ajax), So I could clearly see the events success, and so on.
Here is what I tried but it doesn't work
$.ajax({
url: page,
data: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
'success': 'Cool, it's work')
},
Thank you for your help and your explanations

The issue is because the data parameter should be an object, a string or an array which you use to send data to the server. However, given your $.get sample, you don't actually need to use it in $.ajax at all.
Instead, the success property should be a function which receives the data back from the request and then acts on it. Try this:
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
})
});
For more information, please read the jQuery $.ajax documentation.

Try this:
$.ajax({
url: page,
success: function (data) {
$('.former-students__list').append(data.students);
$('#load-more').data('next-page', data.next_page);
}
})
I think the data property is for POST request payloads.

you should fire the success callback event so try this :
$.ajax({
url: page,
success: function(data) {
$('.former-students__list').append(data.students);
$('#load`enter code here`-more').data('next-page', data.next_page);
}
});

Related

PHP Form submit get return value to html [duplicate]

I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.

Promise and callback function in ajax, when does success take place ?

Right now I have a code like this:
$.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
});
If I am not mistaken, checkAgainstDBHelperWH is known as a callback function. The function executes once the servers sends back response for this particular HTTP /ajax request.
I want to try writing something like the one below, but I don't know what are the effects or is it even logical:
var request = $.ajax({
url: apiUrl + valueToCheck,
data: {
format: 'json'
},
error: function () {
},
dataType: 'json',
success: function (data) {
checkAgainstDBHelperWH(data, valueToCheck);
},
type: 'GET'
})
arrayOfPromises.push(request);
$.when.apply(null, arrayOfPromises).done(function () {
//...some javascript here
});
I want to understand if the .done(function () is fired after the callback function checkAgainstDBHelperWH is completed? Or whatever I am trying to write above does not flow consistently with how ajax works?
Thanks!
I tested it, your code only work if the function(in this case, 'checkAgainstDBHelperWH') doesn't call ajax.
If you want to wait finishing the inner ajax process, use then() and return inner ajax.
var ajaxs =
$.get("xxx").then(function() {
return $.get("yyy").done(function() {
});
});
Here is the jsfiddle.
I'm not sure whether this way is general or not.

jquery unable to access function parameter inside function with an ajax call?

hitUrl = function (searchUrl, nbCity) {
$.ajax({
context: this,
type: 'GET',
headers: { "sourceid": "1" },
url: '/webapi/xyz/abc/?' + searchUrl,
dataType: 'text',
success: function (json) {
D_usedSearch.similarCars.showSimilarCarLink(searchUrl);
});
When i put breakpoint on 1st line of success of this jquery success callback, i am unable to access 'searchUrl' in console. It is undefined.
How do i access this?
That's probably because Ajax is asynchronous: the code from the function is executed parallel from the code in the ajax call.
Take a look to this answer for the solution to your problem.

Calling a Success script if #Ajax call succeed

I have the following javascript which contains an ajax call:-
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected"),
data: { ids: boxData.join(",") }
})
});
but is there a way to call a javaScript function is the above Ajax call succeed?
Thanks
function mySuccessFunction() {
alert('success');
}
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected")',
data: {
ids: boxData.join(",")
},
success: function(data) {
// your code if AJAX call finished successfully
// call your function that already loaded from here:
mySuccessFunction();
// you can also process returned data here
}
});
You have three particular handlers you can use to process information returned with AJAX, .success(), .done(), and .fail(). With these methods, your code might look something like this:
$.ajax({
type: "POST",
url: '#Url.Action("DeleteSelected"),
data: { ids: boxData.join(",") }
}).success(function(data) {
// This callback is executed ONLY on successful AJAX call.
var returnedJSON = data; // The information returned by the server
yourSuccessFunction();
}).done(function() {
// This callback is ALWAYS executed once the AJAX is complete
yourDoneFunction();
}).fail(function() {
// This callback is executed ONLY on failed AJAX call.
});
Also see: jQuery AJAX Documentation

How to pass parameters in GET requests with jQuery

How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];

Categories

Resources