Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - jquery .ajax always returns error - data being added to database

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...