简体   繁体   中英

Javascript Variable passing to PHP with Ajax

I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.

Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?

Keeping it simple for demonstration purposes, but this is the functionality I desire..

zipCode.js:

$(document).ready(function() {

var zip = '123456';
    $.ajax({
    url: 'zip.php',
    data: {zip_code:zip},
    type: 'POST'
    });
});

zip.php:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>

</head>
<body>
<?php

echo $_POST['zip_code'];

?>

</body>
</html>

An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?

You are supposed to put this:

<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>

on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code . Also, set your dataType:'JSON' in $.ajax({/*here*/}) .

Here:

var zip = '123456';
$.ajax({
  url: 'zip.php',
  data: {zip_code:zip},
  type: 'POST',
  dataType: 'JSON',
  success: function(data){
    // in here is where you do stuff to your page
    console.log(data.zip_code);
  }
});

When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.

If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd

The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.

The current setup you have doesn't make sense in practice

That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results ( Received ZIP code 123456 )

start_page.html:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
    This is just a static page.
</body>
</html>

zipcode.js:

$(document).ready(function() {
    var zip = '123456';
        $.ajax({
        url: 'handle_post.php',
        data: {zip_code:zip},
        type: 'POST',
        success: handleData
        });
    });
}

function handleData(data) {
    alert(data);
}

handle_post.php:

<?php
die ('Received ZIP code ' . $_POST['zip_code']);

As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:

  • zip.php will be parsed on the server (and resulting in the error)
  • Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
  • browser will see the javascript .ready() and run that code
  • server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)

Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.

try this to give you better idea of what's happening.

$.ajax({
  url: 'zip.php',
  data: {zip_code:zip},
  type: 'POST'
});.done(function(data ) {
  console.log(data)
});

In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.

You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like

if(isset($_POST['zip_code'])){ 
    echo $_POST['zip_code];
}

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