简体   繁体   中英

Ajax call always returns error even on successful call

I'm trying to get the hang of Ajax calls and I'm struggling with a basic peace of code :)

I keep getting the error alert even when the call seems to be successful. I tried to debug the code and added some breakpoints and noticed that done-function does execute. The form-info has been written away and a string is returned from the php-script. For a brief while the text does appear but then disapears after the done-function. While debugging i don't get the error message. It only appears while running the script normally.

Any help would be greatly appreciated.

<div id="formDiv">
<form method="post" id="form">
<label for="title">Title: </label>
<input type="text" name="title" id="title" />
<label for="composer">Composer: </label>
<input type="text" name="composer" id="composer" />
<label for="link">Link: </label>
<input type="text" name="link" id="link" />
<label for="description">Description: </label>
<input type="text" name="description" id="description" />
<input type="submit">
</div>

<div id="outerDiv">
    <p id="p"></p>
</div>

<script>
$("#form").submit(function(){
    var postData = $(this).serializeArray();
    $.ajax({
    url: "test.php",
    type: "POST",
    data: postData,
    dataType: "text"    
    })
    .done(function(data){
        $("#p").text(data);
    })
    .fail(function(){
        alert("Error!");
    });
    });

</script>

test.php

<?php   
$dbc = mysqli_connect('localhost', 'root', '', 'db');
if ($dbc->connect_error) {
die('Connect Error: ' . $dbc->connect_error);
}

$title = $_POST['title'];
$composer = $_POST['composer'];
$link = $_POST['link'];
$description= $_POST['description'];

$query = "INSERT INTO table(Titel, Componist, Link, Description) VALUES ('$title', '$composer', '$link', '$description')";
mysqli_query($dbc, $query);


$resultquery = mysqli_query($dbc,"SELECT * FROM table");
$result = "";
while($row = mysqli_fetch_assoc($resultquery)){
    $result .= $row["Titel"]." | ".$row["Componist"]." | ".$row["Link"]." | ".$row["Description"]."\n";
}

echo $result;
mysqli_close($dbc);

?>

Instead of alerting you might try to use console.log. You might also add parameters to the faile function to see what comes from the server

funcation fail( jqXHR, textStatus, errorThrown ) {
    console.log("textStatus: " + textStatus);
    console.log("errorThrown: " + errorThrown);
}

I doubt whether you have written your field names and table name correctly

INSERT INTO db(Titel, Componist, Link, Description)

Spellings are wrong in title, and you are inserting data not into the table, you insert them into db. This is wrong. Add your table name

After trying a lot of different things this seems to work:

I've added the action attribute to my form tag

<form method="post" id="form" action="test.php">

And added preventDefault() on the form and changed the error handling

<script>
$("#form").submit(function(e){
    var postData = $(this).serializeArray();
    $.ajax({
    url: "test.php",
    type: "POST",
    data: postData,
    dataType: "text"    
    })
    .error(function( jqXHR, textStatus, errorThrown ) { console.log(errorThrown); })
    .done(function(data){
        $("#p").text(data);
    })
    e.preventDefault();
    });

</script>

So why is the action attribute necessary for this to work?

Try the following snippet using success and error callbacks rather than done and fail`.

$("#form").submit(function(){
    var postData = $(this).serialize();
    $.ajax({
        url: "test.php",
        type: "POST",
        data: postData,
        dataType: "text", 
        success: function(data){
             $('#p').text(data);
        },
        error: function(){
            alert("Error!");
        }   
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM