I'm trying to create a simple login with PHP and MySQL and I'm using the AJAX() jquery function to load the PHP script.
All that I want to do is to load a new web page (for example java2s.com) when the script finds the user in my database.
Problem is that the script won't work at all.
This is the HTML with the Jquery:
EDIT: This is the fixed code thanks to all those who commented, which sadly still doesn't work.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
)
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" id="loginForm" class="button positive">
</body>
</html>
The PHP script is very simple:
<?php
$data = file_get_contents('php://input');
$result = json_decode($data);
$con=mysqli_connect("localhost","****","*****","*******");
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."';";
$exists = mysqli_query($con,$str);
if (mysqli_num_rows($exists) ==1)
{
$arr = array('result'=>"login successful");
$ris=json_encode($arr);
echo $ris;
}
else
{
$arr= array('result'=>"login error");
$ris=json_encode($arr);
echo $ris;
}
mysqli_close($con)
?>
When I load the page and press the submit button nothing will happen.
Anyone can help?
Thank you very much in advance
try something like this
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonlogin,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
EDITED CODE
you have not implemented DOM ready method correctly
$(document).ready(function(){
// code goes here
});
Maybe because all the php is commented out?
Also in your success function should look like this:
success: function(response){
dosomethingwithrespones(response);
}
The data in the $.ajax denotes what you send.
why are you using function ajaxJson()... try to remove it and if you really want to use it then modify your button code like this and remove $("#loginForm").click(function() { } from jquery...
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
and change <script type="text/javascript"> instead of <script language="javascript">.. this identifier is not standard, this attribute has been deprecated(outdated by newer constructs) in favor of type.
first way
function ajaxJson()
{
//your code goes here without triggering **click** event..
}
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
second way
$("#loginForm").click(function()
{
//your code goes here...
}
<input type="submit" id="loginForm" class="button positive">
keep everything outside $(document).ready function...
hope it may help you
You have missed ending { and } for ready function.try below code.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(function () {
$("#loginForm").click(function() {
alert("hi");
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
});
});
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="button" id="loginForm" class="button positive">
</body>
</html>
try this query in login.php,
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."' ";
Jquery:
$(document).ready(function(){
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
dataType: 'json',
data: sendstr,
success:function(response){
if (response.result=="login successful")
{
change();
}else{
alert(response.result);
return false;
}
}
});
});
});
Related
I have the following code that i wish to use to submit form without reloading the page, but it reloads the entire page and when checked in console the script.php page is also not getting executed.
Code on index.php page
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
code on script.php page
<?php
$name=$_POST['name'];
echo $name;
?>
Can anyone please tell how i can submit the form without reloading the page and also display the result from script.php page on index.php page
update your function. pass event object in function. and use event.preventDefault() to prevent default submit action.
$(".submit").click(function(e) {
e.preventDefault();
try this
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
OR
<input type="button" class="submit" />Submit
You need to send the data from the script.php page back to your index.php page. Swich out the little bit of ajax for this:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
In your script.php:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>
Do not mix form submit and button click.
If you are a click event of button then use type="button" and if you are doing $("form").submit() then use type="submit".
Also check for
$(".submit").click(function(e) {
e.preventDefault();
and check your ajax post data , do
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});
Instead of listening to the input's click event, you should listen to the form's submit.
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>
I am trying to pass the form value "New Value" from jQuery to a PHP script, and then update the "to_change" div from "Old value" to "New value". It seemed like the AJAX call succeeded, but the POST variables are not being sent to the PHP script, and when I use getJSON, I do not succeed. How could I resolve this issue?
Javascript/HTML code:
<html>
<head>
<script src = 'jquery-1.10.2.js'></script>
<script>
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
$.getJSON("parameters_form2.php", function(tmin) {
document.getElementById("to_change").innerHTML = tmin[1];
});
}
});
return false;
});
});
</script>
</head>
<body>
<div id="to_change">Old value</div>
<form id="form_tmin" name="form_tmin">
<input type="hidden" id="tmin_value" name="tmin_value" value="New value">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
PHP code:
<?php
header('Content-Type: application/json');
if ($_POST["tmin_value"]) {
$tmin[1] = $_REQUEST["tmin_value"];
}
else {
$tmin[1] = "FAILURE";
}
echo json_encode($tmin);
?>
You already have json response in data just set this data in where ever you want to display. you don not need $.getJSON again.
try like this:
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
document.getElementById("to_change").innerHTML = data[1];
}
});
return false;
});
});
You already have the response of query, no need to use $.getJson again
Instead just use:
success: function(data){
$("to_change").html(data[1]);
}
i tried to Submit my form with ajax with out reloading the whole page, but the ajax is not working, here is the code i used
$("#sendingform").submit(function(){
var mess = $("#urmess").val();
var mid = "1";
alert (mid);
$.ajax({
url: 'ajax/send.php',
data: { mid: mid, mess: mess},
success: function (data){
alert(data);
}
});
return false;
});
the html is
<hr/>
<form action="#" id="sendingform" method="post">
<textarea id="urmess" class="conposer" name="messtxt"></textarea>
<input type="submit" class="sendbtn" name="go" class="send" value="Send"/>
</form>
Try this
$(function(){ /* Execute when the DOM is ready */
$(document).on("submit","#sendingform",function(e){
e.preventDefault(); /* Prevent the default action of the form */
var mess = $("#urmess").val(); /* Get the textarea value */
var mid = "1";
alert (mid); /* Alert 1 */
$.ajax({
url: 'ajax/send.php',
data: {
mid: mid,
mess: mess
}, /* Define AJAX data */
success: function (data){
alert(data); /* Alert return */
}
});
});
});
Here's The Code Hows Your PHP Code Must Look Like :
<?php
$a=json_decode($_POST["Jdata"]);
$con=mysql_connect("localhost","root","");
mysql_select_db("json",$con);
$t=$a->mess;
$u=$a->mid;
$x=mysql_query("insert into test(data1,data2) values('$t','$u')");
?>
And Here's HTML+JQuery Code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form action="#" id="sendingform" method="post">
<textarea id="urmess" class="conposer" name="messtxt"></textarea>
<input type="submit" class="sendbtn" name="go" class="send" value="Send"/>
</form>
<script>
$("#sendingform").submit(function(){
var mess = $("#urmess").val();
var mid = "1";
alert (mid);
$.ajax({
type: "POST",
url: 'ajax/send.php',
dataType: "json",
data:{Jdata:JSON.stringify({'mid': mid,'mess': mess})},
success: function (data){
console.log(data);
}
});
return false;
});
</script>
</body>
</html>
I have 2 pages with which I am working with: test1.php and test2.php. test1.php contains 2 <DIV> tags, one named "SubmitDiv" and the other named "DisplayDiv". In SubmitDiv, there is a check box and a submit button. When the check box is checked and the submit button is clicked, I would like it to display test2.php in the DisplayDiv div tag. I have figured that much already.
However, now I want test2.php to receive data from test1.php and process that data. In this case, it is receiving the checkbox's name, "chk" and will be printing that with an echo command. This is where I am a bit stumped as to how to go about this. After searching a bit for an answer, this is what I have written so far:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
function sendQuery() {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function() {
$('#DisplayDiv').load('test2.php');
}
});
return false;
}
</script>
<body>
<form id="SubmitForm" action="" method="post">
<div id="SubmitDiv" style="background-color:black;color:white;">
<input type="checkbox" id="chk" name="chk" form="SubmitForm" value="chk">CHECK</input><br>
<button name="submit" id="submit" type="submit" form="SubmitForm" onclick="return sendQuery();">Submit</button>
</div>
</form>
<div id="DisplayDiv"></div>
</body>
</html>
test2.php:
<html>
<meta charset="utf-8">
<?php
$chk = $_POST['chk'];
echo $chk;
?>
</html>
When the submit button is clicked, however, all it does is refresh the page, rather than display the test2.php in the DisplayDiv like it's supposed to. Any ideas on how to pass the data to test2.php and then also display it within the DisplayDiv section?
Instead of .load function use the following
success: function(response) {
$('#DisplayDiv').html(response);
}
If you want to use e.preventDefault(); you must pass the event to the function
function sendQuery(e) {
e.preventDefault();
//...
}
Otherwise I assume your form is simply submitted on click.
You must first remove e.preventDefault(); in the sendQuery function because that is failing to return false onclick.
Then change your AJAX call to as follows:
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function(data) {
$("#DisplayDiv").html(data);
}
});
This works:
$.ajax({
type: 'GET',
url: 'data.php',
data: {
"id": 123,
"name": "abc",
"email": "abc#gmail.com"
},
success: function (ccc) {
alert(ccc);
$("#result").html(ccc);
}
});
Include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
data.php
echo $id = $_GET['id'];
echo $name = $_GET['name'];
echo $email = $_GET['email'];