Ajax .done() don't work together for me - javascript

I have a very strange situation. I have an AJAX function which sends form data to a php codeigniter controller, on json response, it has to deal with the response. first part is working, but later part, which is a .done() function, doesn't work, no matter what I try.
here is my script:
var validator = $('#register-company-form').validate({
rules: {
title: {
required: true,
valueNotEquals: 0
},
/* rules here */
},
highlight: function (element) {
$(element).closest('.form-field').addClass('error-field');
},
unhighlight: function (element){
$(element).closest('.form-field').removeClass('error-field');
},
errorPlacement: function(error, element) {},
submitHandler: function(form) {
var formData = new FormData($(form)[0]);
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false
})
.done(function (response) {
$(".form-field").removeClass("error-field");
$(".item-exists").hide();
if(response.Response == 401) {
$("#company_email").closest('.form-field').addClass('error-field');
$("#company_email").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 402) {
$("#personal_email").closest('.form-field').addClass('error-field');
$("#personal_email").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 403) {
$("#user_name").closest('.form-field').addClass('error-field');
$("#user_name").closest(".form-field").find(".item-exists").show();
} else if(response.Response == 200){
/* load my view */
}
});
return false;
}
});
My PHP script returns following JSON response:
{"Response":200,"Data":null,"Message":null}
After getting this response, my .done() function is supposed to act according to it and load a page, which it is not. I have tried putting console.log() and alert() into it, but now its clear its not responding. Is there any other way to do this or any correction in code?
Please note that the same code really worked fine on another server. This has happened after migration.
Thank you so much for the help!

Thank you so much for your Kind information #DFreind and #JonathanLonowski, with your hints, I finally figured out this problem which took me almost 3 days.
Actually when I looked closely at the html produced by PHP, it said:
1 {"Response":200,"Data":null,"Message":null}
This '1' before the JSON string was generating cannot modify headers error!
After lots of efforts, I just saw a plain goddamn '1' just before opening <?php tag on first line in my controller. Removing this '1' worked like a charm, all errors gone, life saved, dosing in heaven now :-)
Indication for researchers: Please install Firebug if you are facing similar errors and always look into response headers, try experimenting. Most of the time PHP errors mess with your output. In my case, 'headers already sent' error generated because before php started its output, html came in. Watch out for any echo() or set_cookie() functions as well!
Thanks all of you StackOverflowish geeks :)

Related

Stuck in login page spinning when submitting logging request?

I have a website, with some pages like any other website.
It works perfectly on my computer(localhost).
But when I uploaded it to a real server, some problems appeared in login pages..
The problem's after I insert my login information and click submit IT DOESN'T redirect me to main page..
It keeps spinning!
$(document).ready(function() {
end_loader();
$('#ulogin-form').submit(function(e) {
e.preventDefault()
var _this = $(this)
var el = $('<div>')
el.addClass('alert alert-danger err_msg')
el.hide()
$('.err_msg').remove()
if ($('#password').val() != $('#cpassword').val()) {
el.text('Password does not match')
_this.prepend(el)
el.show('slow')
$('html, body').scrollTop(0)
return false;
}
if (_this[0].checkValidity() == false) {
_this[0].reportValidity();
return false;
}
start_loader()
$.ajax({
url: _base_url_ + "classes/Login.php?f=login_user",
method: 'POST',
type: 'POST',
data: new FormData($(this)[0]),
dataType: 'json',
cache: false,
processData: false,
contentType: false,
error: err => {
console.log(err)
alert('An error occurred')
end_loader()
},
success: function(resp) {
if (resp.status == 'success') {
location.href = ('./')
} else if (!!resp.msg) {
el.html(resp.msg)
el.show('slow')
_this.prepend(el)
$('html, body').scrollTop(0)
} else {
alert('An error occurred')
console.log(resp)
}
end_loader()
}
})
})
})
As you have stated that the code and everything else works offline and the responses made by the other programmers, I will continue on that for now by asuming it works offline as you have said.
It might be the case that your local enviroment is more up to date then your online server enviroment. As local you could have PHP 8 but online run 7.0
Example: PHP 7.2 added 'PASSWORD_ARGON2ID' and if you have used that then online enviroment PHP 7.1 will never work since it doesn't know what to do.
Please confirm by:
Create a file that contains the following code:
<?php
phpinfo();
?>
and confirm that your online server is atleast equal to your offline version. Further versions might rollback certain functions so try to have the exact same PHP and ?Linux or Apache? version as offline.
After you confirm that the offline and online versions are the same, let's then try the other issue such as "undefined mysqli_stmt::$get->result in class/login.php line50", it would help if you would provide code.
Also, if you upload your work (code) directly to git->to online server, make sure your .gitignore doesn't ignore the files that you need.
Let's hope this helps.

JSON data from javascript to PHP with Jquery AJAX

Using the following code i am trying to send JSON data via javascript to a PHP script
Watching "isRunning" while stepping through the code returns true, ie suggests AJAX isn't running, however once the code progresses to the next portion of AJAX code "isRunning" changes to false;
I have tried to trap the error on the second portion - which returns "Unexpected error"
Does anyone have an suggestions as to what i am doing wrong, or how I can trap a more informative error response ?
var isRunning = true;
$.ajax({
url: url,
success: function(resp) {
isRunning = false;
}
});
jsonString = JSON.stringify(row);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
console.log('The answer from the PHP file: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
Thank you
Thanks to everyone or their suggestions, I think the issue lies with the JSON.stringify conversion, also i noticed i didn't include the PHP side, which i have kept to a minimum basically
$data = json_decode($_POST['json']);
echo "Data:-".$data."<BR>";
Is it possible that the problem lies on the PHP side ?
As discussed many times before ajax is asynchronous which means it runs while you are requesting the isRunning variable. If you want to know if this call succeed use a network console like most modern browsers have. This will show you if the call will be made and the server response.
For the second part, the code looks to be correct. However if you run the code from your browser you only see the client side. I suggest you use the network console here as well. A small error in the url may already get your code to output Unexpected error. Either way, you need more information like server response, error codes etc..
Have you tried logging jqXHR.responseText with the unexpected error too? Or put a breakpoint on that line and examine the variables in the debugger.
If that doesn't help you could try debugging the php side and seeing how the code executes there and what goes wrong.
Also remember that ajax is asyncronous, so your isRunning could change halfway down the page, or when it's all done.
edit:
If you don't have a debugger for php it would definitely save you a ton of headaches in the long run to get one setup.
I'd recommend netbeans, since it has a robust toolset for many languages (including both javascript and php). You'd also need to configure xdebug on your server to allow remote debugging.
To handle the errors, use the error setting as you're doing, but PHP can return the JSON data too, so you can handle more errors from PHP.
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
if(data.errorCode) {
console.log('The answer from the PHP file: Error #' + data.errorCode + ' - ' + data.errorException);
} else {
console.log('The answer from the PHP file: ' + data.responseText);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
And in your PHP file, you can handle the errors, returning this if the things worked fine:
$response = array(
"responseText" => "AJAX is working OK.",
"errorCode" => 0,
"errorException" => ""
);
This if you have to return an error, like MySQL error or something like that:
$response = array(
"responseText" => "",
"errorCode" => 1,
"errorException" => "Your error message here."
);
And finally sends the JSON data back to the AJAX:
echo json_encode($response);

jQuery $.post not returning data

I'm using $.post to send a form via ajax to a PHP page, which returns JSON data. Once upon a time, it worked perfectly, and the function(data) executed as normal. Somehow, I've broke it, and now it doesn't even touch the function(data). I've tried undoing most of what I've done, but I still can't find the problem.
Here's the script :
$("#modifyhome").submit(function(event) {
if($("#modifyhome").valid()) {
event.preventDefault();
var $form = $( this ),
title = $form.find('input[name="title"]').val(),
content = $form.find('textarea[name="content"]').val();
$.post("?action=page-accueil", {"title": title, "content": content},
function(data) {
if(data['error'] == 1)
{
$().message(data['message']);
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
else if(data['error'] == 0)
{
$().message(data['message']);
$("div.jquery-message").effect("bounce", {times: 3}, 900);
}
else
{
$().message("Erreur de connexion au serveur : veuillez réessayer.");
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
}, "json"
);
}
else
{
$("[id^=qtip-]").effect("pulsate", {times: 3}, 600);
return false;
}
});
And here is what the PHP page (?action=page-accueil) returns :
{"error":0,"message":"Page modifiée."}
That all checks out as valid JSON, but it's as if jQuery doesn't recognize it for some reason. Any help is greatly appreciated :)
You're not clear about what the problem is. At the beginning you say
Somehow, I've broke it, and now it doesn't even touch the function(data)
but then you say that jQuery is not recognizing your JSON, which means the callback function was invoked. You need to test each phase of the process to discover your error. Browser console is a must for debugging in this case.
Test cases:
is the server returning anything? If not
Is there an error in the php code? May return 500 error or could return OK, but with error message as string.
Is there a same-origin issue? Perhaps going form HTTP -> HTTPS?
If the server is returning something but it is not being parsed correctly.
Is the data being returned valid JSON? For PHP you should use json_encode function if available or something similar. jQuery side there is jQuery.parseJSON()
Is there an issue with response-type headers? In this case you will want to use normal $.ajax and set the beforeSend parameter to something like beforeSend: function(xhr){ xhr.setRequestHeader("Accept", "text/javascript") }. You will need to further research this option.
To test any of this it is fundamental that you are familiar with the browser console. Chrome Network Panel or Firebug Net Tab
I used to get this problem too, I am exactly not sure of the reason why. But I have a solution that works.
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = eval("("+data+")");
//.... Then continue it
});
Or, use .parseJSON() function to read the string as JSON, if you dont want to use eval()
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = $.parseJSON(data);
//.... Then continue it
});

Jquery form ajax call trouble

I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?

Ajax success event not working

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

Categories