Issues calling a method after making an ajax call [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Once a checkbox is ticked on a form, I am calling a function that performs certain checks and enables a previously disabled button.
My js code has the following:
$('#default_address').change ->
id = $('#default_address').val()
if(this.checked)
$.ajax({
url: '/shipments/' + id + '/get_address',
dataType: "JSON",
success: (data) ->
$('#billing_address_address_line1').val(data[0])
$('#billing_address_address_line2').val(data[1])
$('#billing_address_phone_number').val(data[2])
}).done
checkPlaceOrderValidity()
The checkPlaceOrderValidity() method is as shown below:
#checkPlaceOrderValidity = ->
// some code
else
place_order_btn.attr 'disabled', false
place_order_btn.removeClass 'disabled'
If I add an alert just before calling the checkPlaceOrderValidity() method, it works fine(which I found really strange). I m unable to find the cause even after debugging my code.

Try this,
$.ajax({
url: '/shipments/' + id + '/get_address',
dataType: "JSON",
success: (data) - >
$('#billing_address_address_line1').val(data[0])
$('#billing_address_address_line2').val(data[1])
$('#billing_address_phone_number').val(data[2])
}).done(checkPlaceOrderValidity);

Related

“Undefined” error response from AJAX JQUERY call to XML file [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I want to open an XML file using jQuery, but I have an undefined error when I want to display the value of open outside the function.
Here is the code :
$(document).ready(function () {
var open ;
$.ajax({
type: "GET",
url: "../build/js/openTickets.xml",
dataType: "xml",
success: nv =function(xml) {
$(xml).find("mestickets").each(function () {
var open =$(this).find("nbopenTickets").text();
console.log(open); // it works
});
}
})
console.log(open);//undefined
remove var from
var open = $(this).find("nbopenTickets").text();
just do
open = $(this).find("nbopenTickets").text();
And then use call back function like below.
var open;
$(document).ready(function() {
$.ajax({
type: "GET",
url: "../build/js/openTickets.xml",
dataType: "xml",
success: nv = function(xml) {
$(xml).find("mestickets").each(function() {
var open = $(this).find("nbopenTickets").text();
console.log(open); // it works
ajexSuccessCallBack();
});
}
});
});
function ajexSuccessCallBack() {
console.log(open);
}

JavaScript undefinded variable after refresh [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Since I loaded a project to the web server I am getting this error message after the first refresh:
TypeError: oModel.responseJSON is undefined
Although the variable exists and AJAX succeed. The error refers to this line:
<body onload="displayEntries(oModel.responseJSON.results);">
I load before the body close tag the following JS:
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="js/user.js"></script>
JS runs in strict mode and in the "user.js" I have this code:
let oModel = $.ajax({
url: 'data.php',
dataType: 'json'
});
function displayEntries(entries) {
$("#div").empty();
let html = "";
jQuery.each(entries, function(i, entry) {
html = '<div id="cid-' + i + '" class="entry">' + entry.name + '</div>';
$("#div").append(txt);
});
}
When I enter "oModel.responseJSON.results" into the console, it is displayed correctly.
Ajax is asynchronous
Get rid of onload="displayEntries and just call the function in succcess callback of $.ajax
$.ajax({
url: 'data.php',
dataType: 'json'
}).then(displayEntries);
This happens because you're trying to access value of a variable before the AJAX call is over.
Call the displayEntries() function after the AJAX call is over like so:
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(function(data) {
displayEntries(data)
});

Jquery ajax call data not binding [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a function which returns html code based on pulled json data from the controller. I am trying to append the jquery ajax call result to a div after completing the ajax operation.
The problem is there are 100 records in json and pulling them take little time. Data is not binding to the div. But when I add an alert it shows the data. I think the background time to display alert and clicking on ok is setting the ajax resulted data. Do we have any good option to bind data or to bind data only after data is completely loaded? I tried with complete function but it didnt work.
function queryOrdersExtraRow() {
var Details;
$.ajax({
url: "../MoreDetails/GetJsonDetails",
type: 'Get',
dataType: 'json',
data:{Id:138},
cache: false,
contentType: 'application/json',
success: function (result) {
Details = '<table class="extra">' +
'<tr><th>Name#</th><td>' + result.name + '</td></tr>' +
'<tr><th>Address Type</th><td>' + result.address + '</td></tr>'+
'<tr><th>Phone:</th><td>' + result.phone + '</td></tr>' +
'</table>';
return Details;
},
error: function (error, textStatus, errorThrown) {
reportFriendlyAjaxError(error, textStatus, errorThrown);
},
complete: function () {
}
});
//alert(Details);
return Details;
//Bind data here
}
Instead of using return, call your binding function right within the success.

submit multiple forms using JQuery ajax [duplicate]

This question already has answers here:
jQuery Multiple Forms Submit
(2 answers)
Closed 8 years ago.
I have this code to submit 1 form on click.
$('#verify_id').click(function() {
var formData = new FormData($('form#verify_id_form')[0]);
$.ajax({
type: 'post',
url: '/public_transaction/verify_id',
data: formData,
async: false,
success: function (res) {
alert(res);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
But, I want to submit 2 more forms with this. How can I change data to submit multiple forms?
ID of other 2 forms are: #form1 and #form2. How can I modify this line?
var formData = new FormData($('form#verify_id_form')[0]);
EDIT
there is a option in ajax to do something like this...
var dataString = $("#filter-group1, #filter-group2").serialize();
(here 2 forms are getting submitted bu just 1 click)
But, I don't know how to achieve this in my case?
If you don't use "ajax:false" and submit all 3 forms, as $.ajax is asynchronous all the forms will be submitted in non-blocking way.
$('#verify_id').click(function() {
$.ajax({
//code for form 1
});
$.ajax({
//code for form 2
});
$.ajax({
//code for form 3
});
return false;
});

Ajax request is not working php [duplicate]

This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.

Categories

Resources