Return errors from PHP run via. AJAX?

后端 未结 4 854
轻奢々
轻奢々 2020-12-02 20:23

Is there a way to get PHP to return an AJAX error code if the PHP script fails somewhere? I was following a tutorial and typed this in to my PHP:

$return[\'error\         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 20:47

    For simple transfer of data from PHP to AJAX, Json encoding or key value pairs are not always necessary. It can be simply done using string handling.

    A sample code explaining this functionality is below.

    
        $query = "SELECT email FROM login WHERE email = '". mysqli_real_escape_string($conn,$email) ."' AND password = '". mysqli_real_escape_string($conn,$pass) ."'" ;
    
        $result = mysqli_query($conn,$query);
        $row=mysqli_fetch_row($result);
    
        $row_cnt = mysqli_num_rows($result);
        $s_email = $row[0];
    
        if ($row_cnt == 1) {
            $response="success";
        } else {
        $response = "Invalid Credentials";
        }
    
        $conn->close();
    
        $_SESSION["email"]= $s_email;
        echo $response;
    
    

    This code shows how a 'success' response is sent back to ajax calling the php code. Further in ajax the following could be done to retrieve the response.

    
        $.ajax({ type : 'POST',
              data : {email: $('#email').val(), password: $('#pass').val()},
              url  : 'login.php',              
              success: function (data) {
                if(data == 'success'){  //the value echoed from php can be stored in the data variable of ajax
                    window.location.assign('upload.php');
                }
                else{
                    alert(data);
                }
              },
              error: function ( xhr ) {
                alert("error");
            }
        });
    
    

    The above concept can be extended to return MULTIPLE VALUES also. This method allows simple tranfer of data from PHP to AJAX in a string format.

    We have to follow a simple step of echoing everything we need to send as a response from the php to ajax, seperated by a unique seperator.

    
        echo $response.#;
        echo $email.#;
        echo $password.#;
        echo "Hello".#;
        echo "World";
    
    

    Then the variable data in ajax could be simply retrieved as in the above example and a simple function like,

    
        var res = data.split("#");
    
    

    data, being the variable within ajax. The res array can then be used within js for whatever purpose we need.

提交回复
热议问题