How do I debug Jquery Success function - javascript

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.

Related

500 Internal Server Error in ajax when calling web server method in C#

When I am calling server method from AJAX call at that time showing 500 internal server error. And this error also happens sometimes only, while sometimes it is working fine.
I am really confused that what is going on that it is sometimes working and sometimes not working. In fact I didn't change anything after working the code but when I check second day it is coming this type of error.
Here is my code
<input type="button" id="btn_save" value="Save" class="button" />
$(document).on("click", "#btn_save", function (e) {
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: JSON.stringify({ schoolName: $('#txt_schoolname').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function () {
document.getElementById("txt_schoolname").value = "";
alert("Error! Try again...");
}
});
});
function OnSuccess(response) {
document.getElementById("txt_schoolname").value = "";
alert(response.d);
}
[WebMethod]
public static string EntrySave(string schoolName)
{
//Here is the code
}
Sometimes working fine but sometimes not coming call in this entrysave method.
try this:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: { "schoolName": $('#txt_schoolname').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {alert('ok');},
error: function () {alert('error');}
});

Second Ajax call already populated with success results

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

Jquery - Calling a ajax function within ajax function

Can I use ajax function withing a ajax function.
In my case there are two ajax calls. First ajax will return some data , If it is successful then the second ajax should be called .
Below is my code snippet,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here"
dataType = "json",
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
Some more info :
I had checked chrome dev console and the error I am getting is
//success - 1
success: function(data) {
//Error message : Uncaught SyntaxError: Unexpected identifier
That was the error message I got.
And yes I cleared the syntactical mistakes and I was getting the same error message.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here",
dataType : "json"
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
I checked the service URL in RESTClient extension of firefox browser and again yes , there is Jsondata coming from that service.
Any good suggestion will be highly appreciable
Merry Christmas :)
There are some errors in your scripts.
In the first ajax call, where are the commas to separate the members ?
url:"my service url here",
dataType= "json",
and this should be:
dataType : "json",
Going back to your answer, yes you can but, what if you had the third ajax call?
Your code would be a mess and really hard to read.
The best would be to use promises.
This is the best way to work with asynchronous in javascript (that's also the reason why I've commented your async:false ).
You can read how promises work here.
$.ajax already returns a promise:
var promise = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url:"my service url here",
dataType: "json",
});
which could be chained with another one:
promise.then(function(result){ });
I tend to prefer the approach where I split my ajax call in different function which create a new promise and return it; just in case I want to manipulate the result:
You can split the two ajax calls:
function FirstAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
// async : false,
url:"my service url here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
and
function SecondAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
// async:false,
url: "my second service URL here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
Now you could resolve the first one and chain the second one:
FirstAjaxCall()
.then(function(result){
return SecondAjaxCall(result);
})
.then(function(result){
// final result
})
.fail(function(reason){
// reason should contain the error.
});
As you can see FirstAjaxCall() is resolve in the .then() branch and it passes it's result in the anonymous function. Same thing happens with the second ajax call SecondAjaxCall(). If something fails in the first or the second call the errors are trapped here:
.fail(function(reason){
// reason should contain the error.
});
The beauty of promises is you can chain them or execute them in parallel.
Yes you can.
Something wrong in your code that I can see is that }//success-1 is before });//ajax - 2 and it should be after.
also there is a missing coma ( ,) after url:"my service url here",
replace the '=' you have by ':' for your two dataTypes.
your should correct that and try again.
Try something like below in a structured way:
//First method with callback
function myFirstCall(callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here",
dataType= "json",
success:function(data){
callback();
});
}
// Second method
function mySecondCall() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my second service url here",
dataType= "json",
success:function(data){
});
}
//Let's trigger it
myFirstCall(function() {
mySecondCall();
});
You have to change "=" after the first "dataType" to ":"
dataType= "json", => dataType : "json",
and move "alert" function to the outside the second $ajax block.
$.ajax({ => alert('inside ajax-2');
alert('inside ajax-2'); $.ajax({
Last, order of closing brackets are opposite.
}//success-1 => });//ajax - 2
});//ajax - 2 }//success-1
The following code should work as you thought.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here"
dataType : "json",
//success - 1
success:function(data){
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
alert('inside ajax-2');
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function (data) {
//some functionality
}//success-2
});//ajax - 2
}//success-1
});//ajax - 1

How to consume a web service using javascript with AJAX?

I'm trying to consume a web service by the way of a method GET, but I can't get the success function, when the program goes to the error function, the alert displays "0", I don't know why.
Here's my code using AJAX
function funcAddPines() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "url.asmx/HelloWorld",
dataType: "json",
data: JSON.stringify({}),
success: function (objRes) {
alert("EntrĂ³ a web-service");
},
error: function (e) {
alert(e.status);
}
});
}

Refresh each second with setInterval

I am logging to refresh a page each sec, and displaying a console.log message:
function refreshEachMinute() {
$.ajax({
type: "POST",
url: "minutesrefresh.php",
//data: dataString,
dataType: "json",
success: function(data) {
//alert('ref');
console.log('ok');
}
});
} // end function refresh
// refresh each minute
setInterval(refreshEachMinute, 1000);
The alert message shows, but the console.log does not. In addition, minutesrefresh.php is not loading in the Firebug bar.
I was facing a similar issue sometime back. So, instead of doing it like this, I changed it to:
function refreshEachMinute() {
$.ajax({
type: "POST",
url: "minutesrefresh.php",
//data: dataString,
dataType: "json",
success: function(data) {
setTimeout(refreshEachMinute, 1000);
console.log('ok');
}
});
}
$(function(){setTimeout(refreshEachMinute, 1000)});

Categories

Resources