Ajax success event not working - javascript

I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?

The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.

Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.

I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.

Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.

I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.

I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.

You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem

I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.

I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});

I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me

I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)

in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.

The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json

Related

Why error function is always fired on my ajax call? [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Post not working in PHP function, even though var_dump in same function shows the data

I'm befuddled. I have a JavaScript function that posts to a PHP function. PHP says, "undefined index" on mPicker. Yet if I call var_dump within the same function mPicker is plainly visible.
I've also ran an alert client side in JavaScript to be sure the form data was serialized, and it too shows that mPicker indeed has a value. Yet this line in PHP returns the error:
$es=$_POST["mPicker"];
This is just short hand for all your sake. The longer version of the code tests for SQL injection.
And the error in xdebug:
The JavaScript code:
$.post("./php/adates.php", { atype: apttype, data: $("#apptForm").serialize() })
.done(function(data) {
alert(data);
});
And more of the php function code:
if (isset($_POST["atype"]) && !empty($_POST["atype"])) {
$typ = test_input($_POST['atype'], $con);
} else {
echo "error ln 6: typ is undefined.";
}
$es=$_POST["mPicker"];
echo $es;
exit;
test_input is the function I mentioned that tests for SQL injection, and just for testing, have omitted temporarily on the post on mPicker. As you can see, the line $_POST["atype"] escapes error, and is perfectly resolved in the PHP function. I know I am tired and must be missing something stupid. Help, anyone!
try to use jQuery "ajax" instead of "post"
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: "html",
success: function(html){
console.log(html)
}
});
and set the dataType to "html", then use "echo" or "var_dunmp" in php, you can see ur data in console

Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server

I am trying to do a GET request to solr search engine using $.ajax() from jQuery. This is the code I am using for doing an ajax call:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
So I am getting a valid json object in the response but somehow the browser throws an Uncaught Syntax Error. The actual error is:
Uncaught SyntaxError: Unexpected token :
select?indent=on&q=myparam:value&wt=json&callback=…....somevalue...
The tricky part is that the response header is text/plain when I checked in the browser. How can I solve this? Please help me...
Colons require encoding in query strings.
Your url should look like this:
http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam%3Avalue&wt=json
If you're generating the query string dynamically, use encodeURIComponent() to correctly encode special characters.
I got this solved. Actually I had to use jsonpCallback:"mysuccesscallbackfunction" in the ajax call and json.wrf=mysuccesscallbackfunction in the URL. It looks like this now:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json&json.wrf=mysuccesscallbackfunction',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
jsonpCallback:"mysuccesscallbackfunction",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
and my mysuccesscallbackfunction is:
function mysuccesscallbackfunction(resp) {
console.log('inside mysuccesscallbackfunction: ', resp );
}
Now, first it executes whatever is inside mysuccesscallbackfunction and then goes to default success callback. I found it somewhere on web. I would still like to know why it worked now.

Extract Json response

I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json

JSON data not responding

Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks

Categories