I'm a computer science student, in my sophomore year. For independent learning I decided to create a website in technologies like: SQL, PHP, JS, AJAX, BOOTSTRAP. I'm trying to add content to the database, I use AJAX - I do not want to refresh the page, so I use AJAX. I manage to add the content to a database - but the page refreshes.
I tried to use jquery - when I add content - to prevent refresh. The code works - but there is still a refresh.
The code that accesses the database:
<?php
$DBConInfo = [
'server' => '127.0.0.1',
'username' => 'root',
'password' => '',
'name' => 'test',
];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($DBConInfo['server'],$DBConInfo['username'], $DBConInfo['password'],$DBConInfo['name']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// php code to Insert data into mysql database from input text
if(isset($_POST['insert']))
{
$hostname = "127.0.0.1";
$username = "root";
$password = "";
$databaseName = "test";
// get values form input text and number
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$picture = $_POST['picture'];
// mysql query to insert data
$query = "INSERT INTO `product`(`name`,`description`, `price`, `picture`) VALUES ('$name','$description','$price','$picture')";
$result = mysqli_query($conn,$query);
// check if mysql query successful
if($result) {
echo 'Data Inserted';
}
else{
echo 'Data Not Inserted';
var_dump($conn->error);
}
//mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP INSERT DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id="form-insert" action="" method="post">
<!--<input type="text" name="id" required placeholder="id"><br><br>-->
<input type="text" name="name" required placeholder="Name"><br><br>
<input type="text" name="description" required placeholder="description" min="10" max="100"><br><br>
<input type="text" name="price" required placeholder="price"><br><br>
<input type="text" name="picture" required placeholder="picture" min="10" max="100"><br><br>
<input id="submit-insert" type="submit" name="insert" value="Add Data To Database">
</form>
<span id="result"></span>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src ="js/DBscript.js" type="text/javascript"></script>
</body>
</html>
Using ajax - to prevent refresh:
$("#submit-insert").click( function() {
$.post( $("#form-insert").attr("action"),
$("#form-insert :input").serializeArray(),
function(info){ $("#result").html(info);
});
//clearInput();
});
$("#form-insert").submit( function() {
return false;
});
function clearInput() {
$("#form-insert :input").each( function() {
$(this).val('');
});
}
After submitting the form you have to use event.preventDefault()
$("#submit-insert").click( function(event) {
event.preventDefault();
});
$('#form-insert').on('submit', function (event) {
event.preventDefault();
$.ajax({
type : 'post',
url : 'NameOfPHPFile.php',
data : $('#form-insert').serialize(),
success : function () {
alert('form was submitted');
}
});
});
Related
I take no credit for the JS or AJAX code and I don't understand it. (Thank you Alon Alexander)
I have no AJAX knowledge and I would rather use PHP/JS with no JQuery, but I don't understand how to make it work.
I have a form that uses OnUpdate to fire a JS code that then uses AJAX to perform a SQLi query that should return the search data.
Problem is the return is alway the same even if I use data I KNOW should be returned true (file already exists), but Always returns 'New Entry' in my "Notice" Paragraph
Further, if record found I will then use JS to update form fields with record data. But that is for the next step in this. First need this to work.
i.e. "Record Exists" and form populates with that record info
or "New Entry" and forms stays blank.
index.php //reduced to needed info only
<?php include("process.php"); ?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/phone.js"></script>
<script type="text/javascript" src="js/entrynum.js"></script>
</head>
<body>
<?php
if (isset($_POST['reg-submit'])) {
echo "<p id='notice' style='padding: .5em; border: 2px solid red;'>Entry $entrynum Saved!<br>$timenow on $datenow</p>";
} else {
echo "<p id='notice' style='display: none; padding: .5em; border: 2px solid red;'></p>";
}
?>
<main>
<div class="Container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend><h1>Registration</h1></legend>
<label for="entrynum">Entry Number</label>
<input type="number" pattern="\d*" name="entrynum" id="entrynum" value="" required="true" placeholder="" autofocus onchange="entry_check()" />
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<input type="submit" name="reg-submit" id="reg-submit" value="Submit" />
</fieldset> <!-- Registration Form-->
</form>
</div>
</main>
</body>
</html>
entrynum.js
function entry_check() {
var entrynum = $("#entrynum").val();
// Send the AJAX call
$.post(
'entrysearch.php', // TO search.php page
{entrynum: entrynum}, // the DATA sent with the request
function(data) { // a CALLBACK function
if (data == 'none') { // no rows were found or an error occurred
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
return;
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}
);
}
entrysearch.php
<?php
include("includes/connect.php");
if (!isset($_POST['entrynum'])) {
echo 'none';
die();
}
$sql = $db->prepare("SELECT * FROM HeatWaveData WHERE entrynum=%d", $_POST['entrynum']);
$results = $db->query($sql);
$result = $results[0];
if (!$result) {
echo 'none';
die();
}
echo json_encode($result);
?>
I suggest you to use $.ajax function instead of post.
You can try by adding an id to the form by adding id="myform", then change entrynum.js as it follows:
// Change onSubmit behaviour for the form
$("#myform").on("submit", function(e) {
// Prevent page reload
e.preventDefault();
$.ajax({
// Get form action or uses current page.
url : $(this).attr('action') || window.location.pathname,
type: "POST",
// Get all input to submit and serialize on array (this will become $_POST)
data: $(this).serialize(),
success: function (data) {
//Here you have server response
},
error: function (jXHR, textStatus, errorThrown) {
// If error thrown jXHR contains XMLHttpRequest stuff like status
console.log(jXHR);
// You will see on an alert the real error thrown
alert(errorThrown);
}
});
});
FINALLY! It seems the sql needed a var ($entry) instead of using $_POST['entrynum']... Not sure why.
Then if no records found the ajax would not return anything (not even NULL). So I had to add some if statements and return '0' if no records found.
Further, it helped to add datatype "json' so object was parsed.
Javascript:
function entry_check() {
var entrynum = $("#entrynum").val();
$.post(
'entrysearch.php',
{entrynum: entrynum},
function(data) {
if (!data) {
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}, "json"
);
}
entrysearch.php
<?php
if (isset($_POST['entrynum'])) {
$entry = $_POST['entrynum'];
include("connect.php");
$sql = ("SELECT * FROM HeatWaveData WHERE entrynum = $entry");
if ($results=mysqli_query($db,$sql)) {
if ($rowcount=mysqli_num_rows($results)) {
$result = $results->fetch_object();
echo json_encode($result);
} else {
echo $rowcount;
}
}
}
?>
It works! Took me all night of research reading examples and docs.
it is my code.
html
<html>
<head></head>
</body>
<form id="myform" action="formdata.php" method="post">
username:<input type="text" name="username" id="name"><br>
password:<input type="password" name="password" id="pass"><br>
firstname:<input type="text" name="firstname" id="fname"><br>
lastname:<input type="text" name="lastname" id="lname"><br>
<input type="submit" id="submit" value="register">
</form>
<div id="status_text"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#submit").click(function(){
var username = $('#name').val();
var password = $('#pass').val();
var firstname = $('#fname').val();
var lastnamee = $('#lname').val();
var postData = '&username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname;
var status_text = $('#status_text');
//alert(postData);
//var mydata = {'username':name,'password':pass,'firstname':fname,'lastname':lname};
/*$.post($('#myform').attr('action'),
$('#myform:input').serializeArray(),
function(info){
$('status_text').html(info)
});*/
$.ajax({
url:"action",
type:"post",
success:function(info)
{
status_text.html(info);
}
});
});
</script>
</body>
</html>
and it is my php code for database
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
$name = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO karthik.person(name,password,firstname,lastname)VALUES('$name','$password','$firstname','$lastname')";
if($conn->query($sql) === TRUE){
echo("record added success");
}else{
echo("failed".$conn->error);
}
$conn->close();
?>
when ever i run this code it goes to next page and display the result like "record added successfully" instead of that i want the code to display the result in the same page. i almost tried all ways but i can't get my expected result.
You have some problems here:
You are not preventing the default submit event and that causes the form to submit "normally" as well.
You are not sending any data with your ajax request so you will never have any $_POST variables on the server-side.
You have an sql injection problem. You should use a prepared statement and bind the values.
You are not sending your ajax request to the correct url.
You are using a plain-text password. You should always salt and hash passwords.
You need to tell the browser not to submit the form:
$("#submit").click(function(e) {
e.preventDefault(); // Prevents the default behaviour for the submit-action
//... the rest of your code
When you get this working, you should start fixing stuff from #jeroen's list.
I have a php script and I would like it to be called with ajax, I have had an error coming from the ajax which says "Error:email=my_email&password=myPassword".
Here is the PHP script
<?php
session_start(); //starts a session in order to be-able to save session variables and to read them
require "db_config.php"; //Allows us to use the database connection from db_config.php in this file
if ($_SERVER["request_method"] == "post"){ //checks if the form was submitted
$email = $_POST["email"]; //fetching the email address which was inserted in the login.html form
$password = $_POST["password"]; //fetching the password which was inserted in the login.html form
/*
querying the database, to check whether there is a result with the email and password entered by the user
*/
$checkForUser = mysqli_query($db_connection, "SELECT * FROM `tbl_users` WHERE email = '$email' and Password = '$password' LIMIT 1");
/*
checking if the query resulted in one row, if there is a row
it means there is a user with this email and password, which means these are the correct creadentials
*/
$rows = mysqli_num_rows($db_connection, $checkForUser);
if ($rows == 1){
//this means: correct credentials
//the next few lines fetch the information from the result
while($row = mysqli_fetch_assoc($checkForUser)){
$_SESSION["user_id"] = $row["userId"]; //creates a session variable containing the users id
$_SESSION["users_name"] = $row["firstName"]. " ".$row["lastName"]; //creates a session variable containing the users name
}
echo "You are now logged in: ". $_SESSION["users_name"];
}else{
//this means: incorrect credentials
echo "Incorrect Username or password"; //prints out error message
}
}
?>
Here is main.js
$(document).ready(function() {
$('#loginForm').submit(function() {
var data = $(this).serialize();
$.ajax({
url: "../php/login.php",
type: "POST",
data: data,
success: function(data) {
$('*').html(data);
},
error: function() {
alert('ERROR: ' + data);
}
});
return false;
});
});
Here is the login.html page which may be helpful
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" type="text/css" href="css/responsive.css">
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
<meta name="copyright" content="Yudi Moszkowski">
<title>Login | Your Site Name</title>
</head>
<body>
<div id="loginContainer">
<div class="logo"><img src="img/yourLogo.png"></div>
<form action="php/login.php" method="post" id="loginForm">
<input type="text" name="email" placeholder="Email" id="loginEmail" class="loginInput" required="true">
<input type="password" name="password" placeholder="Password" id="loginPassword" class="loginInput" required="true"/>
<input type="submit" value="Login" name="loginSubmit" id="loginSubmit">
</form>
<div id="loginOptions"><p id="noAccount">Not signed up? Signup</p><p id="forgotPass">Forgot password?</p></div>
</div>
</body>
</html>
Thanks for your time :)
it seem that you type wrong url :
in html action, u use "php/login.php" and in ajax call, u use same url with "../" before it. if you explain the location of login.php and this html file, it will be helpful to solve your problem.
I need to get data from mysql database without refreshing the page using jquery ajax. I have a php script which is working fine. However, my JS seems to be having some problem. Here is the jquery script.
index.php
<!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" class="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="item"></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 ),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( 'test.php', { s: $(".s").val() } ).done(function( data ) {
alert( "hiiiiiiiiii" + $(".s").val() );
});
// Put the results in a div
});
$.getJSON(
'fetch_data.php',
's='+$('.s').val(),
function(result){
$('#item').empty();
$.each(result.result, function(){
$('#item').append('<p>'+this['s']+'</p>');
});
});
</script>
</body>
</html>
This code is not working. pleas give me solution how it work?
fetch_data.php
<?php
if(!mysql_connect("localhost","root",""))
{
echo "db connection error : ".mysql_error();
exit;
}
else
{
if(!mysql_select_db("test"))
{
header('Content-type: application/json');
echo "db selection error : ".mysql_error();
exit;
}
}
$sql = "select s from test ";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($res)){
echo $row[0];
array_push($result,
array('s'=>$row[0]));
}
echo json_encode(array('result'=>$result));
?>
I want to do is make a login system without refreshing the page using a button, ajax but i dont know how to do it.
My problem is my code wont work if i click the button. How do i use ajax to communicate with my myIncludes.php if i press the button login?
index.php
<html lang="en">
<head>
<script type="text/javascript">
$('#login').click(function(){
<?php include_once('myIncludes.php'); ?>
});
</script>
</head>
<body>
<form method="post">
Username: <input type="text" name="user" /><br />
Password: <input type="text" name="pass" /><br />
<button type="button" name="login" id="login">Login</Button>
</form>
</body>
</html>
myIncludes.php
<?php
session_start();
include_once('connection.php');
include_once('user.php');
if(isset($_POST['submit'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$object = new User();
$object->Login($user, $pass);
}
?>
user.php
<?php
include_once('connection.php');
class User{
private $db;
public function __construct(){
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function Login($user, $pass){
if(!empty($user) && !empty($pass)){
$st = $this->db->prepare("SELECT * from users WHERE username=? AND password=?");
$st->bindParam(1, $user);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "User verifies, Access granted";
} else {
echo "Incorrect Username or Password";
}
}else{
echo "Please enter Username and Password";
}
}
}
?>
connection.php
<?php
class Connection{
public function dbConnect(){
return new PDO('mysql:host=localhost; dbname=test', 'root', '');
}
}
?>
I am currently building a system like this, but to know how to do this you must understand AJAX. First of you need an HTML page with a filled header, but an empty body you only need some empty divs in the body.
<?php
//start up some objects and sessions if required
//I like to set up some data and add this data to a session.
//so its available to the entire application. In an object oriented way.
?>
<html>
<head>
//fill in some header data like imports etc.
<script src="your javascript file" type="text/javascript"></script>
<script src ="jquery"/></script>//I dont use it myself but it can be useful
</head>
<body>
<div id="content"></div>
<div id ="hidden" style="visibility:hidden></div> //for hidden js feedback.
<script type="text/javascript">
loadLogin();
</script>
</body>
</html>
Then your javascript (without jquery)
URL = "urltoyourbackendphp";
//type is type of function to be called by php.
//div is div to be changed.
//vars is array with post variables.
function ajaxcall(type, div, vars){
var xml = new XMLHttpRequest(); //doesnt work on IE 7 or lower
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;
}
};
xml.open("POST",URL,true); //URL to php
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var nvar = "type="+type;
var i = 1;
foreach(vars as vara){
nvar = nvar+"&var"+i+"="+vara;
}
xml.send(nvar);
}
function login(){
var name = document.getElementById("name");
var pass = document.getElementById("pass");
name = name.value;
pass = pass.value;
ajax(login, hidden, array(name, pass));
}
function loadLogin(){
ajax("loadpage", "content", array("login"));
}
function loadHome(){
ajax("loadpage", "content" array("home");
}
function alertLogin(){
alert("Username or Pass were wrong");
}
and your php backend
<?php
$type = $_POST["type"];
if($type == "loadpage"){
$pagename = $_POST["var1"];
if($pagename == "login"){
fread("loginpage.php"); //echoes the contents of a file
}elseif($pagename == "home"){
fread("Home.php");
}
elseif($type == "login"){
$name = $_POST["var1"];
$pass = $_POST["var2"];
//do checks on these. Make sure to prevent sql-injections too.
if(checks){
echo "<style onload='loadHome()'></style>";
}else{
echo "<style onload='alertLogin()'></style>";
//This is one of the few ways to make php do another javascript call.
//Via echo and I think it might as well be the most efficient.
}
}?>
Now there might be a few syntax errors since this is mostly out of my head without a compiler to check this for me, but its the system I use and it works really fine plus it can be really dynamic. But if you want a bigger application you must keep in mind all sorts of things like preventing sql-injection and sessions etc.
The most important thing to know is that I did base most of this on the w3schools tutorials about ajax.
ndex.php
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: "POST", // data send format POST/GET
url: "./myIncludes.php", // file url for data processing
data: $("#frm_data").serialize(), // all form field are serialize
dataType: "json", // response type xml, json, script, text, htm
success: function(data) {
if(data.result == true){
window.location = "dashboardpage.php";
}else {
alert("invalid user/password");
}
}
});
});
});
</script>
</head>
<body>
<form method="post" name="form" id="frm_data" >
Username: <input type="text" name="user" /><br />
Password: <input type="text" name="pass" /><br />
<button type="button" name="login" id="login">Login</Button>
</form>
</body>
</html>
myIncludes.php
<?php
session_start();
include_once('connection.php');
include_once('user.php');
if(isset($_POST['submit'])){
$result = false;
$user = $_POST['user'];
$pass = $_POST['pass'];
$object = new User();
if($object->Login($user, $pass)){
$result = true;
}else{
$result = false;
}
echo json_encode(array('result' => $result));
die();
}
?>
user.php
<?php
include_once('connection.php');
class User{
private $db;
public function __construct(){
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function Login($user, $pass){
if(!empty($user) && !empty($pass)){
$st = $this->db->prepare("SELECT * from users WHERE username=? AND password=?");
$st->bindParam(1, $user);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
return true;
} else {
return false;
}
}else{
return false;
}
}
}
?>
Include jQuery library to login page.
Follow the below script to do ajax login action:
$(document).ready(function() {
$("#login").click(function() {
var postData = $("form").serialize();
jQuery.ajax({
'url': 'myIncludes.php',
'data': postData ,
'type': "POST",
'success': function(data){
if (data == true) {
// Logged in successfull
alert("user loggedin successfully");
window.location = "dashboardpage.php";
} else {
alert("invalid user/password");
}
}
});
});
});