简体   繁体   中英

Send JSON output from php function to Ajax

I have a problem, I'm working to a project in my university, the first step is to build a login form in php that works with AJAX. Now, I'm having some troubles in the function "output" in functions.php file showed below, because it prints me on screen not the protected area (the page after login), but it prints me he content of the JSON file!

function.php :

# Function to set JSON output
function output($Return=array()){
    header('Access-Control-Allow-Origin: *'); # Set response header
    header('Content-Type: application/json; charset=UTF-8');
    exit(json_encode($Return)); # Final JSON response
}

client.js : ( Note : I must use Prototype JS library for the assignment, so the '$' function and the syntax is based on the prototype documentation for a new Ajax request)

$('#login_form').submit( function() {
    new Ajax.Request('./submit.php', {
        method:'post',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            alert("Success");
            var json = transport.responseText.evalJSON(true);
        }
    });
});

submit.php :

# Check if Login form is submitted
if(!empty($_POST) /*&& $_POST['Action'] == 'login_form'*/){

    # Define return variable. for further details see "output" function in functions.php
    $Return = array('result'=>array(), 'error'=>'');

    $email = $_POST['Email'];
    $password = $_POST['Password'];

    /* Server side PHP input validation */
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $Return['error'] = "Please enter a valid Email address.";
    } else if($password === '') {
        $Return['error'] = "Please enter Password.";
    }
    if($Return['error']!='') {
        output($Return);
    }

    # Checking Email and Password existence in DB

    # Selecting the email address of the user with the correct login credentials.
    $query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
    $result = $query->fetch(PDO::FETCH_ASSOC);

    //$_SESSION['UserData'] = $result;
    if($query->rowCount() == 1) {
        # Success: Set session variables and redirect to Protected page
        $Return['result'] = $_SESSION['UserData'] = $result;
    } else {
        # Failure: Set error message
        $Return['error'] = 'Invalid Login Credential.';
    }

    output($Return);
}

I'm guessing (because you didn't show any HTML at all) that you have a

<form id="login_form" method="POST" action="./submit.php">

One problem is that you $('#login_form').submit( function() { doesn't prevent the default form submit action, so you will get the JSON

Easily fixed:

$('#login_form').submit( function(e) {
    e.preventDefault();
    // rest of your code

Now, two other issues spring to mind

header('Access-Control-Allow-Origin: *'); # Set response header - 

why are you setting Cross Origin Resource Sharing (CORS) headers on a same origin request?

if you indeed want CORS access, then

requestHeaders: {Accept: 'application/json'},

will trigger a CORS preflight check. does your server code handle a CORS preflight check? It doesn't look that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM