提交表单而不刷新(ajax,php)

时间:2016-05-14 11:56:41

标签: php html ajax

我正在尝试提交表单而不刷新页面,我希望在单击按钮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;
    }

}

2 个答案:

答案 0 :(得分:0)

我认为你传递空数据,请看下面的例子如何传递一些数据;如果你想运行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文件中,您可以switchif/else使用不同的功能,具体取决于您的action;

<?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);
}

答案 1 :(得分:0)

这是我用于同一任务的内容。

<强> 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();