$.ajax Get data does not append to var - javascript

I ve a problem with the output:i want to fill the ouptput whit some data from an ajaxcall.
the call is successfull(the output inside the each is filled with data)
but the output inside the each issnt apended to the output outside .
i always geht "
<ul id="listname" data-inset=true></ul>
and not
<ul id="listname" data-inset=true><li>some data</li></ul>
$("div:jqmData(role='collapsible')").each(function(){
var id = $(this).data("id");
var idDate=id.slice(7,18);
var listapp="id_col_"+idDate;
var listname="id_col_"+idDate;
output='<ul id="listname" data-inset=true>';
$.ajax({
url: 'lomodata.php',
data: 'timestamp='+idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
}
}
});
output+='</ul>';
$(this).append(output).trigger("create");
$(this).listview();
$(this).listview('refresh');
});

Note that $.ajax is by default asynchronous, and by the time you reach $(this).append(output), output is not yet defined, since the .ajax() call hasn't finished yet. You need to move the append to the success handler, or add the async: false option, so that $.ajax becomes a blocking call (although this defeats the purpose of using ajax):
success: function(res) {
if (res !='') {
var output='<ul id="listname" data-inset=true>';
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
output+='</ul>';
$(this).append(output).trigger("create");
}
}

AJAX is Asynchronous. When you write $.ajax( ... ), an HTTP request will be sent to the server, which will then move on to the next operation, output += '</ul>'. The HTTP request will not have finished by this time, and so your callback will not yet have been executed by the time you append output to the document.

$("div:jqmData(role='collapsible')").each(function () {
var el = this;
var id = $(this).data("id");
var idDate = id.slice(7, 18);
var listapp = "id_col_" + idDate;
var listname = "id_col_" + idDate;
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
output = '<ul id="listname" data-inset=true>';
if (res != '') {
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
console.log(output);
});
}
output += '</ul>';
el.append(output).trigger("create");
el.listview();
el.listview('refresh');
}
});
});

If you move all lines of codes that use the output variable to the success function of the ajax call, you will see that it works. The problem is that you're using asynchronicity incorrectly.
Something like this:
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
if (res != '') {
var output = '<ul id="listname" data-inset=true>';
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
});
output += '</ul>';
console.log(output);
$("#myObject").append(output).trigger("create");
$("#myObject").listview();
$("#myObject").listview('refresh');
}
}
});

Related

ASP.NET MVC - After HTML append with Jquery the DropDownList value comes as undefined

I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>

JavaScript/jQuery callback using Ajax

I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.
In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.
I tried to delay it using an if condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.
Can anyone recommend JavaScript or jQuery code to fix this problem?
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview
You've almost got it!
The same way that you call getMovieInfo in the success callback of getMovieList, you should be calling countTheMovies in the success callback of getMovieInfo.
As Jacob said above, move the countTheMovies call inside the AJAX request.
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
if (isLast) countTheMovies();
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.
You can call your countTheMovies() function from inside the success field of your Ajax call. This way it will make the function call when you intend it to.
Try out this
$(function(){
getMovieList();
});
function getMovieList() {
$.when( $.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
}) ).then(function( data, textStatus, jqXHR ) {
countTheMovies();
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}

make an ajax call in the very first page in JQM

I am trying to show a popup in my first page if a php post returns a json file with data.
I tried with:
$(document).on("pageinit", '#home', function() {
ajax call even with async:false,...
And after that, I fill up the element with some list elements if json has data:
if(userLastPush == 1){
var getPushXdays = '{"day":"4"}';
$.ajax({
type: "POST",
url: urlServer+"getPushXDays.php",
data: getPushXdays,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//console.log(response);
html = '';
if(response.message != "empty"){
jQuery.each(response, function(category, val) {
if(val.id_Event == 0){
html +='<li>' + val.message + '</li>';
}else{
html +='<li>' + val.message + '</li>';
}
});
}
$(".popupPush").append(html).listview('refresh');
if(checkPushing == 0){
$("#checkpush").trigger("click");
}
},
error: function(xhr, status, message) {}
});
}
But it just works sometimes. Others, ajax never ends or never shows data. I tried by using a function instead and function is called but no return from ajax. Is there a way to make this getting all data before page is load?

Json data in a next and previous button

I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources