在AJAX调用中显示来自PHP的消息

时间:2018-07-25 16:30:45

标签: php jquery mysql ajax

我有一个收藏夹按钮,它调用ajax请求来更新MySQL数据库。

如果有重复的添加或添加的太多,我想发出警报。

如果有重复的添加,有人可以看到一种显示警报的方式吗?我的代码如下:

AJAX请求

$.ajax({
    type: 'post',
    url: 'favaddDB.php',
    data: $('#addfaveform').serialize(),
    success: function () {
      alert('Added To Favourites');
    }
});

PHP

$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');                                                                  
$query1="SELECT * FROM `$email` ";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe

//Check if fave adds >9 
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die(); exit();} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1;}

2 个答案:

答案 0 :(得分:0)

只需返回文本以提醒您的JavaScript:

$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');                                                                  
$query1="Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe

//Check if fave adds >9 
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die("Here is a message");} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1; die("Here is another message"); }

Ajax请求:

$.ajax({
  type: 'post',
  url: 'favaddDB.php',
  data: $('#addfaveform').serialize(),
  success: function (message) {
    alert(message);
  }
});

此外,您应该考虑使用JSON,将整个对象传递回javascript,并在其中进行解析:

$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');                                                                  
$query1 = "Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1 = $db->prepare($query1);
$result = $stat1->execute();// IMPORTANT add PDO variables here to make safe

// Tell javascript we're giving json.
header('Content-Type: application/json');

if (!$result) {
    echo json_encode(['error' => true, 'message' => 'A database error has occurred. Please try again later']);
    exit;
}

//Check if fave adds >9 
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
    echo json_encode(['error' => false, 'fave' => $fave, 'message' => 'Fave > 9!']);
} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {
   $fave = $fave+1;
   echo json_encode([
       'error' => false,
       'fave' => $fave,
       'message' => 'Current fave count: ' . $fave
   ]);
}

然后在ajax中,确保设置dataType: 'json',它将自动将其解析为一个对象:

$.ajax({
    type: 'post',
    url: 'favaddDB.php',
    data: $('#addfaveform').serialize(),
    dataType: 'JSON',
    success: function (res) {
        if (res.error) {
            //Display an alert or edit a div with an error message
            alert(res.message);
        } else {
            //Maybe update a div with the fave count
            document.getElementById('#favcount').value = res.fave;
            alert(res.message);
        }
    }
});

答案 1 :(得分:0)

在大多数情况下,简单为佳。 通过返回messages,您可以根据消息在前端执行任何操作。

PHP:

<?php

$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');                                                                  
$query1 = "SELECT * FROM " . $email;
$stat1 = $db->prepare($query1);
$stat1->execute();

$count = $stat1->rowCount();
$fave = $count;

if ($fave > 9) {
  echo "tooMany"; exit();
} else {
  echo "addedFav"; $fave++;
}

JS:

jQuery.post({
  url: 'favaddDB.php',
  data: jQuery('#addfaveform').serialize()
}).then(function (code) {
  switch (code) {
    case "addedFav":
      alert('Added To Favourites');
      break;
    case "tooMany":
      alert('Too many favourites');
      break;
  }
}).catch(function (error) {
  console.log(error);
});