javascript - How to pass on a form through Ajax, and PHP -


i'm new this, want work simple code i'll add onto it. it's not working in sense don't echo. want submit form , have not refresh page.

here form

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

here 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 php

<?php  $name=$_post ['name']; echo "response".$name;   ?> 

the datastring should formed querystring; you've missed = between key , value:

var datastring = 'name=' + name;  

that being said, can improve code. firstly should attach event submit of form, , use event.preventdefault() stop normal form submission. also, can use serialize() generate object containing forms' values pass across in ajax request. response php code retuned in parameter sent success handler, need there. lastly, should attach events in js, not html attributes, 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; 

Comments