I have a jQuery ajax function. the callback function consists of two functions:
1) Take the ajax result (which is an html form) and insert it as an html span's inner html.
2) Submit this form
How can I ensure that the form is loaded before JavaScript tries to submit it?
Code:
$("select").live("change", function(){
FormUpdate();
})
function FormUpdate() {
$.ajax({
type: "POST",
url: "index.php?UpdateForm=Yes",
data: $("#Form").serialize(),
success: function(msg){
$("span#Content").html(msg);
$("#Form").submit();
}
});
}
My problem comes because javascript tries to submit the form before it has loaded and my data submitted.
Just simply put the function for taking ajax result and insert into the DOM in front and the form submission function at the back.
Only after insertion is done, the next function will be called.
Example:
$.ajax({
type: "POST",
url: "backend.php",
data: "name=John",
dataType: "json"
success: function(msg){
$("#thediv").html(msg.html);
$("form#theform").submit();
}
});
DOM manipulations are synchronous so the form wont be submitted until afterwards. Are you having a specific problem with this scenario? Please post tons of code, if so :)
Related
I have a normal button, which triggers a basic function that prints the value of an element in my HTML to the console.
Now, instead of printing the value of that element i want to send it to my Django view with a POST request.
Here is the function:
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
console.log(myvalue);
});
Here, instead of printing that value, i want to send myvalue with a post request using Ajax.
I know how to do a POST request, the only difference is that this time, instead of using a form, i'm using a single button to trigger the request, and i'm not really used to that.
Here is how i would do it with a form:
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': $('id').val()
},
});
return false;
});
});
So, basically i just need to know how to integrate this piece of code inside the first function, so that the Ajax call is triggered not by the form (as it is in the second code) but from a button.
Just put your jquery ajax function inside into the click event function.
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': myvalue
},
});
});
Hope this will help.
I've got 3-4 ajax calls that will be made at some point.
For one of those calls I'd like to trigger a function on the ajaxSend event which is global. This specific ajax call is not necesserily the first or last one in the sequence. It seems that if I attach the ajaxSend event to the $(document), my function will fire every other time that an ajaxSend event occurs. Here's what my code looks like:
//ajax call one
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call two <- let's say I'd like to fire ajaxSpecificFunc() here
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
//ajax call three
$.ajax({
type: "POST",
url: myUrl,
data: myData
});
function ajaxSpecificFunc(){
$(document).on("ajaxSend", function() {
//Some code that should only happen on ajaxSend but for only one ajax call
});
}
EDIT: I am aware of global:false property for ajax, but do not wish to use it, as this would mean I would have to modify every new ajax call in the future to have ajaxSpecificFunc() continue to fire for the one specific ajax call
You can add beforeSend in jQuery.ajax():
$.ajax({
type: "POST",
url: myUrl,
data: myData,
beforeSend: ajaxSpecificFunc
});
As noted by A.Wolff, this way if we call this function it will bind the ajaxsend for each call. Instead you can remove it and just do the specific ones like:
function ajaxSpecificFunc(jqXHR, settings){
// you can work with the jqXhr and settings
}
If you can't bind the handler directly to the ajax call, and want to use the global handlers only then you can check the setting object to see whether the ajax call is your targeted on and if so then call your stuff
$(document).ajaxSend(function(event, jqXHR, settings) {
console.log('send', settings);
if (settings.url == 'myurl') {
//then do your stuff
}
})
Note: But this might become an overkill, and you should try to do it specific to your ajax call
i am using ajax request to get the data, and also i use loading to start and stop ajax. if the data is not empty the loading work perfeclty, but if the data is empty, the ajax cannot stop the loading. i use ajaxStart and ajaxStop to do it.
this is my js code:
<script>
$(function() {
$("#searchgrowh").click(function() {
$('#result').html("");
$('.loading').ajaxStart(function(){$(this).show();});//this method for ajax start
$('.loading').ajaxStop(function(){$(this).hide();});//this method for ajax stop
$('.loading').ajaxError(function(){$(this).hide();});
$.ajax({
type: "POST",
url: "<?php echo base_url();?>internal/trending/ajaxsubmit/",
data: $('#form').serialize(),
success: function(html){
$("#result").prepend(html);
},
});
return false;
});
});
</script>
please see
.ajaxStart and .ajaxStop not firing
also i've had luck with
ajaxSuccess
and
ajaxComplete
I'm working with Django, trying to make a chained AJAX call -- that is, a call that, when returned, kicks off more AJAX calls. I've been over the various methods of dealing with CSRF tokens and AJAX that the Django documentation provides, to no avail.
I have working code that allows for this chained AJAX call to successfully go through:
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken},
success: function(data, status){
$('#queue_div').append("<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>");
var div_id = 'queue'+counter;
data['div_id'] = div_id;
var token = $.cookie('csrftoken');
data['csrf'] = token;
$('#'+div_id).html(data['status']);
callbackAJAX(data);
} //end success function
}); //end ajax function
e.preventDefault();
But when you delay the form event from firing the AJAX event right away, either by using "beforeSend" (as below):
var data = {'group_name':'name', 'client':'MrClient'}
var counter = 0
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
headers: {'X-CSRFToken':csrftoken}
beforeSend:function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
} .....
or by adding an event right before the $.ajax call (as below):
frm.submit(function(e){
$('#foo').append('<div class='container'>"+data['group_name']+"- "+data['client']+"<div id='queue"+counter+"'></div></div>');
$.ajax({
type: frm.attr('method')....
You get a CSRF error.
I was successful in doing very, very simple functions such as the following:
var counter = 0;
frm.submit(function(e){
$.ajax({
type: frm.attr('method'),
sendBefore: function(e){
counter++;
}
But that's it. Anything more complicated gets rejected. I'm thoroughly confused as how to make heads or tails of what is actually happening OR what is acceptable to Django. & its CSRF protection.
The HTML you are trying to append is invalid. I believe that's why the form submission is not working. First you are trying to insert an element with ID foo into an element with the same ID ( foo ). Which is invalid HTML since IDs should never be repeated within the page.
Second and main problem is that you are appending <div id=foo></div> which should be <div id="foo"></div>
Here's a question which has proved very difficult to find an answer online for.
Let's say a user runs an ajax function onclick to fill the contents of a div.
But, what if the ajax output is php, and for that onclick, i want other divs on the page to change in a manner that is dependent on the contents of div1?
This means I need to wait for div1 to actually change so i can use the ajax output of the php calculations to adjust div2 accordingly.
After some testing i've found out that i cant add a call to a second ajax function at the end of the first because it seems to run before the div content from the first ajax call actually changes.
So how can i trigger an ajax call onchange of the contents of a div?
All ajax calls take a callback to run when the call completes, put your logic in there.
You could use Jquery
$('#div1').change(function(){
doAjax( $(this).html() );
});
Or in the callback of the ajax
$.ajax({
url: 'http://yoururl.com',
type: 'post',
data: { key: value },
success: function( data ){
doAjax( data );
}
});
If you are aware of jquery, this is what you should try:
$.ajax({
traditional: true,
type: "post",
url: '<your_url>',
beforeSend: function () {
//your logic to perform operation before ajax request
},
data: {
//data to send
},
success: function(response) {
//your logic to perform operation after ajax request
//here make another ajax request
}
});