0

This is my html with script

<div id="info" class="container-fluid">Here is some text</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
$.post("testPHP.php", {name: "John"}, function(data)
    {
        $( "#info" ).html( data )
    })
</script>

and the php code

<?php
   $name=$_POST['name']; 
   echo $name;
?>

In html I may see the name John displayed in the div with id info. But when I run the php file I get this error

Notice: Undefined index: name in C:\xampp\htdocs\ticketing\testPHP.php on line 2

How can I send a variable via Ajax to a php file and echo this?

2
  • Is this one file or two separate files? You should have 2 files and you don't need to run the php file, only call it using $.post(). Commented Dec 23, 2015 at 10:58
  • But.. You're already sending variables (name) with AJAX to a PHP file.. What are you trying to do? Commented Dec 23, 2015 at 11:05

3 Answers 3

2

Ajax in pass some extra data like type:"ajax" and file in check

<?php
if (isset($_POST['type']) && $_POST['type']=='ajax') {
    $name = $_POST['name'];
    echo $name;
} else {
echo "You access with direct URL";
} ?>
Sign up to request clarification or add additional context in comments.

Comments

0

Try to check if there is a post request in your testPHP.php

<?php
if (isset($_POST['name'])) {
    $name = $_POST['name'];
    echo $name;
} else {
    // do something else here
}

3 Comments

I tired this and I get this error Notice: Undefined index: name in C:\xampp\htdocs\ticketing\testPHP.php on line 3 What I want to do is to have an <a> tag like this: <a href='testPHP.php'>view ticket</a> in the html file and when click to the link and redirect to testPHP.php , I want to echo the name variable.
I edited the answer, try again. If you get error please paste the error message.
Now I get "You access with direct URL" in both html and php file. This is my html code: <div id="info" class="container-fluid">Here is some text</div> <a href='testPHP.php'>view ticket</a> The idea is that when click on the link and redirect to testPHP.php I want the variable name to be echoed I have modified the script like this: $('a').click(function() { $.post("testPHP.php", {name: "John"}, function(data) { $( "#info" ).html( data ) }) })
0

It won't send any data because there is no form in it. No object will be serialized(input, select, etc.).

1 Comment

Welcome to Stack Overflow! This should be a comment, not an answer. You can leave a comment once you earn enough reputation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.