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>
Related
I cannot get a simple ajax example to work from an html page inside my visual studio project. It works fine from a webform (aspx):
...
webform1.aspx and form1.html
...
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: bob }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
...
webform1.aspx and form1.html
...
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
...
json.aspx
...
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
If I put the code in webform1.aspx, it works fine. If I put it on form1.html, nothing comes back from json.aspx. I am running the project in debug mode from my machine using vs2013. Any help would be appreciated.
Update #1
I checked fiddler and the server is returning the following result (500):
{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...
Your json is malformed. Strings need to be in quotes. Put bob in quotes and you should be good. I'm unsure why it's working on the ASP.NET page though, unless it has the quotes there.
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: \"bob\" }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
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);
})
});
I have to display data in a web application with the ability to filter. The data is ported via FTP as XML. Can I use Dynamic Data to handle this or is there an alternative way. I do know I can manually linq to the xml and display in datagrid or some other control but the Dynamic Data Template seems to offer all the Data management functionality.
ya use JSON and JQUERY
here is code from which i filter account no,
$(function () {
var search = $("#<%=txtAccountNo.ClientID%>");
search.watermark('Enter Account No');
search.autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetAccountNo',
data: "{ 'prefixText': '" + search.val() + "', 'count' : '10','contextKey':''}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
}
},
error: function (XMLHttpRequest, textStatus, error) {
//alert(textStatus);
}
});
},
minLength: 1
});
});
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;
});