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)
});
Related
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.
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.
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);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm trying to use a .ajax call, to assign the value from an xml document, to a variable in javascript. I can't quite figure out how to use a callback, I know this topic is well discussed on forums, but I haven't been able to find an example out there that does what I am trying to do. The example below makes a call to Google Maps, and gets a string "Central Standard Time" back. I can use .ajax calls to move the text to a div. But I can't figure out how to assign this to a variable, my_zone, and move that value to a div.
Anyone able to help me out? Please? If someone can do a rewrite of the code here, thanks....
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
//this works great, we get the value and it goes to the 'zzz' div, asynchronously
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
$( "#zzz" ).empty().append( val ); //want to return val
}
});
//this is what I am trying to do, get the return'd value, and put it into a variable
var my_zone = getZone(); //just want to get the value into a variable
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
function getZone() {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
return val; //needs to be part of a Callback
}
});
}
///////////
});
</script>
</head>
<body>
<div id="xxx">some output here....</div>
<div id="zzz">some output here....</div>
</body>
</html>
You can't do that, instead you can pass a callback function to getZone() which will get called once the request is completed with the desired parameter
//pass a callback function which will get called when the ajax request is completed
getZone(function (my_zone) {
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
});
function getZone(callback) {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function (xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
callback(val); //call the callback with the value
}
});
}
I would like to call a function on a php file, which one I call in ajax.
I tried the following code:
$("#jq_entryConfQuickSend").click(function () {
$.ajax({
type: "GET",
context: document.body,
//async:false,
url: RP_ROOT_PATH + "/courriers/entries_courriers/rp_win_courrierEntryConfirmation.php",
data: "id_client=" + RP_CLIENT.rp_clientID,
success: function (responseText) {
//var json = eval("(" + responseText + ")");
$("#response-div").html(responseText);
$(responseText).find("script").each(function (i) {
eval($(this).text());
console.log('result');
});
}
});
});
In $(responseText) seems to be an array (I can see the following e.fn.e.init[58]) in chrome debugger, but when I try to use the find('script') function, it doesn't return anything??
And I have many script tag in these file???
Question: What is e.fn.e.init[]?
How can I call my javascript functions on the file I've just loaded in ajax
Thank you
In the ajax parameters I needed to include :
dataType: "html"
Then it will be possible to call the function from the response