Having trouble using AJAX to POST to a database - javascript

I'm currently building a mobile app using Cordova and I'm having trouble getting a basic test login function working with my code. I have no clue why this isn't working, and I'm unfamiliar with the convoluted way I have to use php so I'm not even sure how to get proper error reporting from that part of the code. If anyone could help me out, I'd be really grateful.
Code below (I've blanked out some details with asterisks.
HTML
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<form id="Loginform">
<p><label>username:</label>
<input type="text" id="unl" /></p>
<p>
<label>Password:</label>
<input type="text" id="pwl" /></p><p>
</p>
<p><input type="submit" id="login" value="Login" onClick="logIn();" />
</p></form>
<form id="Registerform">
<p><label>username:</label>
<input type="text" id="unr" /></p>
<p>
<label>Password:</label>
<input type="text" id="pwr" /></p><p>
<label>Re-type Password
:</label>
<input type="text" id="pw2r" />
</p>
<p>
<input type="submit" id="register" value="Register" onClick="regisTer();" /></p>
</form>
<input type="button" id="check" value="check" onClick ="checkUn();">
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/localstorage.js"></script>
<script type="text/javascript" src="js/logreg.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="js/plugins/LaunchMyApp.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
logreg.js
function logIn() {
alert("1");
}
function regisTer() {
var un = $("#unr").val();
var pw = $("#pwr").val();
var pw2 = $("#pw2r").val();
if (pw!='' && pw2!='' && un!='') {
if (pw == pw2) {
alert("run post");
$.post("http://cs12ars.icsnewmedia.net/Media/register.php",
{
name:un, pass:pw
}, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
} else {
alert("both passwords must match");
}
} else {
alert("Please fill in all fields.");
}
}
register.php (on the server, same server as the database)
<?php
//clean input
function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "&#35", $string);
$string = str_replace("%", "&#37", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
//encrypt data
function salt ($string) {
$salt1 = 'gds54d';
$salt2 = '54h6';
$salted = md5 ("$salt1$string$salt2");
return $salted;
}
?>
<?php
$db_hostname = 'localhost';
$db_database = '****';
$db_username = '****';
$db_password = '****';
$db_status = 'not initialised';
$str_result = '';
$str_options = '';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
//connect to the database
mysqli_select_db($db_server, $db_database);
$name = $_POST['name'];
$pw = $_POST['pass'];
$password = salt($pw);
$query = "INSERT INTO `bla` (`bla`, `test`) VALUES (NULL, '$name');";
mysqli_query($db_server, $query);
mysqli_close($db_server);
?>

I have absolutely no idea why, but changing from using $.post to $.ajax and setting asnyc to false made it start working.
$.ajax({
type: "POST",
url: "http://cs12ars.icsnewmedia.net/Media/register.php",
data: {name:un, pass:pw},
async: false
});

Related

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

invisible recaptcha v2 not checking required input fields

I am adding an invisible recaptcha; for some reason, it doesn't check for required fields anymore. Previously, I would get a notification from Chrome stating that the fields can't be empty. Now, it's just ignoring this and letting me submit empty forms.
I am submitting requests using ajax. My guess is that the data-callback is not meant to be used to send ajax requests.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Submit a quote</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/forms.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../js/quotes/ajax.js"></script>
<meta name="description" content="Submit your awesome quote today!">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0aff0a">
<meta name="msapplication-navbutton-color" content="#0aff0a">
<meta name="apple-mobile-web-app-status-bar-style" content="#0aff0a">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<button name="submit" type="submit" id="contact-submit" class="g-recaptcha" data-callback="onSubmit" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI">Submit</button>
</fieldset>
</form>
</div>
<script>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
</script>
</body>
</html>
It seems the submit action is cancelled as well.
$("#form").submit(function (e) {
var url = $("#form").attr('action');
ajaxSendData(url, $("#form").serialize());
e.preventDefault();
});
The above snippet only triggers when not using the recaptcha API.
How would I properly send an ajax request to a PHP page?
My full code (if needed):
<?php
include_once "connect.php";
session_start();
if(isset($_POST["quote"], $_POST["author"], $_POST["g-recaptcha-response"])){
if(!isValid()){
http_response_code(400);
exit();
}
$stmt = $conn->prepare("INSERT INTO pending (quote, author) VALUES (?, ?)");
$stmt->bind_param("ss", $quote, $author);
$quote = htmlspecialchars($_POST["quote"]);
$author = htmlspecialchars($_POST["author"]);
$stmt->execute();
echo"Added to pending! Thank you for submitting";
$stmt->close();
$conn->close();
//$_SESSION["lastRequest"] = time();
}else{
http_response_code(400);
exit();
}
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if($decoded = json_decode($result, true)){
return $decoded['success'];
}
}
catch (Exception $e) {
return null;
}
}
Try to put the recaptcha in separate div
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<button name="submit" type="submit" id="contact-submit" data-callback="onSubmit">Submit</button>
</fieldset>
</form>
</div>

validating answer submitted to database

<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate">
<div id="display"><script type="text/javascript">document.write(count);</script></div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
</script>
</html>
So basically this is the code I've done so far, I'd like to do a validation to check the count after the user clicks on submit, and check the count with the database answer. Is there anyone out there who can help me out?
in the form use the method in tag form onsubmit ="validation". after you need to implement the validation method in javascript and make a ajax request (in validation) to another php form, in that php form u make the query to db and returning the number of click you need to do. o you need to implement jquery library.
function validation(){
$.ajax({
url: "your_php_requesting_to_db.php",
success: function(data){
if(data == numberofclicks){
return true;
}else{
return false;
}
}
});
}
Here is the new code, im new in this foro so i don't know how to put in a comment the code, im assumng you got the total clicks you need to do, answering your question of timmer here is a little bit of doc
http://www.w3schools.com/js/js_timing.asp
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate" onsubmit="validate()">
<div id="display">
<script type="text/javascript">document.write(count);</script>
</div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="hidden" id="totalClicks" value="<?php /*IF U GOT THE NUMBER OF CLIC FROM BD PUT IN THERE LIKE ECHO $NUMCLICKS */ ?>"/>
<input type="hidden" id="countClic" value="0" />
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
document.getElementById('countClic').value=count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
function validate(){
var totalClics = document.getElementById('totalClicks').value=count;
var clicksCount = document.getElementById('countClic').value=count;
if(totalClics == clicksCount){
return true;
}else{
return false;
}
}
</script>
</html>

Basic POST with JQuery Mobile from form using php

Firstly I apologize for posting another one of these questions, but I've dove through a ton of SO questions related to this topic and haven't be able to figure out my problem. I'm new to PHP and an amature at best using Jquery mobile and the like.
I'm attempting to post to a .php file and get a response back. Eventually this will evolve into a database posting yada yada. For now, I can't seem to get my response back from my post. I'm running Xampp to host the php, Jquery Mobile is being used in other functions so it does work properly,
HTML:
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Javascript:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
alert(status); //Won't fire
alert(html); //Won't fire
var response = html;
alert(response); //Won't fire
if (response == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
PHP
<?php
// VARS
$Username=$_GET["Username"]; //Also tried _POST
$Password=$_GET["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
My best guess is that something is wrong with the .php because all of the questions I've looked at seem to confirm my JavaScript is right. All of my alerts fire except the ones in the call back function. The username and password are also correctly being set so that isn't the problem. I tried using _POST and _GET in my .php, I originally was using _POST because I was posting data but I was following this question: (Phonegap contact form not working over PHP) and it did the opposite so I changed it. No difference. My .php is actually hosted for sure (I can navigate to it without an error). I also tried using the $.ajax function but had the same issues.
Thanks in advance.
EDIT: Added more of the HTML (all that should be relevant) per request, can't add it all as it is too long.
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Stylesheets -->
<link rel="stylesheet" href="css/snctfy2/snctfy2.css" />
<link rel="stylesheet" href="css/snctfy2/jquery.mobile.icons.min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href="jquerymobile/jquery.mobile.structure-1.4.2.min.css" rel="stylesheet" type="text/css" /> <!-- Add .structure after theme-->
<!-- Jquery core -->
<script src="js/jquery.js" type="text/javascript"></script>
<!-- Jquery mobile library file -->
<script src="jquerymobile/jquery.mobile-1.4.2.min.js" type="text/javascript"></script>
<!-- DateBox -->
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.css" />
<script type="text/javascript" src="js/datebox/jqm-datebox.core.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.calbox.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.datebox.js"></script>
<script type="text/javascript" src="js/datebox/jquery.mobile.datebox.i18n.en_US.utf8.js"></script>
<!-- Scripts (pre-load)-->
<script src="js/scripts.js" type="text/javascript"></script>
<!-- CSS Override -->
<link rel="stylesheet" type="text/css" href="css/override.css" />
<title>SNCTFY</title>
</head>
<body>
<!--there is some more <div> tags here unrelated-->
<!--------------------------------------------------------Login Page---------------------
-------------------------------------------->
<div data-role="page" id="login" data-theme="a" class="bPage">
<div data-role="content">
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Register
<button onclick="showAlert()">Test</button>
<p id="testlog">Results</p>
</div>
</div>
<!-- more <div> pages -->
<!-- Scripts (post-load)-->
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
EDIT2: Changed JavaScript to one of the answers to test
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data: { "Username": username, "Password": password },
success: function (data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
};
Just try jquery Ajax
<body>
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username =$('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data:{"Username":username,"Password":password},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
in PHP
<?php
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
Try this:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
//These are the names of the form values
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: dbURL,
type:'post',
data:'&username='+username+'&pass='+password,
success:function(response){
alert(response);
}
});
};
<?php
// VARS
$Username=$_POST["username"]; //Also tried _POST
$Password=$_POST["pass"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
try this code
script
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
if (data == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
</script>
PHP
// VARS
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}

AJAX Load and PHP Error

I have created a simple form which submits data to the database.
I want to use Ajax so that when submit is pressed, a loading bar shows and then takes you to the success! page after a few seconds. How do i go about this?
Also the following code gives me the following error, what do i need to fix - SOLVED:
Notice: Undefined index: command in F:\xamppnew\htdocs\web\billing.php on line 5
Code:
<?php
include "storescripts/connect_to_mysql.php";
session_start();
if ($_REQUEST['command']=='update'){
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$address=$_REQUEST['address'];
$phone=$_REQUEST['phone'];
$item_id = $_SESSION['item_id'];
$quantityorder = $each_item['quantity'] = $_SESSION['quantity1'];
$cartTotal = $_SESSION['cartTotal'];
// Add this product into the database now
$sql = mysqli_query($link,"insert into transactions values('','$item_id','$quantityorder','$cartTotal','$name','$address','$email','$phone')");
die('Thank You! your order has been placed!');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
<title>Billing Info</title>
<script language="javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript">
function validate(){
var f=document.form1;
if(f.name.value=='' || f.email.value=='' || f.address.value=='' || f.phone.value=='' ){
alert('You have not filled in all fields');
f.name.focus();
return false;
}
f.command.value='update';
f.submit();
}
</script>
</head>
<body>
<div align="center" id="mainWrapper">
<?php include_once("template_header.php");?>
<div id="pageContent">
<div style="margin:24px; text-align:left;">
<br />
<form name="form1" onsubmit="return validate()">
<input type="hidden" name="command" />
<div align="center">
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Product ID:</td><td><?php echo $item_id = $_SESSION['item_id'];?></td></tr>
<tr><td>Total Quantity:</td><td><?php echo $each_item['quantity'] = $_SESSION['quantity1']; ?></td></tr>
<tr><td>Order Total:</td><td>£<?php echo $cartTotal = $_SESSION['cartTotal'];?></td></tr>
<tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" onkeypress='return isNumberKey(event)' /></td></tr>
<tr><td> </td><td><input type="submit" value="Place Order" /></td></tr>
</table>
</div>
</div>
<?php include_once("template_footer.php");?>
</form>
</body>
</html>
<!--================================== code for "stack_ajax.php" start here ==================================-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/external_css.css">
<script type="text/javascript" src="jquery_src/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function validate(){
var f=document.form1;
if(f.name.value=='' || f.email.value=='' || f.address.value=='' || f.phone.value=='' ){
alert('You have not filled in all fields');
f.name.focus();
return false;
}
f.command.value='update';
postData = $("#form1").serializeArray( );
$.ajax({
type : "POST",
data : postData,
dataType : "html",
url : "ajax_response.php",
async : true,
beforeSend : function( ) {
$("#ajax_image_div").show();
},
success : function(data, textStatus, xhr) {
ajax_response_status = parseInt(data, 10);
if(ajax_response_status)
window.location.href='success_message.php';
else
window.location.href='failed_message.php';
},
error : function(xhr, textStatus, errorThrown) {
alert(textStatus);
},
complete : function(jqXHR, textStatus) {
$("#ajax_image_div").hide();
}
});
return true;
}
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
</head>
<title>Billing Info</title>
<body>
<div id='ajax_image_div' style="display:none;">
<img id="ajax_loader_image" style="vertical-align:middle" src='image/ajax_loader.gif'>
</div>
<div align="center" id="mainWrapper">
<div id="pageContent">
<div style="margin:24px; text-align:left;">
<br/>
<div align="center">
<form id="form1" name="form1" method="POST" action="" autocomplete="off" enctype="multipart/form-data">
<input type="hidden" name="command" />
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Your Name:</td><td><input type="text" name="name" id="user_name" /></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" onkeypress='return isNumberKey(event)' /></td></tr>
<tr><td> </td><td><input type="button" name="submit" value="Place Order" onClick="return validate()"/></td></tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<!--================================== code for "stack_ajax.php" end here ==================================-->
<!--============================== code for "ajax_response.php" start here ==============================-->
<?php
/*
Note : I made changes in your HTML form ( You can add session variable by yourself ) and delete following lines
1. <?php include_once("template_header.php");?>
2. <?php include_once("template_footer.php");?>
*/
sleep(3); /* Wait for 3 seconds before executing below code, by doing so
you will be able to see "AJAX LOADER" on the page.
*/
/* print_r($_POST); // You will get all the FORM input data in this array. */
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$address = $_REQUEST['address'];
$phone = $_REQUEST['phone'];
$item_id = $_SESSION['item_id'];
$quantityorder = $each_item['quantity'] = $_SESSION['quantity1'];
$cartTotal = $_SESSION['cartTotal'];
// Add this product into the database now
$sql = mysqli_query(
$link,
"insert
into
transactions
values
('','$item_id','$quantityorder','$cartTotal','$name','$address','$email','$phone')"
);
if( $sql )
echo 1; /* When SQL query will execute successfully. */
else
echo 0; /* When SQL query will not execute successfully. */
exit;
?>
<!--============================== code for "ajax_response.php" end here ==============================-->
/* ================================== code for "external_css.css" start here ==================================*/
#ajax_image_div {
top:30%;
left:30%;
width:50%;
height:50%;
position:absolute;
z-index:999;
}
#mainWrapper {
width:100%;
height:100%;
position:absolute;
}
#ajax_loader_image {
position:relative;
top:35%;
left:35%;
}
/* ================================== code for "external_css.css" end here ==================================*/
<!-- ============================= code for "success_message.php" start here ============================= -->
<?php
echo 'Thank You! your order has been placed!';
?>
<!-- ============================= code for "success_message.php" end here ============================= -->
<!-- ============================= code for "failed_message.php" start here ============================= -->
<?php
echo 'An error occurred, please try after some time ';
?>
<!-- ============================= code for "failed_message.php" end here ============================= -->
<!--
Note : make sure your directory structure must be same as below
php_ajax ( create a folder with "php_ajax" and put all the code inside it )
1. css [ create a folder with "css" name ]
A. external_css.css
2. image [create a folder with "image" name]
A. ajax_loader.gif [ You may download it using internet :-) ]
3. jquery_src [ [create a folder with "jquery_src" name]]
A. jquery-1.11.0.min.js [ jQuery framework, you may download it using internet ]
4. ajax_response.php
5. failed_message.php
6. stack_ajax.php
7. success_message.php
Let me know if you have any problem after implementing this. I put all the codes in separate files to
make DEBUG task very easy.
-->

Categories

Resources