How can one trigger a function onchange of a div? - javascript

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
}
});

Related

Sending a POST request with Ajax on button click

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.

Saving Variable in AJAX success call to pass in Another AJAX success call

Creating a 'refresh' button via jQuery, AJAX and PHP.
This particular one I'm having control two DOM instances (divs) - #sold-container, and also #totalorderswidget.
$(document).ready(function() {
$(function() {
$('#orderfeed').on('click', function() {
var orders;
$.ajax({
type: 'POST',
url: 'liveorderwidget.php',
beforeSend: function() {
$('#sold-container').html('<div class="page-loader"></div>');
$.ajax({
url: "totalorderswidget.php",
beforeSend: function() {
$('#totalorderswidget').html('<div class="page-loader"></div>');
},
success: function(orderdata) {
// $('#totalorderswidget').html(orderdata);
orders = orderdata;
}
});
},
success: function(solddata) {
$('#sold-container').html(solddata);
$('#totalorderswidget').html(orders);
}
})
});
});
});
I didn't like how each DIV was updating and showing my page-loader CSS at different times, so I thought I'd try and grab the data to pass and display them both at the same time (get data from the first ajax call, display both on the second).
This is working as two normal AJAX calls, and each appends the success html to each id on it's own. (uncommenting // $('#totalorderswidget').html(orderdata); works),
but initializing a variable like var orders; outside the functions and trying to put the data in the success call (orders = orderdata;) does not work.
Doing a console.log on the first AJAX success call (orderdata) brings back the expected response, but trying to use it in the second AJAX call ($('#totalorderswidget').html(orders);) does not work and a console.log brings back undefined for the order variable.
What must I change in order to grab data from the first success call function and bring this data into the second/final ajax success call?

Load HTML content synchronously

I need to load HTML in a div.
$("#content").load("content.html");
$("#myText").html("Prasath");
After that I need to update some text in a div(id='myText') which is available in "content.html". "content.html" contains huge data, so it takes some time to load. Before that this line is executed:
$("#myText").html("Prasath");
How to load HTML content synchronously from JavaScript/jQuery ?
I don't want to do this from call back option in load.
You can't load it synchronously but you can quite easily do the next task in the load() callback. For example:
$("#content").load("content.html", function() {
$("#myText").html("Prasath");
});
$("#content").load("content.html", function(data){
// this will execute after load is fired.
});
Use a callback.
EDIT: If you really want to make synchronous request, you can use the following code. However, you'll get a warning in console as I mentioned in the comment earlier:
var data = $.ajax({
type: "GET",
url: "content.html",
async: false
}).responseText;
// this code waits for the above ajax request.
Please have a look on the JQuery documentation about load().
You can pass callback function to load()
For example:
$("#content").load("content.html", function(){
$("#myText").html("Prasath");
});
EDIT: There is no way to make load() to load content synchronously. A workaround solution is that you can define a Jquery function that use ajax() to send synchronous request to target url and then set the response content to destinate div.
$(function(){
$.fn.extend({
syncLoad: function (url) {
var result = $.ajax({
url: url,
async: false,
type: "GET"
}).responseText;
$(this).html(result);
}
});
$("#content").syncLoad("/echo/js/?js=hello%20world!");
});
JS Fiddle: https://jsfiddle.net/1v8fmb8b/

Is there a way to synchronize ajax calls

It may be a trivial question, but I am wondering if there is way to somehow know when the last ajax call gets completed. So lets say I have 3 asynchronous ajax calls
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 1>
})
.done(function() {
// handler
});
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 2>
})
.done(function() {
// handler
});
$.ajax({
type: "GET",
datatype: "json",
url: <my service url 3>
})
.done(function() {
// handler
});
I want to show a progress bar when the first call starts and hide it when the last one finish. The issue is that even though I call them in sequence, because calls are asynchronous, I don't know how to tell when all calls finish. I could nest them one inside another, but then as far as I understand it will take much longer as one will have to wait for another to finish. Is there a way to sync it somehow?
I used to have the same need. If you can use jQuery, have a look there : http://lostechies.com/joshuaflanagan/2011/10/20/coordinating-multiple-ajax-requests-with-jquery-when/
Otherwise, you can pass a simple callback function through your AJAX call that comes back in your progress indicator update at the end of each async treatment.
Already answered, but consider using global events instead -
AjaxStart - Triggered when any ajax call starts
AjaxStop - Triggered when all ajax calls are finished
Example -
$( document ).ajaxStart(function() {
$( "#progressBar" ).show();
});
$( document ).ajaxStop(function() {
$( "#progressBar" ).hide();
});
But you will need to make sure that the second call begins before the first call is complete or atleast it should be triggered immediately after the first one completes.

maintain function order in jQuery ajax callback function

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 :)

Categories

Resources