将错误消息从php发送到ajax

时间:2022-10-08 22:03:31

I am trying to send a "notification" or error messages from php to ajax. I'm trying to achieve something like this:

我试图从php发送“通知”或错误消息到ajax。我正在努力实现这样的目标:

php:

if (myString == '') {
    // Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
    // Send "stringEqualsFoo" error to ajax
}

ajax

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(){
        alert("It works");
    },
    error: function() {
        if(stringIsEmpty) {
            alert("String is empty");
        } else if(stringEqualsFoo) {
            alert("String equals Foo");
        }
    }
});

How can I send error messages to ajax?

如何向ajax发送错误消息?

Update

Here's the php file I have. I tried using the echo solution answers said, but when I output what the data is (in ajax), I get undefined:

这是我的php文件。我尝试使用echo解决方案的答案说,但是当我输出数据是什么(在ajax中)时,我得到了未定义:

<?php
$img=$_FILES['img'];
    if($img['name']==''){
        echo('noImage');
    }else{
        $filename = $img['tmp_name'];
        $client_id="myId";
        $handle = fopen($filename, "r");
        $data = fread($handle, filesize($filename));
        $pvars   = array('image' => base64_encode($data));
        $timeout = 30;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
        $out = curl_exec($curl);
        curl_close ($curl);
        $pms = json_decode($out,true);
        $url=$pms['data']['link'];
        if($url!=""){
            echo "<h2>Uploaded Without Any Problem</h2>";
            echo "<img src='$url'/>";
        }else{
            echo "<h2>There's a Problem</h2>";
            echo $pms['data']['error'];
            header("HTTP/1.1 404 Not Found");
        } 
    }
?>

I added echo("noImage") in if($img['name']==''){

我在if中添加了echo(“noImage”)($ img ['name'] ==''){

5 个解决方案

#1


5  

The error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/

只有在请求失败时才会调用错误函数,请参阅http://api.jquery.com/jQuery.ajax/

So if you return a response from your PHP server, the error function won't be triggered. However, you can define a function to handle the error based on the response you send from PHP:

因此,如果从PHP服务器返回响应,则不会触发错误功能。但是,您可以根据从PHP发送的响应定义一个函数来处理错误:

success: function(data){
        if (data === "stringIsEmpty") {
           triggerError("stringIsEmpty");
        } else if (data === "stringEqualsFoo") {
           triggerError("stringEqualsFoo");
        }
    },

And then you can have the error function like this:

然后你可以得到这样的错误函数:

function triggerError(error) {
    if (error === "stringIsEmpty") {
        alert("Your string is empty!");
    } else if (error === "stringEqualsFoo") {
        alert("Your string is equal to Foo!");
    }
}

If you make a request to let's say post.php, you can just return a string:

如果您发出请求让我们说post.php,您只需返回一个字符串:

// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;

Or specifically for the example:

或者特别为例子:

echo "stringIsEmpty";

For more information see: How to return data from PHP to a jQuery ajax call

有关更多信息,请参阅:如何将数据从PHP返回到jQuery ajax调用

#2


3  

You can trigger the jQuery error-handler by changing the http response code in php. Any 4xx or 5xx error should work, but best stay in rfc.

您可以通过更改php中的http响应代码来触发jQuery错误处理程序。任何4xx或5xx错误都应该有效,但最好留在rfc。

PHP:

// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";

jQuery:

[...]
error: function(jqxhr) {
    alert(jqxhr.responseText)
}
[...]

#3


1  

The thing is, if your php responds, then it's technically not a error, and must be handled in the success callback.

问题是,如果你的php响应,那么它在技术上不是错误,必须在成功回调中处理。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(data){
        alert('The response is: '+data);
        if(data=="empty sting"){
            alert("The string is empty");
        } else if (data == 'foo') {
            alert("The string equals 'foo'");
        } else {
            alert("It works");
        }
    },
});

And in your PHP:

在你的PHP中:

if (myString == '') {
    echo('empty string');
} else if (myString == 'foo') {
    echo('foo');
}

#4


0  

The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...

当调用在发送过程中失败时,将触发ajax方法的“错误”设置。像“超时”,“404”等错误......

If you want to control some response of the server you can write this code in the "success" setting.

如果要控制服务器的某些响应,可以在“成功”设置中编写此代码。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(response){
          if (response == '') {
               // Send "stringIsEmpty" error to ajax
          } else if (response== 'foo') {
               // Send "stringEqualsFoo" error to ajax
          }
     }
   }

});

The PHP could be something like this

PHP可能是这样的

if (myString == '') {
    echo '';
} else if (myString == 'foo') {
    echo 'foo';
}

#5


-1  

So if your returned string is empty, or it equals "foo", you may think that is an error, but HTTP thinks it is a success, and you need to look for these strings in the "success" function.

因此,如果返回的字符串为空,或者它等于“foo”,您可能认为这是一个错误,但HTTP认为它是成功的,您需要在“success”函数中查找这些字符串。

#1


5  

The error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/

只有在请求失败时才会调用错误函数,请参阅http://api.jquery.com/jQuery.ajax/

So if you return a response from your PHP server, the error function won't be triggered. However, you can define a function to handle the error based on the response you send from PHP:

因此,如果从PHP服务器返回响应,则不会触发错误功能。但是,您可以根据从PHP发送的响应定义一个函数来处理错误:

success: function(data){
        if (data === "stringIsEmpty") {
           triggerError("stringIsEmpty");
        } else if (data === "stringEqualsFoo") {
           triggerError("stringEqualsFoo");
        }
    },

And then you can have the error function like this:

然后你可以得到这样的错误函数:

function triggerError(error) {
    if (error === "stringIsEmpty") {
        alert("Your string is empty!");
    } else if (error === "stringEqualsFoo") {
        alert("Your string is equal to Foo!");
    }
}

If you make a request to let's say post.php, you can just return a string:

如果您发出请求让我们说post.php,您只需返回一个字符串:

// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;

Or specifically for the example:

或者特别为例子:

echo "stringIsEmpty";

For more information see: How to return data from PHP to a jQuery ajax call

有关更多信息,请参阅:如何将数据从PHP返回到jQuery ajax调用

#2


3  

You can trigger the jQuery error-handler by changing the http response code in php. Any 4xx or 5xx error should work, but best stay in rfc.

您可以通过更改php中的http响应代码来触发jQuery错误处理程序。任何4xx或5xx错误都应该有效,但最好留在rfc。

PHP:

// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";

jQuery:

[...]
error: function(jqxhr) {
    alert(jqxhr.responseText)
}
[...]

#3


1  

The thing is, if your php responds, then it's technically not a error, and must be handled in the success callback.

问题是,如果你的php响应,那么它在技术上不是错误,必须在成功回调中处理。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(data){
        alert('The response is: '+data);
        if(data=="empty sting"){
            alert("The string is empty");
        } else if (data == 'foo') {
            alert("The string equals 'foo'");
        } else {
            alert("It works");
        }
    },
});

And in your PHP:

在你的PHP中:

if (myString == '') {
    echo('empty string');
} else if (myString == 'foo') {
    echo('foo');
}

#4


0  

The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...

当调用在发送过程中失败时,将触发ajax方法的“错误”设置。像“超时”,“404”等错误......

If you want to control some response of the server you can write this code in the "success" setting.

如果要控制服务器的某些响应,可以在“成功”设置中编写此代码。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(response){
          if (response == '') {
               // Send "stringIsEmpty" error to ajax
          } else if (response== 'foo') {
               // Send "stringEqualsFoo" error to ajax
          }
     }
   }

});

The PHP could be something like this

PHP可能是这样的

if (myString == '') {
    echo '';
} else if (myString == 'foo') {
    echo 'foo';
}

#5


-1  

So if your returned string is empty, or it equals "foo", you may think that is an error, but HTTP thinks it is a success, and you need to look for these strings in the "success" function.

因此,如果返回的字符串为空,或者它等于“foo”,您可能认为这是一个错误,但HTTP认为它是成功的,您需要在“success”函数中查找这些字符串。