P. Nick
P. Nick

Reputation: 991

Ajax POST and php query

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.

jQuery:

$(document).ready(function() {

        $(document).on('submit', 'form#shoutboxform', function () { 

            $.ajax({  
              type: 'POST',  
              url: 'shoutboxform.php',  
              data: form.serialize(),
              dataType:'html',  
              success: function(data) {alert('yes');},
              error: function(data) {

              alert('no');
              }
            });  
            return false;  

              });

        }); 

PHP:

<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
    $sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
    if(!empty($sboxmsg)) {
        $addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
    }
}

And HTML:

<form method="post" id="shoutboxform" action="">
                <input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
                <input type="submit" name="subsbox" id="shbox_button" value="Post">
            </form>

When I submit anything, it just reloads the page and nothing is added to the database.

Upvotes: 0

Views: 66

Answers (2)

bingo
bingo

Reputation: 2308

Prevent the default submit behavior

   $(document).on('submit', 'form#shoutboxform', function(e) {
  e.preventDefault();
  $.ajax({
      type: 'POST',
      url: 'shoutboxform.php',
      data: $(this).serialize(),
      dataType: 'html',
      success: function(data) {
          alert('yes');
      },
      error: function(data) {

          alert('no');
      }
  });
  return false;
});

Upvotes: 2

Tom
Tom

Reputation: 160

Use the following structure:

$('form#shoutboxform').on('submit', function(e) {
    e.preventDefault();
    // your ajax
}

Or https://api.jquery.com/submit/ :

$("form#shoutboxform").submit(function(e) {
    e.preventDefault();
    // your ajax
});

Upvotes: 2

Related Questions