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
Related
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>
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....!";
}
}
I have to insert data through jQuery and ajax method. But data is not inserting in database. Pleas help me is this method is wrong?
Here is my code,
form.html
<!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- <script src="jquery-3.1.0.js" type="text/javascript"></script>-->
<script type="text/javascript">
function submitData()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
var contact = document.getElementById('contact')
$.ajax({
type: 'POST',
url: 'data_ins.php',
data:{
uname:name,
uage:age,
ucontact:contact
},
success: function(response){
$('#success_para').html("Data inserted");
}
});
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="return submitData();">
name : <input type="text" name="name" id="name"> <br>
age : <input type="text" name="age" id="age"> <br>
contact : <input type="text" name="contact" id="contact"> <br>
<input type="submit" name="submit" >
</form>
<p id="success_para"></p>
</body> </html>
and, data_ins.php
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$name = $_POST['uname']; $age = $_POST['uage']; $contact = $_POST['ucontact'];
if(!$conn) {
echo"<script>alert('Database Connection Failed or invalid connection');</script>"; }
else {
$sql = "insert into records (name, age, contact) values ('$name', '$age', '$contact')"; mysqli_query($conn, $sql);
mysqli_error($conn); }
?>
Please let me know what's wrong in my code. Thanks, in advance.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
Your "submit" button causes page reloading, so you'll not be able to see the result of a query in your onSuccess.
<input type="button" name="submit" onclick="submitData();" >
Have you checked your response? You can also view it in browser's inspector.
success: function(response){
$('#success_para').html(response);
}
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>
I am trying to understand the basics of using AJAX in conjunction with PHP in order to use php pages to provide functions, but not change my 'view' on my MVC design.
So I created this basic login page...
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$(#"login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
};
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
</form>
<div id="message"></div>
<div>
</body>
</html>
And this was my php page to "handle" to login...
<?php
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username == 'demo' && $password == 'demo')
{
echo 'success';
}
}
?>
The problem I am having is that whenever I submit my login, I am redirected to "/loginForm.php" instead of staying on my current page and having the message change underneath the login form.
I tried using Firebug to help me track down what I suspected to be a javascript error, but to no avail.
Any idea on why I am being redirected or why the form is not submitting via Ajax?
One more mistake here
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
}); <--- You Missed ")" here
}
a small mistake
$(#"login").click(function() {
This should be
$("#login").click(function() {
^ // # inside quotes.
Besides the typo and Rocky's good catch on the }); <--- You Missed ")" here
Both your username and password fields are the same.
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
and
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
the 2nd one should read as
<input type="text" id="password" name="password" />
In using everyone's answer, you will have yourself a working script.
Remember to hash your password once you go LIVE.
Edit sidenote: I've made a note below about using a button, rather than an input.
Here's a rewrite, just in case. However that input needs to be a <button>.
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
});
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="password" name="password" />
<!--
Your original input
<input type="text" id="username" name="username" />
-->
</p>
<button type="submit" id="login" name="login" />LOGIN</button>
<!--
Your original submit input. Don't use it
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
-->
</form>
<div id="message"></div>
</div>
</body>
</html>
Your last div just before </body> was unclosed </div>, I've changed that above.
Additional edit from comments.
It seems that there was probably a space inserted somewhere and the use of trim() was the final nail to the solution.
response.trim();
A special thanks goes out to Jay Blanchard to have given us a helping hand in all this, cheers Sam!
References (TRIM):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
http://php.net/manual/en/function.trim.php