I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.
Related
I am using jquery to pull football data from an api as follows
type: 'GET',
dataType: 'json',
url: "http://api.football-data.org/v1/competitions/426/teams",
processData: true,
//idLength: url.Length - url.LastIndexOf("/", StringComparison.Ordinal) - 1,
//id: url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1, idLength),
success: function (data, status) {
var trHTML = '';
$.each(data.teams, function (key, item) {
var id = item._links.self.href;
var indexOfLastBackSlash = id.lastIndexOf("/") + 1;
id = id.substring(indexOfLastBackSlash);
//$('<option>', { text: item.TeamName, id: item.ID }).appendTo('#lstTeams');
trHTML += '<tr class="info"><td>' + item.name +
'</td><td>' + item.code +
'</td><td>' + item.shortName +
'</td><td>' + item.squadMarketValue +
'</td><td>' + item.crestURL +
'</td><td>' + id +
'</td></tr>';
I want to be able to select a 'td' and navigate to another url like "http://api.football-data.org/v1/teams/322/fixtures" for the team with id of 322. How can I do so?
You can create a function which will do same ajax request but this time for single record. On your target's click event you need to call that function passing the id you need to fetch records for. One way of doing this is to set a data attribute to your target container.
Below is the sample code performing similar functionality.
$(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/',
method: 'GET',
dataType: 'json'
}).then(function(Data) {
$.each(Data, function (key, data) {
var id = data.id;
var title = data.title;
$('.tableAllRecords').append('<tr><td><a href=# class=mylink data-id='+id+'>'+id+'</a></td><td>'+title+'</td></tr>');
});
});
});
function fetchSingle(id) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + id,
method: 'GET',
dataType: 'json'
}).then(function(data) {
var id = data.id;
var title = data.title;
var body = data.body;
$('.tableSingleRecord').append('<tr><td>'+id+'</td><td>'+title+'</td><td>'+body+'</td></tr>');
});
}
$(document).on('click', '.mylink', function(e) {
var id = $(this).data('id');
fetchSingle(id);
e.preventDefault(); // disabling anchor's default [redirect] behaviour
});
Here is the link to fiddle. https://jsfiddle.net/2h54vu7h/
If you need to display records on a new page, you simply have to pass id into your url and on next page you have make an ajax request getting the id variable from url.
Example: '<a href=somepage.html?id='+id+'>View Details</a>';
This question already has answers here:
jQuery callback for multiple ajax calls
(14 answers)
Closed 5 years ago.
I would like to call a function only after all of the ajax calls I am making in the $.each loop complete. What is the best way to achieve this?
function recaculateSeatingChartSeatIds()
{
var table_id = $(".seatingChartTable").attr("id");
var seat_id = 0;
$(".nameContainer").find("p").each(function()
{
seat_id++;
var participant_id = $(this).attr("data-part-id");
$.ajax({
method: 'POST',
datatype: 'jsonp',
url: base_url + 'users/assignToTableAndSeat/' + event_id + "/" + participant_id + "/" + table_id + "/" + seat_id
}).done(function () {
console.log("Participant Added");
}).fail(function (xhr, text, error) {
console.log(error);
});
});
funcToCallAfterAllComplete();
}
what if you set a flag on each p after the ajax call and then always call a function that checks to see if all p's have that flag
$(".nameContainer").find("p").each(function()
{
seat_id++;
var participant_id = $(this).attr("data-part-id");
$.ajax({
method: 'POST',
datatype: 'jsonp',
url: base_url + 'users/assignToTableAndSeat/' + event_id + "/" + participant_id + "/" + table_id + "/" + seat_id
}).done(function () {
console.log("Participant Added");
$("p[data-part-id='"+ participant_id +"']").data('completed', 'completed');
}).fail(function (xhr, text, error) {
console.log(error);
});
});
tryFuncToCallAfterAllComplete(){
$(".nameContainer").find("p").each(function()
{
if($(this).data('complete') != 'completed'){
return;
}
}
funcToCallAfterAllComplete();
}
funcToCallAfterAllComplete();
}
this would allow you to still call them all at the same time, and funcToCallAfterAllComplete would only run when all ajax calls have finished
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I am new to ajax. I am trying to display data into table in JSP file.
API is called using AJAX.
Controller pass below response:
BatchwiseStudent [name=Ram, course=MCA (Commerce), emailId=rammansawala#gmail.com, placed=null, batch=2016, mobileNo=7.276339096E9]
In JSP page:
<script type="text/javascript">
function getStudentDetails(){
$batch = $('#batch');
$course = $('#course');
$.ajax({
type: "GET",
url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),
success: function(data){
console.log("SUCCESS ", data);
if(data!=null){
$("#batchwiseTable").find("tr:gt(0)").remove();
var batchwiseTable = $("#batchwiseTable");
$.each(JSON.parse(data),function(key,value){
console.log(key + ":" + value);
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['name']);
rowNew.children().eq(2).text(value['emailId']);
rowNew.children().eq(3).text(value['placed']);
rowNew.children().eq(4).text(value['batch']);
rowNew.children().eq(5).text(value['mobileNo']);
rowNew.appendTo(batchwiseTable);
});
$("#batchwiseTable").show();
}
},
error: function(e){
console.log("ERROR ", e);
}
});
}
</script>
I can see new row into the table but there is no data. I want name, emaild, mobileNo, etc into particular field.
can anyone guide me where am i wrong?
Below code should be keep in the .jsp Page where you show table you don;t need to write html code for table jsp page.
<div id="insert-table-here"></div>
Javascript code:
below code is for ajax call
replace uri with your url value that is used in your url.
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
var str = '<table class="table table-bordered"><thead>'+
'<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
$.each(data, function (key, value) {
str = str + '<tr><td>' +
value.name + '</td><td>' +
value.course + '</td><td>' +
value.emailId + '</td><td>' +
value.placed + '</td><td>' +
value.batch + '</td><td>' +
value.mobileNo + '</td></tr>';
});
str = str + '</tbody></table>';
$('#insert-table-here').html(str);
}, error: function (data) {
}, complete: function (data) {
}
});
I have the following code:
var src, flickrImages = [];
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
// undefined returned here for flickrImages
map.setZoom(13);
map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
infowindow.open(map,this);
I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.
I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.
Any help is much appreciated.
Thanks in advance,
Dave.
The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.
That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.
The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.
It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?
Define a global variable outside of your ajax call and assign it a value
var myData
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
myData = data
myFunction()
}
});
As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add
async: false,
to your ajax request. Here is you code looks after adding this:
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
async: false,
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).
Here is another option. You create a function that return an ajax call like this.
function flickrImages (){
return $.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json"
});
}
Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this
var result= flickrImages ();
flickrImages = [];
result.done(function(data){
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
});
console.log (flickrImages);