I have a problem where i am getting data from a PHP script using jQuery which works however the data instantly vanishes as i can only assume the page is refreshing for some reason.
How can i return "Hello world" and keep it on the page?
My HTML/JS code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$( "#target" ).submit(function( event ) {
var usr = $("#username").val();
var pass = $("#password").val();
$.post("script.php", {username: usr, password: pass}, function(result){
$("#result").html(result);
});
});
});
</script>
</head>
<body>
<p>Start typing a name in the input field below:</p>
First name:
<form id="target">
<input id="username" type="text" value="User">
<input id="password" type="text" value="pass">
<input type="submit" value="Go">
</div>
<span id="result"></span>
</body>
</html>
The PHP code:
<?php
echo "Hello World";
?>
You are submitting the form with $( "#target" ).submit() so you need to prevent that from happening with event.preventDefault();
$( "#target" ).submit(function( event ) {
event.preventDefault(); // add this line
var usr = $("#username").val();
var pass = $("#password").val();
$.post("script.php", {username: usr, password: pass}, function(result){
$("#result").html(result);
});
});
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.