10

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>
T0w3ntuM
  • 332
  • 2
  • 3
  • 12

6 Answers6

37

@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!

Vicer
  • 1,034
  • 5
  • 15
  • 22
8

Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.

T0w3ntuM
  • 332
  • 2
  • 3
  • 12
6

I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )

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.

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

Community
  • 1
  • 1
noderman
  • 1,934
  • 1
  • 20
  • 36
2

I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.

Good Luck Guy!

1

You should specify status Code 200 for successful response.

<?php
http_response_code(200);
?>

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

skmasq
  • 4,470
  • 6
  • 42
  • 77
1

The first solution

Try to remove dataType in your js file like that:

$(document).ready(function() {
    $('.button').click(function() {
        var form = $(this).closest('form');
        $.ajax({
            type: "POST",
            url: form.attr('data'),
            data: form.serialize(),
            success: function (response) {
                alert('something');
            },
            error: function() {
                alert('fail');
            }
        });
    });
});

The second solution

Send a real clean JSON to AJAX like that:

PHP

if(isset($_POST['username'])) {
    $user = new Users;
    $user->cleanInput($_POST['username'], $_POST['password']);
    if($user->insertUser()) {
        $error = [
            "title"=> 'true',
            "body"=> 'some info here ... '
        ];
        echo json_encode($error);
    } else {
        $error = [
            "title"=> 'false',
            "body"=> 'some info here ... '
        ];
        echo json_encode($error);
    }
}

JavaScript

$(document).ready(function() {
    $('.button').click(function() {
        var form = $(this).closest('form');
        $.ajax({
            type: "POST",
            url: form.attr('data'),
            dataType: 'json',
            data: form.serialize(),
            success: function (data) {
                let x = JSON.parse(JSON.stringify(data));
                console.log(x.title);
                console.log(x.body);
            },
            error: function() {
                //code here
            }
        });
    });
});
blazej
  • 927
  • 4
  • 11
  • 21
Ayoub ait
  • 163
  • 2
  • 4