Pass the PHP variable back to the jQuery $ .ajax function

1. HTML

I have an input that asks the user to enter a PIN code:

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

2. JavaScript

When the user enters 4 characters, the jQuery function starts an ajax call to process the PIN in the PHP file and returns 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 return the value of $site back to the success function of the ajax call. The console log report is null as a value if the output is not faf9 , and there is no log if I enter the correct output.

I can not understand where I am mistaken?

+4
source share
5 answers

Change dataType to:

 dataType: 'HTML', 

That's all:)

+8
source

your php returns a string, but you expect a JSON object. Change your data type attribute inside the $.ajax function

+2
source

For dataType: "json" you need to return a json object. If not, change this type using the appropriate dataType: "html" or dataType: "text"

In addition, you need to initialize $site if you do not need to return null.

+2
source

Make the following changes:

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

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

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

+2
source

This m8 is not your specific issue, but I think you should use $(this) without quotes

+1
source

Source: https://habr.com/ru/post/1413892/


All Articles