sigil
sigil

Reputation: 9546

trying to use AJAX to submit without refresh, fails silently

I'm using WAMP to build a basic AJAX web app. I want a form that, when submitted, inserts the input into a table in the database, without refreshing the page.

Here's the HTML for my form:

<div style="float: right;" id="submitDiv">
    <form id="submitForm" action="" method="post">
        <input type="text" name="content"/>
        <input type="submit" value="send" name="submit"/>
    </form>
    <br>
    <span id="error" style="display: none; color:#F00">error</span>
    <span id="success" style="display:none; color:#0C0">success</span>
</div>

Javascript for performing the AJAX submission:

<script language="JavaScript">
$(document).ready(function(){
    $('#submitForm').on('submit',function(e){
        $.ajax({
            url:'/module/submit.php',
            data:$(this).serialize,
            type:'POST',
            success:function(data){
                console.log(data);
                $("#success").show().fadeOut(5000);
            },
            error:function(data){
                $("#error").show().fadeOut(5000);
            }
        });
        e.preventDefault();
    });
});
</script>

submit.php for inserting the POST content:

<?php
    if(isset($_POST['content']))
    {
        $content=$_POST['content'];
        $db=new PDO('mysql:host=localhost;dbname=testDb;charset=utf8','root','');
        $insertSQL="insert into submission (content) values ('".$content."')";
        $stmt=$db->prepare($insertSQL);
        $stmt->execute();
    }
?>

When I type some text into the input box and click submit, the "Success" span appears and fades, but the text doesn't appear in the console log; all I get is:

(index):21

The text is not inserted into the submission table. I tried debugging submit.php by enabling the error log in php.ini as:

error_log = "c:/wamp/logs/php_error.log"

but no error log file is generated.

Any idea what's going wrong here?

UPDATE: There were at least two bugs: .content. should be .$content., and $db->prepare() should be assigned to a prepared statement variable that then calls execute(). I've made my changes in the code. The remaining problem is that submitting the form takes me to submit.php instead of staying at index.php.

Upvotes: 1

Views: 887

Answers (3)

Sean
Sean

Reputation: 12433

Since you are using PDO::prepare, then you should not be directly inserting your value.

Try

<?php
  if(isset($_POST['content']))
  {
    $db=new PDO('mysql:host=localhost;dbname=testDb;charset=utf8','root','');
    $insertSQL="INSERT INTO submission (content) VALUES (?)";
    $stmt = $db->prepare($insertSQL);
    $stmt->execute(array($_POST['content']));
  }
?>

I think your issue is $(this).serialize should be $(this).serialize(). You should also add some checks (if/else) in both your js and php code to verify the insert worked.

Your js code could be

<script language="JavaScript">
$(document).ready(function(){
    $('#submitForm').on('submit',function(e){
        $.ajax({
            url:'/module/submit.php',
            data:$(this).serialize(), // missing () on serialize()
            type:'POST',
            success:function(data){
                console.log(data);
                if(data != "Error") {
                   $("#success").html(data).show().fadeOut(5000);
                }
                else {
                   $("#error").html(data).show().fadeOut(5000);
                }
            },
            error:function(data){
                $("#error").show().fadeOut(5000);
            }
        });
        e.preventDefault();
    });
});
</script>

and your php code

<?php
  if(isset($_POST['content']))
  {
    $db=new PDO('mysql:host=localhost;dbname=testDb;charset=utf8','root','');
    $insertSQL="INSERT INTO submission (content) VALUES (?)";
    $stmt = $db->prepare($insertSQL);
    $stmt->execute(array($_POST['content']));
    if($stmt){
       echo "You successfully inserted the value " . $_POST['content'];
    }
    else {
       echo "Error";
    }
  }
  else {
    echo "You did not submit a value";
  }
?>

Upvotes: 3

Daedalus
Daedalus

Reputation: 7722

Aside from problems of not using PDO correctly, your problem appears to be a simple typo:

<?php
    if(isset($_POST['content']))
    {
        $content=$_POST['content'];
        $db=new PDO('mysql:host=localhost;dbname=testDb;charset=utf8','root','');
        $insertSQL="insert into submission (content) values ('".content."')";
        //        There should be a $ here to denote a variable ^
        $db->prepare($insertSQL);
        $db->execute();
    }
?>

Unsure why it isn't erroring out, given that is use of an undefined constant, otherwise.

Upvotes: 1

shuskic
shuskic

Reputation: 81

Are your sure php is receiving the POST data? I'd change your php file to this:

if(isset($_POST['content']) { //do stuff } else { echo "FAIL" }

This should be your first step to debugging. Then I'd change

$(this).serialize

to

$("#submitForm").serialize();

Upvotes: 2

Related Questions