Passing in parameters to promise.done() after AJAX call - ajax

I know there are lots of AJAX questions out there, but after reading through them wasn't able to figure out how to do this (I'm new to JS)
Pass in the $form variable (or other variables) to the ajaxFormSubmitSuccess function, in addition to the "data variable" that gets returned by the ajax call (which you could access by .done(function(data){}); ...not really sure what type of object it is).
I have (this doesn't work):
//handles ajax form submissions
$("form[data-ccajax='true']").submit(ajaxFormSubmit);
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
context: this,
data: $form.serialize(),
dataType: "html"
};
//send ajax command
var promise = $.ajax(options);
promise.done(ajaxFormSubmitSuccess($form, promise));
promise.fail(ajaxFormSubmitFailure);
return false;
}
Right now the .done(ajaxFormSubmitSuccess($form, promise)); code calls the function below. the data variable doesn't get extracted from promise...so $data remains null throughout the code.
var ajaxFormSubmitSuccess = function ($form, $promise) {
var $data;
$promise.success(function (data) { $data = data; });
alert("succeededajaxFormSubmit");
var target1 = $("#"+$form.attr('data-cctarget1'));
target1.html($data);
}
Any help on how to do this right is much appreciated!

$promise inside the ajaxFormSubmitSuccess is not the result of the ajax call but a promise. It's async so that's why your variable $data is still empty after $promise.success().
Try this way:
var ajaxFormSubmitSuccess = function ($form, $promise)
{
$promise.success(function (data)
{
alert("succeededajaxFormSubmit");
var target1 = $("#"+$form.attr('data-cctarget1'));
target1.html(data);
});
}
For more insights: https://api.jquery.com/promise/

Related

Django: correct way to pass AJAX

I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.

zf2 and ajax I can't get the parametrs

I can not get the data passing from the controller ajax me there any solution?
button click action
$(".bajaAlumno").click(function () {
var urlform = "<?php echo $this->url(null, array('controller'=>'Academius','action' =>'bajaAlumnos' ) ); ?>";
var dato= $(this).attr('id');
var myData = {textData:dato};
$.ajax({
type:"POST",
url:"/Academius/bajaAlumnos",
data:{data:myData},
success: function(data){
//The callback function, that is going to be executed
//after the server response. data is the data returned
//from the server.
// Show the returned text
//$("#answer").text(data.text);
//$("#answer").text(data.text);
alert('enviado');
}
});
});
and controller
public function bajaAlumnosAction()
{
die(var_dump($this->params()->fromPost()));
}
one answer?

how to get the values passed into an ajax post

Here is my codes,
function getMods(name){
var init;
$.ajax({
type: "POST",
url: "init.php",
data: { 'id': getID(), 'Name': name },
cache: false,
success: function(data)
{
return data;
},
async:false
});
}
function init(){
var gm = '<br/>';
var gm1 = getMods('Name');
$('#brand').append(gm1);
var gm2 = getMods('Owner');
var gm3 = getMods('Admin1');
var gm4 = getMods('Admin2');
var gm5 = getMods('Admin3');
var gm6 = getMods('Admin4');
$('#online3').append(gm2 + gm + gm3 + gm + gm4 + gm + gm5 + gm + gm6 + gm);
}
The getMods() returned "undefined". When i use this code:
alert(data);
The page alerted the correct values.
Here is the php file init.php:
<?php
include('dbconnect.php');
if(isset($_POST['id']) && isset($_POST['Name'])){
$id = $_POST['id'];
$name = $_POST['Name'];
$init = chatMods($name,$id,$username,$password);
echo $init;
}
?>
And I add the async in the getMods().
You should make the distinction between a return value of a function (getMods() in your case) and a callback function (success).
In your code, you call getMods() which in fact doesn't return any value, hence you get undefined.
The success callback happens only after a while, after your function had already returned.
One possible solution for you (though not the greatest because it locks your JS processing) is to use an Ajax call in a synchronous way. A call that only returns when an answer from the server has been received. Use async: false in your $.ajax call, capture your return value and then return it. See this example: https://stackoverflow.com/a/2592780/290343
You should be aware, of course, that your Ajax calls might fail and you need to take that into account. Also, your code might run really slow because it does 6 remote calls to a server.

How to populate array with data returned from ajax call?

I'm making a call to an app to fetch data (routes), then looping through that data to fetch additional data about each individual route. The final data will show up in console.log without a problem, but I can't get it into an array.
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var routes = [];
$(data).each(function(i){
routes.push(data[i]._id);
});
function getRouteData(route, callback) {
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json',
success: function(data) {
callback(data);
}
});
}
var route_data = [];
$(routes).each(function(i) {
getRouteData(routes[i], function(data) {
console.log(data); // this shows me the 13 objects
route_data.push(data);
});
});
console.log(route_data); // this is empty
});
nnnnnn's right, you have to use Deferreds/promises to ensure that route_data is populated before sending it to the console.
It's not immediately obvious how to do this, with particular regard to the fact that $.when() accepts a series of discrete arguments, not an array.
Another issue is that any individual ajax failure should not scupper the whole enterprise. It is maybe less than obvious how to overcome this.
I'm not 100% certain but something along the following lines should work :
$.getJSON('http://example-app/api/routes/?callback=?', function(data) {
var route_promises = [];
var route_data = [];
function getRouteData(route) {
var dfrd = $.Deferred();
$.ajax({
url: 'http://example-app/api/routes/'+route+'?callback=?',
dataType: 'json'
}).done(function(data) {
//console.log(data); // this shows me the 13 objects
route_data.push(data);
}).fail(function() {
route_data.push("ajax error");
}).then(function() {
dfrd.resolve();
});
return dfrd.promise();//By returning a promise derived from a Deferred that is fully under our control (as opposed to the $.ajax method's jqXHR object), we can guarantee resolution even if the ajax fails. Thus any number of ajax failures will not cause the whole route_promises collection to fail.
}
$(data).each(function(i, route) {
route_promises.push( getRouteData(route) );
});
//$.when doesn't accept an array, but we should be able to use $.when.apply($, ...), where the first parameter, `$`, is arbitrary.
$.when.apply($, route_promises).done(function() {
console.log(route_data);
});
});
untested
See comments in code.

Retain the context of JQuery ajax function

I have an old code which is dependant on JQuery 1.3.2 that uses the following ajax call
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
context: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.context[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Problem with the code above is that this.callback is null when I upgraded to JQuery 1.8.1, most importantly the ChangeContent function is being used in different places and is outside my control (its used as as an API for external users...etc). An example of the usage of the above is like this:
xhr_object = ChangeContent("/someurl, $("#resultContainer"));
function doFurtherStuff(responseText, statusText, XMLHttpRequest)
{
var identifier = '#' + this.id;
...
}
Notice that the doFurtherStuff must have the correct "this" object value which is the context specified in ChangeContent function. When I tried to use different deferred then() ...etc. functions in JQuery 1.8.1 to solve the above this.callback.call(this.context[0], data); problem after the upgrade the "this" object in the callback function had different value since I guess the new JQuery library handles that differently.
Is there anyway to fix the error above while limiting the change to ChangeContent function only as I try to avoid asking all users to change the way they call and handle call backs from that function?
When you add the context option, you are telling jQuery what this should be inside of the success callbacks. That means you can't access the options passed into the ajax request. Either don't supply a context, or pass in the callback manually.
function ChangeContent(url, somepageobject) {
var callback = doFurtherStuff;
var xhrobj = $.ajax({
url: url,
context: somepageobject,
success: function(data) {
somepageobject.html($(data));
callback.call(this[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Update:
If you want to instead continue using your code as-is, simply rename the context property.
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
thecontext: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.thecontext[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}

Resources