Jquery ajax call data not binding [duplicate] - javascript

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.

Related

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

Javascript - use json data inside another ajax request

I'm trying to use some data returned from an ajax request to construct a string, which then needs to be posted back using ajax. However the variable I'm assigning the data to is not in the scope of the second request and thus returning an 'var is undefined' error. In the example below I need to post the data returned from the first request (
var cUrl = '/api/courses/a';
var pUrl = '/api/courses/b/pages/1?page_body=';
var bodyData = '';
$.getJSON(cUrl, function(cData){
bodyData = '<div id="' + cData.id + '">' + cData.description + '</div>';
});
('body').on('click', '#add_btn, function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: pUrl + bodyData,
headers: {"X-HTTP-Method-Override": "PUT"},
success: function(result) {
alert('Successfully Added!');
}
});
});
Any help would be very much appreciated! Many Thanks!
As I understand, you want to handle the click event only if you have the json response data, so:
Just add the click event handler in the getJSON callback.
Or trigger a custom event when you get the json response, and create the click event handler for #add_btn in the custom event handler. With that the #add_btn click event will only fire when you have your json response.

Eror 500 with ajax and codeigniter

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

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

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

Ajax GET request, why does success function not print?

I have this function that performs a GET request for a given id:
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
success: function(data){
console.log('findById success: ' + data.name);
currentRaceEntry = data;
renderList(currentRaceEntry);
}
});
};
When I enter sitename/rest/entries/8 it returns a page with the xml for the object requested(as expected). (I can show this code but I dont think the problem is there). When I preform this request the console shows:
findById 8
My question is why doesn't it show console.log('findById success: ' + data.name);? The xml displays in the browser which looks to me like it was successful. So why doesn't the success function appear to be called? Thanks!
EDIT
this is what it looks like:
The console in the browser is blank
If you ajax request returns XML data, you need to set dataType as "xml".
At that point, the data object in the success function is an XML fragment, not a javascript objet, and you need to process it as such. The data.name property doesn't exist.

Categories

Resources