4

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?

5 Answers 5

8

Change dataType to:

dataType: 'HTML',

That is all :)

Sign up to request clarification or add additional context in comments.

1 Comment

Or change dataString to dataString:{PIN:PIN}
2

your php returns a string but you're expecting a JSON object. Change your datatype attribute inside $.ajax function

Comments

2

For dataType: "json", you have to return json object. If not, chang that type with appropriate one like dataType: "html" or dataType: "text"

Also, you need to initialize $site if you don't want null return value.

2 Comments

Initialize $site -- can you elaborate please?
@muppethead if it json $site='{}';. if html/text $site='';. Write the line before if syntax.
2

Make following modifications as:

  • Replace var PIN = $("this").val(); with var PIN = $(this).val();

  • Replace var dataString = "PIN=" + PIN; with var dataString = PIN;

  • Replace dataType: "json", with dataType: "html",

2 Comments

I'm pretty curious about why you changed your mind about this: Replace var dataString = "PIN=" + PIN; with var dataString = PIN;
I was assuming that you're using $.post() method in which you should pass a variable as pin: PIN and use it as $_GET['pin'] on server-side. But you're using $.ajax(), I lately recognize hence did that change! ;)
1

This m8 not be relevant to your exact problem, but i think you should use $(this) without quotations

1 Comment

Good catch. I do have $(this) in my code. Not sure why I added quotes here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.