无需刷新即可提交表单(ajax,php)


Submit form without refresh (ajax , php)

我试图在不刷新页面的情况下提交表单,我希望在单击按钮id=fav时显示一条警告消息。这是代码,但我不知道我做错了什么。它应该是点击按钮还是提交表单?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
$(document).ready(function(){
$("#f1").submit(function(){


// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
    </script>
<form action="#read" method="post" id="f1">
  <div class="r1">
    <button class="down" name="download" title="Add to favorites">Download</button>
    <li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
    </li>
    <button class="d-later" name="dlater">Download later</button>
    <button class="fav-button" type="submit" id="fav"></button>
  </div>
</form>

PHP

   if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){
      $query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
       $result = mysql_query($query);
        if(! $result ) {
             die('Could not delete data: ' . mysql_error());
    } $response['message'] = 'My message';
echo json_encode($response);
    }else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){

          $query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
       $result = mysql_query($query);
        if(! $result ) {
             die('Could not enter data: ' . mysql_error());
    }
   $response['message'] = 'My message';
echo json_encode($response);
}
  function fav_exists($u , $ii){

    $query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
    $result = mysql_query($query);
    $count = mysql_num_rows($result); 

    if($count >= 1) {
        return true;
    } else {
        return false;
    }
}

我认为您正在传递空数据,请参阅下面的示例如何传递一些数据;如果你想运行ajax+php,你需要传递一些数据

<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}

$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});

此外,我强烈建议使用PHP PDO进行SQL查询-http://php.net/manual/en/book.pdo.php

upd:

$('#fav').click(function(){
    do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
  if(response.message){
   alert(response.message);
  }
 }
});
}

在您的php文件中,您可以根据您的action使用switchif/else不同的函数;

<?php if(isset($_POST['action'])) {
  $action = $_POST['action'];
  switch($action) {
    case 'favorites':
    $msg = 'favorites action called';
    breake;
    case 'not fav':
    $msg = 'not fav called';
    breake;
    default: 
    $msg = 'Nothing passed';
    breake;
  }
  $Response['msg'] = $msg;
  echo json_encode($Response);
}

这是我在同一任务中使用的。

HTML

<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>

JS

$(function() {
    $('form').submit(function(e) {
        e.preventDefault(); // Stop normal submission
        data = $('form').serializeArray();
        alert(JSON.stringify(data));
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'inc/update.php',
            data: {
                json: JSON.stringify(data)
            },
            dataType: 'json'
            }
        });  
    });
    return false;
});

PHP

$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();