Jquery event firing order - javascript

Why does the function call that contains an ajax request fire off before the append?
$("#range").on("click", function(){
$("#control").empty().append(.....); //why does this get executed after?
var data = 'something';
some_function_with_ajax(data);
}
function some_function_with_ajax(data){
$.ajax({
url: '/url',
type: 'POST',
data: {data: data},
success: function(resp){
// seems the append actually happens here
}
});
}

Related

Setting global variable inside nested ajax calls

I have a specific requirement with nested ajax calls. I am trying to set a globally accessible variable inside success of one ajax call and this ajax call is being invoked inside success of another ajax call. Eventually the parent success method of parent ajax call utilizes the global variable to perform further operations. The problem is that the value of global variable always remains blank. It works if I make the second ajax request as async:false; but this solution defeats the very purpose of using ajax in the first place.
Let me share a small sample code to illustrate my problem:
//global variables
var xURL = "https://sampleurl.com";
var glblID = "";
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json",
success: function (msg) {
//some js code here
//second ajax call
FetchID();
//more js code here
if(glblID != "")
{
window.location.href = xURL + "?id=" + glblID
}
else
{
window.location.href = xURL;
}
}
});
function FetchID()
{
$.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json",
success: function (data) {
glblID = data.d;
}
});
}
As of jQuery 1.5 implement the Promise interface, giving them all
the properties, methods, and behavior of a Promise
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json"
}).then(function (msg) {
//second ajax call
FetchID().then((data) => {
var glblID = data.d;
if (glblID != "") {
//do something with glblID
} else {
//do something else
}
});
});
function FetchID() {
return $.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json"
});
}

A function to enter the ajax result in a variable

I have a problem with this code.
This happens:
just launch the code from console.log I get null, if I press the update button function works.
why is this happening?
how do I fix?
var urljson = "data_json.php";
var data = null;
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
function update(){
var jqXHR = $.ajax
({
type: "GET",
url: urljson,
dataType: 'json',
success: successHandler
});
function successHandler(result) {
data = result;
}
}
$(document).ready(function(){
console.log(data) //// null
});
document.getElementById('update').addEventListener('click', function() {
update();
console.log(data) //// Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, other 3213… ]
});
$.ajax() returns results asynchronously. Use success handler or .then() chained to $.ajax() to process response returned from request.
function update() {
var jqXHR = $.ajax({
type: "GET",
url: urljson,
dataType: "json",
success: successHandler
});
function successHandler(result) {
data = result;
// do stuff with `data` here
console.log(data);
}
}
$(document).ready(update);
jsfiddle https://jsfiddle.net/89jkzzyk/
When the page loads, update() is not getting called, thus data is null. Add your function call to $(document).ready() and it should work.

Parse JSON data in jQuery and display in textfield

I am going to print the response data from test.php in JSON format to print it on particular field
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
$(document).ready(function(){
$("#test").click(function(){
$("#bemail").val(result.email);//when i prints only result than it displays [object object]
});
});
}
});
Try it like this . You have to put your ajax inside $(document).ready
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result.email);
}
});
});
you are calling document.ready() inside the AJAX success handler which doesn't get invoked since AJAX call doesn't invoke the document loading again, DOM has already loaded and it loads only once in the life cycle of a page session.
This much should do
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result[0].email); //after you explained the JSON response
}
});
Your code is totally wrong, it should be
function displayEmail() {
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
//Just Print the Result in Console using console.log(result)
$("#bemail").val(result.email);
}
});
}
$(document).ready(function() {
$("#test").click(function() {
displayEmail();
});
});

Call Ajax on a click event instead of document.ready

I have an Ajax call on document.ready function as follows
$(document).ready(function(){
function AjaxCall(HandleData) {
return $.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success:function(data)
{
HandleData(data);
}
});
}
AjaxCall(function(output){
data = JSON.stringify(output);
I want to call this though on a click function of a div so that the Ajax call to server is made once i click on it instead of making the call on document.ready
How do I go about this?
I want to call it here
$(".reply").click(function (){
I have tried to put it inside it like below
$(".reply").ready(function(){
function AjaxCall(HandleData) {
return $.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success:function(data)
{
HandleData(data);
}
});
}
AjaxCall(function(output){
data = JSON.stringify(output);
Thanks
$(document).ready(function(){
$(".reply").on("click", function() {
AjaxCall(function(output){
data = JSON.stringify(output);
}
});
function AjaxCall(HandleData) {
return $.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success:function(data)
{
HandleData(data);
}
});
}
});
You're calling the ready() method on the .reply class, when you should simply keep the document ready handler, and assign the click method (I use on() just out of preference) to .reply, and call the AjaxCall method inside of said click handler.

problems executing a jquery ajax call within a function

I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}

Categories

Resources