I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
My server side script works fine, however when the server or network is down, i would like to show error message. You can use the jQuery error function for this. Just add it to the ajax option config. The ajax docs discuss what happens when passing the option as an object. Make sure not to use the ajax success function.
statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem. I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
The Ajax error function has three parameters: In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
@Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false
to the $.ajax function. It wasn't getting a response back from the php.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With