jQuery Loader on a Ajax request [duplicate] - javascript

This question already has answers here:
Add a loading animation to jquery ajax .load()
(5 answers)
Closed 8 years ago.
I am creating an application in Node, which pulls objects in my Schema (Mongo) and presents them in HTML. Okay, all right so far.
Now I need to create a jQuery loader, which features a picture like this while the objects do not appear in the html -> http://i.imgur.com/hq37Dew.gif while the data does not appear.
$.ajax({
type: 'GET',
url: host + '/datas',
success:function(datas) {
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
How I can do this?

$.ajax({
$(".datas").empty().html('<img src="http://i.imgur.com/hq37Dew.gif" />'); // SHOW THE AJAX LOADER
type: 'GET',
url: host + '/datas',
success:function(datas){
$(".datas").html(datas); // this will hide the loader and replace it with the data
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
I think this is it.

Assuming that you give the image an id of image_id ,
$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function(){
// Code to show the image . e.g.
$('#image_id').show();
},
success:function(datas) {
// Code to hide image again / completely make it display-none
$('#image_id').hide // or $('#image_id').css("display","none");
reservas.forEach (function (data) {
// ........
})
}
});

$.ajax({
type: 'GET',
url: host + '/datas',
beforeSend: function() {
// Add loader here
$(placeholder).addClass('loading');
},
complete: function() {
//hide loader here/
$(placeholder).removeClass('loading');
},
success:function(datas){
datas.forEach (function (data) {
var HTML = [];
HTML.push('<tr class="datas">');
HTML.push('<td>' + data.email + '</td>');
HTML.push('<td>' + name.email + '</td>');
reservasHTML.push('</tr>');
$('tbody').append(reservasHTML.join(''));
})
}
});
hope this works

Related

How to manually select an item using AJAX, Select2 and the "val" function

Trying to figure out how to change the selected item of a select2 box after the page loads for the first time (and after it has loaded data from a ajax api call)
I tried using the below, but I cant get them to call after the ajax data has loaded?
$series2.val('2');
$series2.trigger('change');
The documentation says that it cannot be done using the val function (see here https://select2.org/programmatic-control/add-select-clear-items) and I do not want to do this with a custom API call that provides a "selected" value - as this does not work with templating.
This is NOT a duplicate of Select2 auto trigger event change
var $make2 = $(".make2");
var $series2 = $(".series2");
$make2.select2().on('change', function() {
$series2.empty();
if ($make2.val() !== null) {
$.ajax({
url: "{{ url('/') }}" + "/api/series/" + $make2.val(),
type: 'GET',
dataType: 'json',
async: true,
success: function(data) {
$series2.select2({
data: data,
templateSelection: function(result) {
return result['text'];
},
templateResult: function(result) {
if (!result['id']) {
return result['text'];
};
var final =
'<div>' +
'<strong>' + result['text'] + '</strong>' +
'<ul class="list-unstyled">' +
'<li><em>' + result['make'] + '</em></li>' +
'<li><em>' + result['category'] + '</em></li>' +
'</ul>' +
'</div>';
return final;
},
escapeMarkup: function(result) {
return result;
},
});
}
});
}
}).trigger('change');
});

using jQuery mobile with ajax

I am trying to print a jQuery mobile thing using ajax but it doesn't encode the result as jQuery mobile is supposed to do.
This is a simplified version of the part of the javascript code that is supposed to do so:
<script type="text/javascript">
function changePage(task) {
var objText = "";
$.ajax({
type: "POST",
url: "DataFetch.aspx/FetchData",
data: '{id: ' + <%=Session["loggedID"] %> + ', task: ' + task + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var obj = JSON.parse(response.d);
if (task == 2)
{
objText += "<div data-role='collapsible'><h3>click me</h3><p>text</p></div>";
}
document.getElementById('content' + task).innerHTML = objText;
}
});
}
</script>
How can I make it work? (when I write it explicitly in the html or outside the ajax functions it works but I need it to work with json)
Try changing
document.getElementById('content' + task).innerHTML = objText;
to
$('#content' + task).HTML(objText).enhanceWithin();
The enhanceWithin() call tells jQM to enhace the new content you added via AJAX:
http://api.jquerymobile.com/enhanceWithin/

Cannot read property 'length' of undefined jquery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting a list from C# web method with ajax (code below), the list is returned fine, but after the success method is done, it gives me an error - (Cannot read property 'length' of undefined) in the jquery (screenshot below)
Am I missing something ??
function getMainParentMenus() {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
The method above is called by the below method.
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
// var parentMenus = getMainParentMenus();
getMainParentMenus();
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
};
EDIT :
the data in the alert in the first block of code above is displayed like so
and in the chrome debugger :
Because getMainParentMenus is using AJAX it is asynchronous. Your next line of code after calling getMainParentMenus will be executed before the .success part of your AJAX call, so it will be executed before parentMenuss has been populated.
There are a few ways you can tackle this, one way would be to pass the callback function to getMainParentMenus, something like this:
function getMainParentMenus(myCallback) {
$.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
parentMenuss = msg.d;
if (callback && typeof(callback)==="function") {
callback();
}
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
};
Now you can call it like this:
var html = "<div id='accordian'> ddd";
getMainParentMenus(function() {
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
});
Your code for rendering the menus is being executed immediately after getMainParentMenus(); Javascript does not wait for the ajax call to complete before moving on to the next block. It is operating asynchronously, as others have mentioned in the comments.
Your code has to wait for the ajax call to complete before trying to display the data.
jQuery supports deferred execution and promises, so you can create code that will not execute until other code has completed. This is the preferred way of handling asynchronous operations.
Try this:
function getMainParentMenus() {
var request = $.ajax({
type: "POST",
url: "/Mainpage.aspx/getLeftMainNavParentMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
}, //It goes to the screenshot below after this bracket
error: function (error) {
alert("An error has occured while fetching the Left Nav Parent Menus");
}
});
return request;
}
var parentMenuss;
var listOfSubMenus;
function bindLeftNavMenu() {
getMainParentMenus().success(function (result) {
var html = "<div id='accordian'> ddd";
$.each(parentMenuss, function () {
html += " <h3 class='accordianHeader' href='" + this['URL'] + "'>" + this['Title'] + "</h3> ";
alert("okK");
$.each(listOfSubMenus, function () {
html += "<div class='accordianContent'><a href='" + this['URL'] + "'>" + this['Title'] + "</a>";
});
});
html += "</div>";
$("#leftNavigationMenu").append(html);
});
}

how to show the loader dynamically until all the image load in jquery mobile phonegap listview

am having trouble to showing loader untill all the image is load in the listview.the following code is used in my app.it shows the loader untill all the image is load but the problem is , append the last src value to all the image attribute src.please help me.
$.ajax({
url: "http://www.some.com/",
type: 'POST',
data: param,
dataType: "jsonp",
success: function (result) {
$.each(result.results, function (k, v) {
var searchPic = "http://www.some.com" + $.trim(v.eventIcon);
var localarray = new Array();
var c = v.eventText;
strs = c.slice(0, 60);
$('[data-role="listview"]').append('<li> ' + '<img alt="img" class="pic1" src=" ">' + '<h4 >' + v.eventTitle + '</h4>' + '<p>' + strs + '...' + '</p></li>');
$('[data-role="listview"]').listview('refresh');
imgload(searchPic);
});
$('[data-role="listview"]').append('<li id="no-results">There is no record found based on your search criteria, please refine your search.</li>');
}
});
function imgload(tx) {
$('.pic1').load(function () {
$.mobile.loading('hide');
}).attr('src', tx);
}
});

How to Create Relationship Between Contact and Account SugarCRM javascript

Hi can somebody help me? I am new in programing with Javascript and I need to set a Contact to Account Relationship.
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId +
'","module_name":"Contacts","module_id":"' + CurrentContactId +
'","link_field_name":"accounts","related_ids":["session":"' + SugarSessionId +
'"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}
I tried to create new Contact and I want to set a Relationship with an existing Account.
At jmertic's suggestion, I tried the following, but it still didn't work:
function SetRelationContact_Account(){
$.get(CurrentServerAddress + '/service/v2/rest.php', {
method: "set_relationship",
input_type: "JSON",
response_type: "JSON",
rest_data: '{"session":"' + SugarSessionId + '","module_name":"Contacts","module_id":"' + CurrentContactId + '","link_field_name":"accounts","related_ids":["name":"account_id","value":"' + CurrentAccountId + '"]}'
}, function(data) {
if (data !== undefined) {
var addAccountResult = jQuery.parseJSON(data);
}
});
}
"related_ids" should be the Account Id of the record you are relating to, and should be in the form of a javascript array.

Categories

Resources