0

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??

2
  • I don't know about the undefined constant error, but use $_POST['test_data']; instead of $_POST[test_data];. And, if you access try.php directly using your browser, the index is of course undefined as you didn't post any data to the script. Commented Sep 29, 2013 at 12:46
  • Post some more code of both files. I hope you have included the jQuery library in your file. Also check if the page contains any JavaScript errors using your browser's developer tools. Commented Sep 29, 2013 at 13:50

3 Answers 3

2
  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.

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

2 Comments

sorry my bad, wrong typo..if I cannot directly access data.php so how to know if the value I wanna post to data.php is correct or not??
You can either get the response from the page (api.jquery.com/jQuery.post) , or use a chrome extension like Postman, so you can manually create the POST data. chrome.google.com/webstore/detail/postman-rest-client/…
2

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"];

2 Comments

Sorry my bad..wrong typo...I already try $test_data = $_POST["test_data"]; and $test_data = $_POST['test_data']; but it says undefined index
@reza: Well, according to your code you're posting the value to try.php but the code is on data.php. You need to post the value to the page which has the code, or put the code on the page which receives the posted value. Or perhaps include one in the other. Either way, the PHP code in question needs to be executed when the value is posted.
0

$_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.

1 Comment

sorry my bad, wrong typo...I already try $test_data = $_POST["test_data"]; and $test_data = $_POST['test_data']; but it keep says undefined index

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.