Jquery.ajax always returns an error - data is added to the database

I am trying to add users to a database using jquery ajax calls. Users added just fine to the database, but ajax always returns with an error. I also do not know how to get a specific error. Below is the code, form, php and jquery.

Here is 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 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> 
+7
javascript jquery html ajax php
source share
5 answers

@Musa, you mentioned above

My guess is a parsing error, try removing dataType: 'json' and see if it works

You absolutely solved the problem that I encountered! My request to send ajax was similar to the previous one, and it just returned to the "error" section. Although I checked the use of firebug, the status was 200 (ok), and there were no errors.

deleting 'dataType: json' solved this problem for me. Many thanks!

+20
source share

Turns out I had to add async: false to the $ .ajax function. He did not receive a response from php.

+6
source share

I know this is an old question, but I just ran into such a strange situation ( jquery ajax returns success on direct execution, but returns an error when connecting to a button, although the server response is 200 OK )

And found that using a button inside form tags, jQuery always returned an error. Just changing the form tags to div solved the problem.

I believe jQuery assumes that the message should be encoded in the form, even if you say it is application/json .

Try moving your button outside the form and see what happens ...

+3
source share

I had the same problem and discovery there. All the time, the problem is in the version of my jQuery, I had a jquery version (jquery-1.10.2.js) , but this version was not stable Ajax. So, I am changing the version for (jquery-1.8.2.js) , and this miracle was highlighted .

Good luck

+2
source share

You must provide a 200 status code for a successful response.

 <?php http_response_code(200); ?> 

See here: http://php.net/manual/en/function.http-response-code.php

+1
source share

All Articles