简体   繁体   中英

How to insert into mysql table using ajax?

I want to insert data into table using ajax so data will insert without reload of page.

This code insert data into table very well but code also reload the page.

But I want insert without reloading of page.

How can i do this ?

<?php
include('connection.php');
if(isset($_POST['cmt'])){
    $comment = addslashes($_POST['cmt']);
    $alertid = $_POST['alert_id'];
    mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>


<script>
  function submitform(){
    var comment = $("#comment").val();
    var alertid = $("#alertid").val();
    $.ajax({
        type: "POST",
        //url: "ana.php",
        data:{cmt:comment,alert_id:alertid}
    }).done(function( result ) {
        $("#msg").html( result );
    });

  }
</script>

<form method = "POST" onsubmit = "submitform()">
   <textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
   <input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
   <input  type = "submit" name = "submit" value = "Comment">
</form>

return false from your event handler function.

onsubmit="submitform(); return false;">

Consider moving to modern methods of event binding .

try this add this to form onsubmit = "return submitform();"

 function submitform(){
    var comment = $("#comment").val();
    var alertid = $("#alertid").val();
    $.ajax({
        type: "POST",
        //url: "ana.php",
        data:{cmt:comment,alert_id:alertid}
    }).done(function( result ) {
        $("#msg").html( result );
    });
    return false;
  }

You have to create a php file that insert into your table the posted data and call it with ajax like that :

$.ajax({
url: "/file.php",
type: "POST",
cache: false,
dataType: "json",
data: postValue,
success: function(results) {
    bootbox.alert(results.message, function() {
        bootbox.setIcons(null);
        window.location.reload();
    });
},
error: function(results) {
    bootbox.alert(results.message, function() {
        bootbox.setIcons(null);
    });
}

});

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