I am new with jquery. I want to insert all the list items of ul. I tried the following but its not working can someone please guide me whats wrong with the code as i did "async:false" but it still not working
$('#sortable li').each(function () {
items += $(this).text();
insertCustomBCFields($(this).text(), plu);
});
And insertCustomBCFields ftn is below
function insertCustomBCFields(field, plu) {
alert(field + plu);
$.ajax({
type: "POST",
url: 'ProductDefinition.aspx/insertBCCustomFields',
data: "{'field':'" + field + "', 'plu':'" + plu + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
alert("Success");
},
failure: function (response) {
alert("Insert Failed!");
}
});
}
Making a ajax call with async: false, will make it synchronous call . this option should be set to true to make a asynchronous call async: false, unless a synchronous call is necessary.
I can see that your making call to the ajax function each time a li is found in your DOM structure(now thats very bad in terms of performance), well thats not so good, instead you can make ajax call once all the items are iterated.
something like this
var arr="";
var index=0;
$('#sortable li').each(function () {
items += $(this).text();
arr+="{field"+index+":" + field + , "plu"+index+":" + plu + "}";
});
insertCustomBCFields(arr);
Similarly change the ajax call as well
function insertCustomBCFields(arr) {
alert(field + plu);
$.ajax({
type: "POST",
url: 'ProductDefinition.aspx/insertBCCustomFields',
data: {'arr':arr},
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
alert("Success");
},
failure: function (response) {
alert("Insert Failed!");
}
});
}
Happy coding :)
Related
I'm calling Ajax like below
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: '{ "jsondata":' + jsondata + ',"key":"' + getValue('id') + '"}',
success: function (data) {
callback(data);
},
error: function (error) {
callback(error.responseText);
}
});
I want to get the "Data" value at calling time because after the call the execution doesn't goes to the desired web method and the error is showing like
""Message":"Invalid web service call, missing value for parameter: \u0027obj\u0027..."
I have to track the the Ajax posting value during Ajax call and find out what is the problem with posting data.Is there any tricks to get the data value before Ajax calling?
Any help will be appreciated.
Edit: I'm sending the jsondata value like below
var jsondata = '{ "pagenumber":"' + pagenumber + '","sortColumn":"' + sortColumn + '","sortDirection":"' + sortDirection + '","rowPerPage":"' + rowPerPage + '"}';
Thanks.
I was just checking with below code -
please have a look. please check beforesend content
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/dummy',
dataType: "json",
data: '{dummy:"dummy"}',
success: function (data) {
alert(data);
},
error: function (error) {
alert(error);
},
beforeSend: function(data,data1) {
console.log('before'+data1.data)
},
});
})
});
var path = "test_ajax.php";
var jsondata = "Testing123";
var test = "test";
var data = {jsondata : jsondata,key : test};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: path,
dataType: "json",
data: data,
success: function (data) {
alert("success:"+data);
},
error: function (error) {
alert("failure"+error.responseText);
}
});
I am making a dashboard reporting tool that loads multiple charts on the selection of some filters. I use Ajax to load the charts and use Ajaxload to have a small circle as a waiting symbol. Something like:
I want to combine all those circles into one circle in the center, like any normal ecommerce website.
The ajax code is below:
$.ajax({
type: "POST",
data: {
"jsontring": JSON.stringify(output)
},
url: "http://localhost:8080/sales",
contentType: "application/json",
dataType: "json",
cache: false,
beforeSend: function () {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
$('#container1').html("<img class = 'ajload' src='loading.gif' />");
},
success: function (data) {
datavol = data.Vol
dataval = data.Val
$('#container').highcharts(datavol);
$('#container1').highcharts(dataval);
},
error: function () {
alert("Sales Issue!")
},
});
$.ajax({
type: "POST",
url: "http://localhost:8080/soc",
data: {
"jsontring": JSON.stringify(output)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function () {
$('#container3').html("<img class = 'ajload' src='loading.gif' />");
$('#container4').html("<img class = 'ajload' src='loading.gif' />");
},
success: function (data) {
datavol = data.Vol
dataval = data.Val
$('#container3').highcharts(datavol);
$('#container4').highcharts(dataval);
},
error: function () {
alert("Soc Issue")
},
});
$.ajax({
type: "POST",
url: "http://localhost:8080/marketshares",
data: {
"jsontring": JSON.stringify(output)
},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function () {
$('#marketshares').html("<img class = 'ajload' src='loading.gif' />");
$('#marketshares1').html("<img class = 'ajload' src='loading.gif' />");
},
success: function (data) {
datavol = data.Vol
dataval = data.Val
$('#marketshares').highcharts(datavol);
$('#marketshares1').highcharts(dataval);
},
error: function () {
alert("MarketShares Issues")
},
});
Is there any specific fucnctiuon for this?
Ajaxcomplete() Description: Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
You have to create an overlay and center load div, See Exmaple Here, e.g :
<div class="loading">Loading</div>
You have after that to create a global variable e.g var count=0 and increment this variable in every success function e.g count++; :
success: function (data) {
.....
count++;
}
After that You can use a condition inside Ajaxcomplete() function that execute after every ajax request e.g :
$( document ).ajaxComplete(function() {
if(count == 3) //I guess that you have 3 chart to load
$('.loading').hide();
});
NOTE : You can remove the beforeSend().
Hope this will answer your question.
Take a global var for number of ajax call;
isLoadedAll=4;//4 ,let 4 is the number of $.ajax call.
Use one container for loading image.
After a success call a function that checks all ajax success.
function checkAllLoaded(){
--isLoadedAll;
if(isLoadedAll==0)
//do stop loading image here.
}
before send
beforeSend: function() {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
$('#container1').html("<img class = 'ajload' src='loading.gif' />");
}
on each success
success: function(data)
{
checkAllLoaded();
//do other stuff here
}
hope that help.
First load your ajax loader image as:
$(document).ajaxStart(function () {
//here call your ajax loader image
});
And after ajax complete hide your loader image
$(document).ready(function(){
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
// here hide your ajax loader image
});
});
check this link
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have this code that needs to populate an array that will be used on some diagramming tools. so there's a button that will show the results and a checkbox that enables the user to add another set of rows to the array. i use .push() for the array and it works. now, the problem is that the second push on my second ajax calls did not add the data to the array. here's my code:
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one fails
alert("pushed");
});
},
failure: function (data) {
alert(data.d);
}
});
drawChart(rows);
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
i really don't know why it fails. what happens is that even if the condition is satisfied and the second ajax call succeeds, the contents of the array rows is still the first array push. what's the problem with the code?
the result you are getting is actually expected because of async nature of ajax
you should call the method within the success callback of the second ajax call like this
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values);
});
drawChart(rows); // here
},
failure: function (data) {
alert(data.d);
}
});
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});
Hi how do i go about loading up my javascript files after an ajax call has been made, reason being it seems once i click submit, some javascript functions do not end up working. I tried using "$getscript" however it was a bit buggy especially in google chrome? This is what my call looks like;
function InsertStatus() {
var fStatus1 = document.getElementById('<%=txtStatus.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebServices/UserList.asmx/InsertUserStatus",
data: "{ 'fStatus': '" + fStatus1 + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d == "Successful") {
$("#col-3").load(location.href + " #col-3>*", "");
$.getScript('scripts/script.js', function () {
});
}
else {
alert("its false");
$.getScript('scripts/script.js', function () {
});
}
}
});
};
Replace $.getScript('scripts/script.js', function () {});
With:
$.ajax({
dataType: 'script',
url: 'scripts/script.js',
crossDomain:true,
success: function(response)
{
//Whatever
}
});