Second Ajax call already populated with success results - javascript

I have an Ajax call being made from a button press which returns me some data then goes off and creates a grid. The first time the function is called the Ajax call is made, data is returned and the grid is displayed. Happy Days.
However any subsequent call to the function, where none of the data parameters are changed, result in the Ajax call not being made to the server and the function skips straight to 'success' with the results from the successful call already populated.
Changing any of the 'postParameters' results in a successful Ajax call and the data is refreshed.
function btnClick(){
//blah blah
getGridData();
}
function getGridData() {
var postParameters =
{
SiteID: "#Model.SiteID",
DateFilterFrom: $("#datepickerFrom").val(),
DateFilterTo: $("#datepickerTo").val(),
CustomerFilter: $("#customers").val()
};
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
};
I know there must be an important Javascript concept I am missing but I just cant seem to be able to nail it.
Can anyone help put me in the right direction?

Have you tried to disable the cache with:
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
Explanations
The cache basically tries to save a call to the server by saving the return value of the calls.
It saves them using a hash of your query as a key, so if you make a second query that is identical, it will directly return the value from the cache, which is the value that was returned the first time.
If you disable it, it will ask the server for every query.

You can add cache: false to your ajax request.
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
cache:false,
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
IE might not listen to you though. For that you can add a field to the POST Parameters, where you add the current time in miliseconds, so even IE does not cache.

try to add this in ur ajax call:
$.ajax({
cache: false,
//other options...
});
This will force the recall of the ajax each time.
For more information please check the following link :
api.jquery.com/jquery.ajax

Related

Returns error when consuming this php response

Return error in the query
From the browser the answer is correct.
$.ajax({
type: "POST",
url: url,
async: true,
contentType: " charset=utf-8",
dataType: "XMLHttpRequest",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});
The message says "error".
I see three issues. First, dataType is a choice of xml, json, script, or html, unless you did something really fancy. jQuery can guess it based on received data though, so there is normally no need to set it. But if you want to be explicit (assuming your page returns json):
dataType: "json"
Second, contentType value looks like some truncated thing. I would just completely remove it, as you are not sending any data and just requesting a page.
Finally, when you are sending no data and just requesting a resource, the best is to use GET.
All in all:
$.ajax({
type: "GET",
url: url,
async: true,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});

MissMatching parameters in ajax call, try catch block

How to identify mismatching of parameters on a ajax call ? I have the following code sample
var driverId = $('#driverId').val();
var driverPhoneNumber = $('#driverPhoneNumber').val();
$.ajax({
type: "POST",
url: 'srvl_def',
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
dataType: "json",
data: {
driverId: driverId,
driverPhoneNumber: driverPhoneNumber
},
success: function (data) {
alert(data.mensaje);
}
});
My AJAX calls are much more complex than this. I have close to 80 parameters at some places. Missing a parameter it becomes impossible traceback and its very time consuming. Also when parameters are undefined it takes time to debug that. Is there a way in which I can use a try catch block to print out all the undefined and non matching parameters of my ajax ?

How do I debug Jquery Success function

I am using Javascript to get records from the database, everything works the way i want but i cannot show alerts in success handler. When i place a break point to sucess:function(data) it gets hit but this line is not being hit $("#Alert").html(data).show().... Another unusually thing i have noticed is that some time $("#Alert").html(data).show().. gets hit. Is there any way i can debug this?
function MethodNAme() {
ajReq.abort();
ajReq = $.ajax({
type: "POST",
url: "Services/",
data: ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
getSomething();
$("#Alert").html(data).show().delay(5000).fadeOut();
alert("working");
}
}
your syntax is not correct, you are placing a function getSomething() in middle of $.ajax(),
function MethodNAme() {
ajReq.abort();
ajReq = $.ajax({
type: "POST",
url: "Services/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
// getSomething(); <-- remove this
success: function (data) {
$("#Alert").html(data).show().delay(5000).fadeOut();
alert("working");
}
});
}
You can use console.log() to print data in browser console. You can access console window by pressing F12 key and then go to console tab.

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks

jQuery Wait until async ajax calls are finished

Hi I have 2 ajax calls in my script, I need them run asnyc to spare time, but I need the second to wait until the first is finished.
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
if (parO2.length > 0) {
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO2,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/*WAIT UNTIL THE FIRST CALL IS FINISHED AND THAN DO SOMETHING*/
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
}
So any ideas? Thanks
If using jQuery 1.5+, you can use jQuery.when() to accomplish this. Something like (shortened the ajax calls for brevity, just pass the objects as you're doing above)
$.when($.ajax("getText.asmx/ws_getText"),
$.ajax("getText.asmx/ws_getText")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the
// first and second ajax requests, respectively
var jqXHR = a1[2]; // arguments are [ "success", statusText, jqXHR ]
});
You don't know in which order they will return so if you were rolling this by hand, you would need to check the state of the other request and wait until it has returned.
You need to wire up the second call to be contained within the callback of your first ajax call. Like so:
success: function(msg)
{
alert(msg.d.data);
if(par02.length > 0)
{
// Your 2nd ajax call
}
},
Since JavaScript doesnt run in multiple threads on the client, you can't block the thread until certain conditions are met.
Using jquery
$.ajax({
type: "POST",
async:false, // ** CHANGED **
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
}
, error: function () {
chyba("chyba v požadavku", "df");
}
});
Here is another answer on running dual ajax requests. Like Tejs, the user makes an ajax call within the success method...
The poster states You're better off having the success method launch a new ajax request.."
Having two $.ajax() calls in one script

Categories

Resources