Sikret Miseon
Sikret Miseon

Reputation: 557

pass values from a textfield of a form to php using jquery ajax

What i have in mind is an alert box that greets the user of a name that is specified in the textfield after pressing the button

<html>
<head>
<script type="text/javascript" src="jquery-1.6.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){


  $("#btnSubmit").click(function(e){
   e.preventDefault();

     $.ajaxSetup ({  
        cache: false  
     }); 

     dataString = $("#testform").serialize();

     $.ajax({
        type: "POST",
    url: "test.php",
    data: dataString,
    success: function(data){
        alert(data);
    }
      }); 
  });


});
</script>
</head>


<body>
  <form id="testform">
    <input type="text" name="jeds" value="jed" id="jedid">
  </form>    
  <input type="button" id="btnSubmit" value="submit">    
</body>

test.php

    <?PHP
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $name = $_POST['name'];
        print "hello " . $name;
        }
    ?>

im not sure why it can't catch the name.

Upvotes: 1

Views: 681

Answers (3)

Ashutosh Mishra
Ashutosh Mishra

Reputation: 407

I think you have not mentioned the method in the form tag(by default it is GET). you are requesting the variable from $_POST. give method name as post

Upvotes: 1

xdazz
xdazz

Reputation: 160833

<input type="text" name="jeds" value="jed" id="jedid">

should be

<input type="text" name="name" value="jed" id="jedid">

Upvotes: 1

stealthyninja
stealthyninja

Reputation: 10371

Change

<form id="testform">
<input type="text" name="jeds" value="jed" id="jedid">
</form>

<input type="button" id="btnSubmit" value="submit">

to

<form id="testform" method="post">
    <input type="text" name="jeds" value="jed" id="jedid">
    <input type="button" id="btnSubmit" value="submit">
</form>

and

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['name'];
    print "hello " . $name;
}

to

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = $_POST['jeds'];
    print "hello " . $name;
}

Upvotes: 2

Related Questions