如何使用 PHP 为 JQuery .ajax() 返回正确的成功/错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9676084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:24:21  来源:igfitidea点击:

How do I return a proper success/error message for JQuery .ajax() using PHP?

phpjqueryhtmlajax

提问by Pieter

I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.

我不断收到错误警报。MYSQL 部分没有任何问题,查询被执行,我可以在数据库中看到电子邮件地址。

The client side:

客户端:

<script type="text/javascript">
  $(function() {
    $("form#subsribe_form").submit(function() {
      var email = $("#email").val();

      $.ajax({
        url: "subscribe.php",
        type: "POST",
        data: {email: email},
        dataType: "json",
        success: function() {
          alert("Thank you for subscribing!");
        },
        error: function() {
          alert("There was an error. Try again please!");
        }
      });
      return false;
    });
  });
</script>

The server side:

服务器端:

<?php 
$user="username";
$password="password";
$database="database";

mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");

$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";

if($senderEmail != "")
    $query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();

$response_array['status'] = 'success';    

echo json_encode($response_array);
?>

回答by Muhammad Abrar

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

如果您使用 JSON 数据类型,则需要提供正确的内容类型。在回显 json 之前,放置正确的标题。

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Additional fix, you should check whether the query succeed or not.

附加修复,您应该检查查询是否成功。

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

On the client side:

在客户端:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Hope it helps.

希望能帮助到你。

回答by Alex

Just so you know, you can use this for debugging. It helped me a lot, and still does

正如您所知,您可以使用它进行调试。它对我有很大帮助,现在仍然如此

error:function(x,e) {
    if (x.status==0) {
        alert('You are offline!!\n Please Check Your Network.');
    } else if(x.status==404) {
        alert('Requested URL not found.');
    } else if(x.status==500) {
        alert('Internel Server Error.');
    } else if(e=='parsererror') {
        alert('Error.\nParsing JSON Request failed.');
    } else if(e=='timeout'){
        alert('Request Time out.');
    } else {
        alert('Unknow Error.\n'+x.responseText);
    }
}

回答by Marc B

Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.

有些人建议使用 HTTP 状态代码,但我很鄙视这种做法。例如,如果您正在使用搜索引擎并且提供的关键字没有结果,则建议返回 404 错误。

However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WASfound.

然而,我认为这是错误的。HTTP 状态代码适用于实际的浏览器<->服务器连接。关于连接的一切都很顺利。浏览器发出请求,服务器调用您的处理程序脚本。脚本返回“无行”。没有在表示“404页找不到” -页WAS找到。

Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.

相反,我倾向于将 HTTP 层与服务器端操作的状态分开。我不是简单地在 json 字符串中返回一些文本,而是总是返回一个 JSON 数据结构,它封装了请求状态和请求结果。

e.g. in PHP you'd have

例如在 PHP 中,你会拥有

$results = array(
   'error' => false,
   'error_msg' => 'Everything A-OK',
   'data' => array(....results of request here ...)
);
echo json_encode($results);

Then in your client-side code you'd have

然后在您的客户端代码中,您将拥有

if (!data.error) {
   ... got data, do something with it ...
} else {
   ... invoke error handler ...
}

回答by philippe

In order to build an AJAX webservice, you need TWO files :

为了构建 AJAX 网络服务,您需要两个文件:

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
  • 使用 JQuery AJAX 将数据作为 POST(可以作为 GET)发送的调用 Javascript
  • 一个返回 JSON 对象的 PHP 网络服务(这方便返回数组或大量数据)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

因此,首先您在 JavaScript 文件中使用此 JQuery 语法调用您的网络服务:

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);
     }
});

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

您的 PHP 文件(mywebservice.php,如 AJAX 调用中所写)应在其末尾包含类似内容,以返回正确的成功或错误状态:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

回答by Frank Violette

I had the same issue. My problem was that my header type wasn't set properly.

我遇到过同样的问题。我的问题是我的标题类型设置不正确。

I just added this before my json echo

我只是在我的 json echo 之前添加了这个

header('Content-type: application/json');

回答by larachiwnl

Server side:

服务器端:

if (mysql_query($query)) {
    // ...
}
else {
    ajaxError(); 
}

Client side:

客户端:

error: function() {
    alert("There was an error. Try again please!");
},
success: function(){
    alert("Thank you for subscribing!");
}

回答by Roland Roos

...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

...您可能还想检查跨站点脚本问题...如果您的 html 页面来自不同的域/端口组合,那么您的休息服务,您的浏览器可能会阻止调用。

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

通常,鼠标右键->检查您的 html 页面。然后在错误控制台中查看类似的错误

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

从源 '...:8383' 访问 XMLHttpRequest at '...:8080' 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。

回答by Francois Brand

adding to the top answer: here is some sample code from PHP and Jquery:

添加到最佳答案:这里是一些来自 PHP 和 Jquery 的示例代码:

$("#button").click(function () {
 $.ajax({
            type: "POST",
            url: "handler.php",
            data: dataString,

                success: function(data) {

                  if(data.status == "success"){

                 /* alert("Thank you for subscribing!");*/

                   $(".title").html("");
                    $(".message").html(data.message)
                    .hide().fadeIn(1000, function() {
                        $(".message").append("");
                        }).delay(1000).fadeOut("fast");

                 /*    setTimeout(function() {
                      window.location.href = "myhome.php";
                    }, 2500);*/


                  }
                  else if(data.status == "error"){
                      alert("Error on query!");
                  }




                    }


        });

        return false;
     }
 });

PHP - send custom message / status:

PHP - 发送自定义消息/状态:

    $response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!';   /* add custom message */ 
    header('Content-type: application/json');
    echo json_encode($response_array);