简体   繁体   中英

How to post data from javascript to php

I try to post single data to php page using javascript but can't get it right.. here's the code i tried:

try.js:

$(document).ready(function(){
var data = 1;
$.post( "data.php", { test_data: data});
});

data.php:

<?php
$test_data = $_POST[test_data];
echo $test_data
?>

when I access file data.php it says "Use of undefined constant test_data" and "Undefined index: test_data"..why is that?? can someone tell me what is wrong in the code please??

This isn't valid PHP:

$test_data = $_POST[test_data];

As the error indicates, test_data isn't a known constant. You need to use a string literal:

$test_data = $_POST["test_data"];
  1. You're posting to the wrong file. Why post to try.php if your server-side file is data.php

  2. test_data in $_POST[] should be a string, not a constant. use $_POST['test_data'] .

  3. You will still see an error because when you directly access data.php you don't post anything, so $_POST[] is actually empty.

$_POST[test_data]; != $_POST['test_data']

When you do $_POST[test_data] , you're checking if $_POST (an array) has the key test_data . But global variables ( $_POST , $_GET , $_SERVER ) never have a constant as selector. Check for a string.

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