javascript - jQuery Ajax data to same PHP page not working as INTENDED? -
i have 22.php both form , php script reside.
problems;
1) when submit, result shows below. duplicates form.
2) further entering in top (above) form, changes result accordingly.
3) when enter in bottom form, result changes accordingly , disappear bottom from.
what have tried far solutions;
1) removed totally - url: '',
2) replaced same page - url: '22.php',
3) replaced - var yourdata = $(this).serialize();
4) placed php script after body tag
none of above solve! please help!
<html> <head> <title>my first php page</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(event){ event.preventdefault(); var myname = $("#name").val(); var myage = $("#age").val(); var yourdata ='name='+myname+'&age='+myage; // php expecting name , age $.ajax({ type:'post', data:yourdata,//without serialized //url: '22.php', success:function(data) { if(data){ $('#testform')[0].reset();//reset form $('#result').html(data); // here html() //alert('submitted'); }else{ return false; } } }); }); }); </script> </head> <body> <?php if ( isset($_post['name']) ) { // form submitted? echo "welcome ". $_post["name"] . "<br>"; echo "you ". $_post["age"] . "years old<br>"; } ?> <form method="post" id="testform"> name: <input type="text" name="name" id="name" />age: <input type="text" name="age" id="age" /> <input type="submit" name="submit" id="btn" /> </form> <div id='result'></div> </body> </html>
just place php code top , put exit();. here full code:
<?php if ( isset($_post['name']) ) { // form submitted? echo "welcome ". $_post["name"] . "<br>"; echo "you ". $_post["age"] . "years old<br>"; exit; } ?> <html> <head> <title>my first php page</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#btn").click(function(event){ event.preventdefault(); var myname = $("#name").val(); var myage = $("#age").val(); var yourdata ='name='+myname+'&age='+myage; // php expecting name , age $.ajax({ type:'post', data:yourdata,//without serialized //url: '22.php', success:function(data) { if(data){ $('#testform')[0].reset();//reset form $('#result').html(data); // here html() //alert('submitted'); }else{ return false; } } }); }); }); </script> </head> <body> <form method="post" id="testform"> name: <input type="text" name="name" id="name" />age: <input type="text" name="age" id="age" /> <input type="submit" name="submit" id="btn" /> </form> <div id='result'></div> </body> </html>
Comments
Post a Comment