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.
Related
Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
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).
My host is currently having server issues, making today the perfect day to test what happens when my ajax calls fail.
So I'm finding that when something does go wrong, neither my success or fail function in the following are being called: ( simplified for simplicity's sake ). Currently this will fail completely about one in every 10 times.
I'd like to know how to make sure I can catch all errors in ajax, for example when the server simply doesn't respond, as would be the case today.
myvar = jQuery.post(ajax_object.ajax_url, data, function( response ) {
console.log( 'success!' );
})
.fail(function() {
console.log( 'sad trombone' );
});
You can try these two ways.
$.ajax({
url: ajax_object.ajax_url,
type: 'POST',
async: false,
cache: false,
timeout: 30000,
data : data,
dataType: 'json', // use this if you want json response
error: function() {
return true;
},
success: function(data) {
console.log(data);
}
});
OR $.post(ajax_object.ajax_url, { data:data }, function(response){
console.log(response);
});
first you simply give an echo "hii"; exit; in the page ajax_object.ajax_url so you can test whether it is properly redirect to that page..
How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];
i'm working with python and js on a simple website.
i'm trying to call a method from the client side and get result, but no matter what i do
success function isnt happening.
this is my JS
$.ajax({
url: "http://127.0.0.1:8000/api/gtest/",
type: "POST",
data: { information : "You have a very nice website, sir."},
dataType: "json",
success: function(data) {
alert ("post is success");
},
error: function(request,error) {
alert(request.responseText);
alert(error);
}
});
this is my server side code
def gtest(request):
jsonValidateReturn = simplejson.dumps({"jsonValidateReturn": "ddddd"})
return HttpResponse(jsonValidateReturn, content_type='application/json', mimetype='application/json')
The server responds to the call -
"POST /api/gtest/ HTTP/1.1" 200 31
tried to go over similar questions here but with no success :\
no matter what I do, only the error function is called.
the error alert is always empty.. no actual message.
I know this is probably a small change but I can't find it.
$.ajax({
url: "http://127.0.0.1:8000/api/gtest/",
type: "POST",
data: {
'information' : "You have a very nice website, sir.",
'csrfmiddlewaretoken': '{{csrf_token}}'
},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data) {
alert ("post is success");
},
error: function(request,error) {
alert(request.responseText);
alert(error);
}
});
i cant upvote mccannf's comment.
The problem was solved by the link he posted, i ran the html code from a file on my pc and i needed to load it from the server so link wont start with file:// but with http://
best regards..