将错误消息从php发送到ajax

时间:2015-11-11 18:48:36

标签: javascript php jquery ajax

我正在尝试从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");
        }
    }
});

如何向ajax发送错误消息?

更新

这是我的php文件。我尝试使用echo解决方案的答案,但是当我输出data的内容(在ajax中)时,我得到undefined

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

我在echo("noImage")

中添加了if($img['name']==''){

6 个答案:

答案 0 :(得分:5)

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

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

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

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

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

如果您提出让post.php说出来的请求,您只需返回一个字符串:

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

或者特别针对这个例子:

echo "stringIsEmpty";

有关详细信息,请参阅:How to return data from PHP to a jQuery ajax call

答案 1 :(得分:3)

您可以通过更改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)
}
[...]

答案 2 :(得分:1)

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

Timespan

在你的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");
        }
    },
});

答案 3 :(得分:0)

&#34;错误&#34;当调用在发送过程中失败时,将触发ajax方法的设置。错误如&#34;超时&#34;,&#34; 404&#34;等...

如果您想控制服务器的某些响应,您可以在&#34; success&#34;设置。

$.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
          }
     }
   }

});

PHP可能是这样的

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

答案 4 :(得分:0)

我已经尝试过使用带有错误处理功能的jQuery AJAX和PHP引导程序模型

JavaScript文件:

// add receipt data
        $('#insert_form').on("submit", function(event) {
            event.preventDefault();
            $.ajax({
                url: "includes/user-insert.inc.php",
                method: "POST",
                data: $('#insert_form').serialize(),
                async: true,
                beforeSend: function() {
                    $('#insert').val("Inserting");
                },
                success: function(data) {

                    $('#insert_form')[0].reset();
                    $('#add_reciept').modal('hide');
                    dataTable.ajax.reload(null, false);

                    if (data == "No") {
                        $('#alert-danger').addClass('alert alert-danger');
                        $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                        $('#alert-danger').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-danger').fadeOut("slow");
                        }, 8000);
                    } else if (data == "Yes") {
                        $('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
                        $('#alert-success').addClass('alert alert-info');
                        $('#alert-success').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-success').fadeOut("slow");
                        }, 8000);
                    }


                },
                error: function(err) {
                    $('#alert-danger').addClass('alert alert-danger');
                    $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                    $('#alert-danger').fadeIn().show();
                    setTimeout(function() {
                        $('#alert-danger').fadeOut("slow");
                    }, 8000);
                },
                complete: function(data) {
                    $('#insert').val("Insert");
                }
            });

        });

process.inc.php文件:

    // check users again or not
  $sql = "SELECT * FROM users_acc WHERE U_Email='$U_Email'";
  $result = mysqli_query($conn, $sql);
  $resultCheck = mysqli_num_rows($result);

  if ($resultCheck > 0) {
    echo 'No';
  } else {

    $query = "
        INSERT INTO users_acc(Firstname, Lastname, U_Email, U_Password, Gender, user_role_id)  
         VALUES('$Firstname', '$Lastname', '$U_Email', '$U_Password', '$Gender' , '$user_role_id')
        ";
    echo 'Yes';
}

答案 5 :(得分:-1)

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