i am trying to make an ajax request it is not working properly
my code
function checkUserName() {
debugger
var userName = 'vipin jain';
$.ajax({
type: "POST",
url: "Default.aspx/isUserAvailable",
data: { userName: "+userName+" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
$(".successNotification").removeAttr('display');
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
}
can u tell me what is going wrong.
You really should notice what is going wrong, what error message you are receiving, what doesn't work as expected. From this I can see 2 possible things going wrong:
The debugger line, what is that about? Remove it and debug with Firebug in Firefox
data: { userName: "+userName+" }, This always gives '+userName+' as the username, I guess you need the username here? Do it like this: { userName: userName }.
Related
I have a simple javascript object. I serialize it with JSON.stringify I send it to a asp.net web function that just return it. But when I try to parse the returned string with JSON i get
Microsoft JScript runtime error: Invalid character
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: "{'args': '" + JSON.stringify(MyObject) + "'}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
<System.Web.Services.WebMethod()> _
Public Shared Function PassBackdata(args As String)
Return args
End Function
How can I solve this problem? Thank you
If the error occurs on succes function, you may want to check the format of the result object. I had to use var a=JSON.parse(result.d); because that is how it was returned by webservice, it wasn't a direct json, but an object with a "d" field which was the json.
For checking the result I use fiddler.
Instead of:
"{'args': '" + JSON.stringify(MyObject) + "'}"
Try this:
JSON.stringify({args: MyObject})
Don't do yourself what JavaScript can do for you ;)
It would help to know what MyObject looks like, however:
JSON must have key names in double quotes, not single quotes. Try something like this instead:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "test.aspx/PassBackdata",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({args:MyObject}),
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
var a=JSON.parse(result);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
};
if I do: JSON.parse(result.d) instead of JSON.parse(result) it works.
function AjaxSucceeded(result) {
var a=JSON.parse(result.d);
}
don't know why
I have created a httphandler. Everything is working fine If you take the request type GET. But I really don't want GET request due to security reasons.
I am making a POST request using Jquery using following code:
$.ajax({
type: "POST",
async: false,
url: "SaveAccounts",
data: { a: "Sent Data" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function OnSuccess(a) {
alert(a);
},
error: function OnError(request, status, error) {
alert('Error: ' + request + ' ' + status + ' ' + error);
},
complete: function () {
}
});
And the code for processing request is:
context.Response.ContentType = "application/json; charset=utf-8"
Dim s As String = context.Request.Params("a")
context.Response.Write(JsonConvert.SerializeObject(s))
This code is returning 'null' in javascript alert in client side.
Please note every thing is working fine when request type is changed to GET in $.ajax() function.
I have also tried to access posted data using context.Request.Form("a") and context.request.SserverVariables("a")
context.request.Params is a combined collection of 'Form', 'ServerVariables', 'Cookies' etc.
Please tell me where I am going wrong...??
Thanks for looking....
This is working by just removing contentType and dataType specification from the request.
Anything other than this will remain unchanged.
Try
data: { "a=Sent Data" },
e.g. from http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Also the HttpHandlers don't like JSON data so get rid of the contentType and the dataType.
Escaping it - a more complete example
var dataString = "{ 'first' : '" + escape($('#fname').val()) +
"', 'mail' : '" + escape($('#tbMail1').val()) +
"', 'mailinglist' : '" + $("input[name='ml']:checked").val() +
"' }";
/*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;)
$.ajax({
type: "POST",
url: "myAjaxHandler.asmx/ProcessSampleForm",
data: dataString,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".loadingimg").fadeOut();
window.location.replace(msg.d);
},
error:function(xhr,err){
$(".loadingimg").fadeOut();
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
Taken from http://www.jphellemons.nl/post/JQuery-with-webform-input-validation-ajax-posting-json-to-aspnet-C.aspx
I've read through several tutorials on the web about ajax posting with JQuery, all of them reference the response object from the web service as response / response.d -- This lead me to believe that this is the built in object for JQuery's response handler.
Code Snippet:
$('.submit').click(function () {
var theURL = document.location.hostname + ":" + document.location.port + "/LeadHandler.aspx/hello"; // this will change too
alert(theURL);
$.ajax({
type: "POST",
url: theURL,
data: "{'NameFirst':'" + $('#txtFirstName').val() + "'}", // again, change this
contentType: "applications/json; charset=utf-8",
dataType: "json",
success: alert("Success: " + response.d), // this will change
failure: function (response) {
alert("Failure: " + response.d);
}
});
});
however the code is returning "Uncaught ReferenceError: response is not defined" in Chrome's Javascript console. What assumptions am I making that I need to re-evaluate.
You need to supply success with a function to execute:
success: function(response) {
alert(response.d);
}
Success (Like Failure) need a function to pass the response object through.
$('.submit').click(function () {
var theURL = document.location.hostname + ":" + document.location.port + "/LeadHandler.aspx/hello"; // this will change too
alert(theURL);
$.ajax({
type: "POST",
url: theURL,
data: "{'NameFirst':'" + $('#txtFirstName').val() + "'}", // again, change this
contentType: "applications/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success: " + response.d);
},
failure: function (response) {
alert("Failure: " + response.d);
}
});
});
I'm having quite a frustrating problem that I'm sure is TRIVIAL. Whenever I move this jQuery post inside the click function it sometimes works, but most of the time does not.
If I move it outside it works and posts and gives a response like it should everytime..
::boggled:: Someone please enlighten me.
$(document).ready(function() {
$('#Button1').click(function() {
//alert(document.getElementById('TextBox1').value);
$.ajax({
type: "POST",
url: "sudoku.asmx/getSolution",
data: "{'pid':'34367'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("succes " + msg.d);
},
error: function(msg) {
alert("fail " + msg.d);
}
});
});
});
Looks like you need to have your click event return false.
$("#Button1").click(function()
{
$.ajax(...);
return false;
});
I am making a simple game with jquery and i want to make a call to asp.net web service which i know how to do, but the server call need to continue to run until i get a specific response from the server.
I will wait like 3 seconds with each loop cycle
function servercall() {
while (true) {
// code for clone and insert ...
$.ajax({
type: "POST",
url: "Server.asmx/HelloWorld",
data: "{'name': '" + $('#name').val() + "', 'time': '2pm'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
setTimeout("nothing", 2000);
}
}
Use recursion with setTimeout. And be sure start the timer when you receive a response, so that you account for network delays (you don't want a bunch of requests going at the same time)...
function servercall() {
$.ajax({
complete: function(xhr) {
var msg = xhr.responseText;
if(xhr.statusCode == 200)
AjaxSucceeded(msg);
else
AjaxFailed(msg);
setTimeout(servercall, 2000); //recursion magic
}
});
}
You want the JavaScript setTimeout() Function.
You could try either:
function serverCall() {
// ajax code
setTimeout("serverCall()", 2000);
}
or:
function ajaxSucceeded(msg) {
if (isTheAnswerYouAreLookingFor) {
// do stuff
} else {
setTimeout("serverCall()", 2000);
}
}
Here is an article on setTimeout and setInterval that may help you further:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
Set interval is more helpful :
<script type='text/javascript'>
setInterval("servercall()", 2000);
function servercall() {
// code for clone and insert ...
$.ajax({
type: "POST",
url: "Server.asmx/HelloWorld",
data: "{'name': '" + $('#name').val() + "', 'time': '2pm'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
}
</script>