pyxis
pyxis

Reputation: 1

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.

here is my form

<form >
 <input type="text" id="name" >
 <input type="submit" value="s"  onclick="return chl()" >
</form>

here is my js

<script>
function chl(){

  var name= document.getElementByID('name').value;
  var dataString='name' + name; 

  $.ajax({
     type:"post",
     url:"hi.php",
     data:dataString,
     cache:false,
     success: function(html){
       alert ("success"); 
     }
   });
   return false;
}
</script>

and here is my php

<?php

$name=$_POST ['name'];
echo "response".$name; 

?>

Upvotes: 0

Views: 814

Answers (6)

Varun Naharia
Varun Naharia

Reputation: 5428

Form

<form name="test" id="test">
 <input type="text" id="name" >
 <input type="submit" value="s" >
</form>

Script

<script>
$("#test").submit(function(e){
  e.preventDefault();
  var name= document.getElementByID('name').value;

  $.ajax({
     type:"post",
     url:"hi.php",
     data:{"name":name},
     cache:false,
     success: function(html){
       alert (html); 
     }
   });
   return false;
}
</script>

Upvotes: 1

David Demetradze
David Demetradze

Reputation: 1371

<form method="POST" action="server.php">
    <input type="text" name="name" id="myName" >
    <input type="submit" value="s"  onclick="chl(); return false;" >
</form>

<script>
    function chl()
    {
        var nameElement = document.getElementById("myName");  
        //Creates formData object and sends it to PHP script
        var formData = new FormData();
            //name equals to input element name attribute value    
            formData.append(nameElement.name, nameElement.value);
         var xmlHttp = new XMLHttpRequest();
             xmlHttp.onreadystatechange = function()
             {
                 if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
                 {
                     alert(xmlHttp.responseText);  
                 }
             }
             xmlHttp.open("POST", "server.php");
             xmlHttp.send(formData);

    }

</script>


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

Upvotes: 0

daulat
daulat

Reputation: 949

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method  -->
    <input type="text" id="name" />
    <input type="submit" id="click" value="s" /> <!-- Give id to your button  -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) { 
$('#click').on('click', function(event) {
    event.preventDefault();
    /* Act on the event */
    var name=$('#name').val();
    $.ajax({
        url: 'hi.php',
        type: 'POST',
        data: {name: name}
    })
    .done(function(data) {
        alert(data); // You can alert that data 
        console.log(data); //or you view this data on console  Ctrl+shift+I
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });

});

});

</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say  hi
echo 'hi';

?>

Upvotes: 1

Vivek Singh
Vivek Singh

Reputation: 2447

change ajax function like and send data as shown below and your php and js function must be in different pages

function chl(){
   var name= document.getElementByID('name').value;
   $.ajax({
      type:"post",
      url:"hi.php",
      data:{name:name},
      success: function(html){
         alert ("success"); 
      } 
   });
   return false;
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

The datastring should be formed like a querystring; you've missed the = between the key and the value:

var dataString = 'name=' + name; 

That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:

<form method="hi.php">
    <input type="text" id="name" />
    <input type="submit" value="s" />
</form>
$('form').submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: "post",
        url: this.action,
        data: $(this).serialize(),
        cache: false,
        success: function(html){
             alert(html); // = 'response: name = [VALUE]'
        }
    });
});
$name = $_POST['name'];
echo "response: name = ".$name;

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

You can also try with -

var dataString = $('form').serialize();

By this you can get rid of generating the datastring if you have a number of input fields.

Upvotes: 0

Related Questions