user3271403
user3271403

Reputation: 143

Sending information by javascript into PHP

I want to send information of 1 variable with javascript into PHP.

So , i used this code (in index.php) :

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    <script>
        $.post('http://localhost/test/index.php', {
            name: $('.class').html();
        });
        $(document).ready(function(){
           $("#my_form").on("submit", function () {
               var hvalue = $('.class').text();
               $(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
        });
    });
</script>
<form action="" method="post" id="my_form">
    <div class="class" name="name">
        this is my div
    </div>
    <input type="submit" value="submit" name="submit" />
</form>
<?php 
    if(isset($_POST['name'])){ $name = $_POST['name']; } 
    echo $name;

But i see this error :

Notice: Undefined variable: name in C:\Program Files\EasyPHP-5.4.0RC4\www\test\index.php on line 22

What can i do ?

Upvotes: 0

Views: 56

Answers (2)

Farzad
Farzad

Reputation: 852

also , In using jQuery , you didn't closed the tag :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

close like this and use this code :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.post('http://localhost/test/index.php', {
name: $('.class').html();
});
$(document).ready(function(){
   $("#my_form").on("submit", function () {
        var hvalue = $('.class').text();
        $(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
    });
});
</script>
<form action="submit.php" method="post" id="my_form">
<div class="class" name="name">
this is my div
</div>
<input type="submit" value="submit" name="submit" />
</form>

Upvotes: 0

sachleen
sachleen

Reputation: 31131

$name is not defined. You have the echo outside of the if statement, move it inside the braces.

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

Also, you post to submit.php but this code is for index.php... so you need to fix that, too.

Upvotes: 1

Related Questions