Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PHP variable back to jQuery $.ajax function

1. HTML

I have an input requesting the user to enter their PIN code:

<input type="text" name="pin" maxlength="4" id="pin" />

2. javaScript

When the user types in 4 characters, the jQuery function fires off an ajax call to process the PIN in a PHP file and return the corresponding site name:

$("input#pin").keyup(function() {
    var PIN = $("this").val();

    if (PIN.length == 4) {

        var dataString = "PIN=" + PIN;

        $.ajax({
            type: "POST",
            url: "pins.php",
            dataType: "json",
            data: dataString,
            cache: false,
            success: function(site)
                {
                    console.log("site name is:" + site);
                }
        });
    }
});    

3. PHP

pins.php contains the following code:

<?php
$pin = $_POST["PIN"];

if ($pin == "faf9") {
    $site = "pgv";
}

echo $site;
?>

Problem

I cannot seem to get the value of $site back into the success function of the ajax call. Console log reports null as the value if the pin doesn't equal faf9 and there is no log if I enter the correct pin.

I can't seem to figure out where I'm going wrong?

like image 969
izolate Avatar asked Dec 07 '22 14:12

izolate


1 Answers

Change dataType to:

dataType: 'HTML',

That is all :)

like image 155
John Shepard Avatar answered Dec 10 '22 13:12

John Shepard