简体   繁体   中英

ajax post javascript variable to php in same page

i write sample code to ajax post javaxcript varible to php in 2 page, test.php and validate.php.

test.php :

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.min.js" ></script>

</head>
<body>
<form>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit" onclick="post();">
</form>
<div id="result" ></div>

<script type="text/javascript">
function post()
 {
var name=$('#name').val();
var age=$('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data)
{
if (data=="1")
    {
$('#result').html('you are over 18 !');
}
if (data=="0")
{
$('#result').html('you are under 18 !');
}
});
}
</script>

</body>
</html>

validate.php

<?php
$name=$_POST['postname'];
$age=$_POST['postage'];

if ($age>=18)
{
echo "1";
}
else
{
echo "0";
}
?>

how can i write/change above code in same page ?? and validate.php insert in test.php ??

added after first answer : "but i dont have/use any button or in my page. and where can i insert validate.php code in test.php. please help by insert complete correct code."

Try adding a submit() method to your <form> rather than attaching the event to the submit button.

$(document).on('submit', 'form', function(){
    post();
    return false;
});

At the moment I think your form is submitted no matter what, you have to either return false on submit or preventDefaults()

A good idea is also to add an ID to your form in case you have more than one on your page and use the relevant selector in the .on event handler such as

$(document).on('submit', $('#form-id'), function(){ ... });

ajax is use for exchanging data with a server. If you want write code in same page so reload page and write validate.php code above of test.php like this

<?php
   //validate.php code
?>
<form action=test.php type=POST>
  <input type="text" id="name" placeholder="enter Your name...." /><br/>
  <input type="text" id="age" placeholder="enter Your age...." /><br/>
  <input type="button" value="submit">
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM