I am new to ajax and javascript.
I have the following web method in a page called people.aspx in the root of my web porject:
[System.Web.Services.WebMethod]
public static string RenderDetails()
{
return "Is it working?";
}
I'm attempting to access the web method via an Ajax call from the people.aspx page. I have the following ajax call on the click event of a div:
$("div.readonly").click(function (e) {
e.stopPropagation();
$.ajax({
type: "POST",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
failure: function (msg) { alert("Sorry!!! "); }
});
alert("Implement data-loading logic");
});
I'm not receiving any errors in the javascript console, however, the ajax call also does not hit the web method. Any help will be appreciated.
Thanks!
Try change the type to GET not POST (this is probably why your webpage isn't getting hit). Also your failure parameter is incorrect, it should be error. Expand it to include all parameters (it will provide more information). In short, change your entire AJAX query to this:
$.ajax({
type: "GET",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
error: function (jqXhr, textStatus, errorThrown)
alert("Sorry!!! "); // Insert breakpoint here
}
});
In your browser, debug the error function. The parameters (particularly jqXHR) contain a LOT of information about what has failed. If you are still having more problems, give us the information from jqXHR (error string, error codes, etc).
Related
I use Jquery to parse an json from url: the code is like this:
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
everything works fine, but if the server is not reachable I'm not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error
have you got some ideas?
thank you!
You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser's developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan't to use for error detection.
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();
I am building a Facebook messenger bot. I got to a point where I need to show a webview. This webview does some payment processing and on success, I call a Messenger SDK's function to close the webview and then do an Ajax call to continue messaging the user. Now I have an issue, the webview does not close until the ajax has finished executing i.e. sending the messages to the user. If I place the Messenger close function outside the ajax call, the webview closes but the ajax is not executed. Please how do I close the webview and then continue executing the ajax request.This is what I am currently doing:
$.ajax({
type: 'POST',
dataType: 'JSON',
url: '/api/payment/'+userId+'/'+payRef,
data: 'userId='+userId,
success: function (data) {
console.log(data);
MessengerExtensions.requestCloseBrowser();
}
})
I don't know if that can solve your problem, but you can try this:
$.ajax({
type: 'POST',
dataType: 'JSON',
url: '/api/payment/'+userId+'/'+payRef,
data: 'userId='+userId,
beforeSend: function() {
MessengerExtensions.requestCloseBrowser();
},
success: function (data) {
console.log(data);
}})
In theory, the window will close before the request init.
I don't know if I understood right, but did you try the beforeSend and complete functions from ajax?
$.ajax({
type: 'POST',
dataType: 'JSON',
url: '/api/payment/'+userId+'/'+payRef,
data: 'userId='+userId,
beforeSend: function(jqXHR, settings) {
// Action before send the request to the url
},
success: function (data) {
// Action if the process in the url url don't throw any errors
},
complete: function(jqXHR, textStatus) {
// Action when the request is returned to application
},
error: function(jqXHR, textStatus, errorThrown) {
// I would recommend you always use the error function.
}
})
I have a Self-Hosted-Service(using WCF) that will run on clients machines. That service is supposed to make request to another server, get the data as XML then it returns to me that data as JSONP. Now i want to check if the service is running or not .. How can i check that ?
In my JS code i use $.getJSON with callback, so i tried to use .fail like this:
$.getJSON("http://localhost:8080/url?callback=?", function () {
alert("success");
}).fail(function () {
alert('fail');
})
but fail function didn't called when the server is not running(on chrome the Type is pending and Status is Failed)
Then i tried to use $.AJAX like this:
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://localhost:8080/url?callback=?',
success: function (data, textStatus) {
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
I got the same result.
When you make the AJAX request to your localhost and /url? returns weather the other server is up or not, your script won't fail. Because http://localhost/url is online.
I'd make the /url script return JSON array with remoteHostOnline: true or false,
then use:
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://localhost:8080/url?callback=?',
success: function (data, textStatus) {
if (data.remoteHostOnline == false) {
alert('remote host not online');
}
}
});
You might have to tweak this script I didn't test it but you will understand what's wrong.
I have the following problem:
$('#id').on('click', '.class', function(){
// it is doing something and
// executing AJAX request
// with the data from request it is doing something
} // this is onclick handler
Later in the code I need to execute it as well and after executing I need to run another function which depends on the ajax execution of this onclick handler, so I am doing something like this
$('#id .class').click();
anotherFunction();
It is not working. The problem is understandable, because the ajax request has not finished.
I tried to achieve the right execution using the idea of Deferred object.
$.when( $('#id .class').click() ).then( anotherFunction() );
And using the idea of autoexecuted functions with callback:
(function(o, callback){
$('#id .class').click()
})(null, anotherFunction() );
Both ideas failed.
Is there any way to achieve the intended functionality without modifying anotherFunction() and onclick function?
Not sure if I entirely understand your question, but what keeps you from executing your onsuccess / onerror code in the corresponding $.ajax response methods?
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { ... },
success: function (data, textStatus, jqXHR) { ... }
});
Also, why don't you put the ajax executing part to an own function and call it from the event handler and on every other place, like this?
function ajaxMe(onerror, onsuccess)
{
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { onerror(...) },
success: function (data, textStatus, jqXHR) { onsuccess(...) }
});
}
I'm trying to return a callback from an AJAX submitted form. The user submits a form, the server processes and returns the valid response, i.e. an error message and also a JavaScript function that could perform an action. I'm using Zepto.js faling back to jQuery depending on browser.
My ajax request is:
$.ajax({
success: function(data, status, xhr) {
data.callback();
},
url: form.attr('action'),
data: form.serialize(),
dataType: 'json'
});
On the server I want to return something like:
// PHP code
?>
{
return: false,
error: 'Sorry, we couldn’t find an account with that username or password.',
callback: function() {
console.log('this is the callback');
}
}
<?php
// more PHP code
When returned to the browser callback function should fire. I want the server to return the callback so I can use the same JavaScript code and have it respond accordingly to the server response.
Would I need to change the dataType to script? However I thought this was just for loading .js files, not blocks of code.
Any help appreciated.
The general feeling here is I am approaching this in the wrong way. So revised code:
$.ajax({
success: function(data, status, xhr) {
var callback = data['callback'];
callback();
},
url: form.attr('action'), // in this example it's badLogin
data: form.serialize(),
dataType: 'json'
});
// callback specified in PHP
badLogin: function() {
console.log('bad login');
}
And my PHP
if (!$valid) {
?>
{
"return": false,
"error": "Sorry, we couldn’t find an account with that username or password.",
"callback": "badLogin"
}
<?php
}
Thanks for pointing me in the right direction.
You can always return the code as a string and use eval() if you are absolutely sure that the string will always be correct and no code can be injected.