Javascript Variable passing to PHP with Ajax -


i've started working ajax little lately, i'm having trouble feel incredibly simple: storing js variable in php.

say want store zip code (assigned javascript) , pass php variable via ajax: why doesn't work?

keeping simple demonstration purposes, functionality 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" returned. shouldn't "123456" echo'd out?

you supposed put this:

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

on separate page, not html page. ajax sends page, can use , echo out, making database queries before that, or have you. upon success see result of echo argument passed success method in case if used data argument result zip_code held in data.zip_code. also, set 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 stuff page     console.log(data.zip_code);   } }); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -