Weird issue; Button click, Jquery to consume ASMX - asp.net

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;
});

Related

Should breakpoint in the Page_Load event handler be hit when making AJAX call?

I'm making the following ajax request:
$.ajax({
type: 'POST',
url: 'AJAX.aspx/TestPageLoad',
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('Success');
},
error: function (x, e) {
alert( x.responseText);
}
});
I put a break point in my AJAX.aspx page but it does not get hit. Is it the way it supposed to be? According to this article it does.
I put a breakpoint in the Page_Load of my AJAX.aspx page but it does
not get hit
It's because the JavaScript executes on DOM Ready.
Doesn't Page_Load event get fired when making ajax calls?
No. It executes after Page life cycle and on DOM ready
For that you have to set the debugger in Ajax call like below
$(document).ready(function () {
debugger; //A kind of Break Point
$.ajax({
type: 'POST',
url: 'AJAX.aspx/TestPageLoad',
data: JSON.stringify({}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('Success');
},
error: function (x, e) {
alert(x.responseText);
}
});
});

jquery autocomplete with typewatch

I am a jQuery newbie and trying to implement the autocomplete functionality along with jQuery typewatch. That is, to get the data from web service after a certain time period say 750 ms rather than after minLength.
<script type="text/javascript">
$(document).ready(function () {
$('.searchinput').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/SampleWebService.asmx/GetProduct",
data: '{"searchString":"' + request.term + '"}',
dataType: "json",
async: true,
success: function (data) {
response(data);
}
});
},
});
$('.searchinput').typewatch({
callback: $.autocomplete,
wait: 750,
highlight: false
});
});
My autocomplete thing works absolutely fine but somehow I am not able to include the typewatch thing to it. I am sure there is a serious coding failure which I am not aware of.
Thanks
The jquery autocomplete have this option as parameter called delay:
http://api.jqueryui.com/autocomplete/#option-delay
So what you have to do is to change that parameter, and remove the typewatch as:
$(document).ready(function () {
$('.searchinput').autocomplete({
delay:750,
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/SampleWebService.asmx/GetProduct",
data: '{"searchString":"' + request.term + '"}',
dataType: "json",
async: true,
success: function (data) {
response(data);
}
});
},
});
});
The parameter called "delay" is the time you have to wait affter keydown to call external service. That is only for don't overload service with no "sensitive" search data.
What I understood from user question, is that he wants to call the autocomplete "update" function every 750ms.
You could do that changing the typewatch "segment" with this:
$('.searchinput').typewatch({
callback: function(){
$(".searchinput").data("autocomplete").search();
},
wait: 750,
highlight: false
});
That will trigger the search for the service and display popup response every 750ms

getting data as the page loads

I'm trying to get data back after an element is ready in the DOM. I'm trying to use the load function from JQUERY but I get a message .load() is not a function.
Is there a best practice when using ajax to get data for an element (in my case a div) during a page load? I'm using ASP.NET and calling a webmethod in code behind.
Here is my ajax/jquery code:
$(document).ready(function () {
$(function () {
$("[id$=divArea]").load()(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
Thanks.
$(document).ready() is for calling code once the DOM is ready - therefore, if I have understood you correctly, you don't need to include $("[id$=divArea]").load()(function () {
It should work like this:
$(document).ready(function () {
$(function () {
$.ajax({
type: "POST",
url: "apage.aspx/Role",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
alert("got data from Role");
},
error: function (data) {
alert("failed to get data from Role");
}
});
});
});
By the way - it was probably a paste error, but you also omitted the $(document).ready closing }); in the code you posted.
I think that the problem it's the code itself, try the code like this
$(document).ready(function (){
$("[id$=divArea]").load('apage.aspx/Role',function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
})
});

page hanged when web method is executes

I am working on an ajax-webmethod (using json) to save data in a database and select it when needed. Now whenever I call the webmethod, while the method is processed the whole page hangs and nothing can be done with the page.
I want to enable everything while the web method is called from ajax, for example showing a loading image until the web method finishes.
My code is below:
function getvalues(id, tab, pageNo) {
$.ajax({
type: "POST",
url: "default.aspx/LoadData",
data: "{'id':'" + id + "','tab':'" + tab + "','pageNo':'" + pageNo + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d.length > 0) {
var dvComment = document.getElementById("Comments");
dvComment.innerHTML += msg.d;
}
},
async: true,
error: function(xhr, status, error) {
// alert(xhr.statusText);
}
});
}
So now when it renders the html into the DIV the whole time the page hangs.
To show loading image you can use ajaxStart method like this:
$("#loading").ajaxStart(function(){
$(this).show();
});
Where #loading is:
<img id="loading" src="images/ajaxload.gif" alt="loading..." style="display:none"/>
To hide loading image:
$("#loading").ajaxComplete(function(){
$(this).hide();
});

Infinite loop wait 2 second, make server call jquery

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>

Resources