PHP and jQuery page refreshing issue - javascript

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);
});
});

Related

Disabling button after POST Request

How can i disable button when clicked once after post request ? In my code below, when i click the button, the post request is not executed but the button is disabled.
HTML
<form class="col s12" method="POST" action="<?php echo base_url(); ?>do/this">
<button type="submit" name="send" id="my_button"
class="waves-effect waves-green btn">My Button</button>
</form>
JS
document.getElementById("my_button").onclick = function() {
this.disabled = true;
}
document.getElementById("my_button").onclick = function(e) {
e.preventDefault();
this.disabled = true;
}
<form class="col s12" method="POST" action="<?php echo base_url(); ?>do/this">
<button type="submit" name="send" id="my_button"
class="waves-effect waves-green btn">My Button</button>
</form>
If I were you, I would use jQuery to do this.
Like that:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='s']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
});
</script>
</body>
</html>
You can disable the button in this part of the code:
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#result" ).empty().append( content );
});
Like that:
posting.done(function( data ) {
document.querySelector("#send_messages").disabled = true;
});

populate data from database using php ajax val()

i got something weird in my code. honestly, i got this from someone and i try to adapt it for my needs. So the problem is when i click fetch button, the data is not display. can any body here tell me what is wrong with the code?
Any related answer will be appreciated. Thanks in advance.
and here are my code
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var name = $('.username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
success: function( responseObject ) {
alert('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
</body>
</html>
and this is the PHP code :
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username ='admin' LIMIT 1");
$rows = mysqli_fetch_array($return);
$formattedData = json_encode($rows);
print $formattedData;`
here are the result from PHP Code :
{
"0":"1",
"id_auth":"1",
"1":"TRC-US001",
"auth_code":"TRC-US001",
"2":"admin",
"username":"admin",
"3":"5f4dcc3b5aa765d61d8327deb882cf99",
"password":"5f4dcc3b5aa765d61d8327deb882cf99",
"4":"1",
"level":"1",
"5":"2018-07-05 13:55:19.200878",
"last_login":"2018-07-05 13:55:19.200878",
"6":"1",
"status":"1"
}
this is the picture :
result
Hope this can help you
first we need to do some modification on html, and php code :
<!-- doctype is mandatory -->
<!DOCTYPE html>
<!-- language en -->
<html lang="en">
<head>
<!-- title also is mandatory -->
<title>tilte of your project</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
<!-- put all your javascript before the end of the body -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
function myrequest(e) {
// use $('#username') to select by id instead of $('.username') used to select by class
var name = $('#username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
dataType: 'json', /* this is not mandatory */
success: function( responseObject ) {
console.log('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
</body>
</html>
php code :
// this line is very important, by using this line
// the browser can recognize that the data sent from
// the server as a json object.
header("Content-type: application/json");
$formattedData = [];
if (isset($_GET['username'])) {
$username = trim($_GET['username']);
// to be sure that the username is not empty
if(empty($username)) {
print json_encode($formattedData);
exit;
}
$konek = mysqli_connect($sql_db_host, $sql_db_user, $sql_db_pass, $sql_db_name, 3306);
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username = '" . $username . "' LIMIT 1");
// use mysqli_fetch_assoc instead of mysqli_fetch_array
// $rows = mysqli_fetch_array($return);
$rows = mysqli_fetch_assoc($return);
$formattedData = json_encode($rows);
// very important every connection created need to be closed
mysqli_close($konek);
}
print $formattedData;
In your html code, there is an input with an id username. In Javascript, search for this line of code var name = $('.username').val();. Change . to #. It should be var name = $('#username').val();.
.username is for any tag that have a class username.
#username will search for a tag that have an id username.
try to parse responseObject to json using
responseObject=JSON.parse(responseObject);
in you success function

Ajax submit doesn't work (can't read $_POST in php)

I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php
$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])
test.php
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
}
?>
<html>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>
test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = "textbox=" + inputText;
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
There're more of problems here
In test.php
how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad
Scripts should be on the <head></head> or before </body>
while you using just button click why you're using <form>
your code should be something like that
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
return false;
}
?>
<html>
<head>
</head>
<body>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</body>
</div>
</html>
On test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs
If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault(); // to prevent form reload
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
});
});
you never test if you see the reponse from echo - hence you don't alert the response from php at all.
To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:
....
success: function (response) {
alert(response);
console.log(response);
},
....
Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.
Also follow #Mohammed-Yousef's instructions for the other issues!!
you will get the desired results in the response.
function hit() {
var inputText = $("#input").val();
$.ajax({
type: 'post',
url: 'test.php',
data: {textbox : inputText},
success: function (res) {
alert(res);
}
});
}
And you need to change in your test.php file.
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];exit;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="test2.js"> </script>
</head>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>

ajax jquery is not working

I am trying to submit the login request using Jquery Ajax. But the form is not submitting. I am tried to find the issue but can not. the code is vey simple but as I have started learning javascript so I am failing to find the problem in my code. Below is the code Please find the problem with it......
$(function() {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function(event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function(response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function(data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css" />
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
your html and javascript is working perfectly.
can you post your php code?.
otherwise try put this code in your login.php file:
<?php
echo "form submitted";
?>
If you are using js fiddle then import the jquery js file on the dropdown on the left side of the panel.
$(function () {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function (event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function (response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function (data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css"/>
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
Actually the problem was here. as the default form submission is prevented through javascript and I was looking for the message.
if (isset($_POST['submit_form'])) {
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
if (!empty($email) && !empty($password)) {
echo "Login Must be Successful...!";
} else {
echo "Login Failed....!";
}
}

jQuery Ajax data to same PHP page not working as INTENDED?

I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon 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 is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_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 and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_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 is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the 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>

Categories

Resources