validating answer submitted to database - javascript

<?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>

Related

JS/HTML/PHP in one PHP program and MYSQL Updates via Server Sent Events

I'm building a two-way chat application that stores messages into a MySQL database. I would like to use Server Sent Events and have the PHP and HTML all in one page but the problem I'm facing is that the header cannot be set to text/event-stream or I will break the HTML.
My question is how can I have the PHP, JS and HTML on the same page when using Server Sent Events?
Here is my opening JS. I set the EventSource to index.php even though this might be wrong.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index.php");
source.onmessage = function(event) {
document.getElementsByClassName("message").innerHTML = event.data;
};
}else {
document.getElementsByClassName("message").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream");
}
else {
header("Content-Type: text/html");
}
//Database Stuff
$connect = mysqli_connect('localhost', 'user', 'Pass');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
?>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<?php echo "data: ".$row['mymessages']; flush();?>
</div>
</div>
<?php
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
?>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<?php echo "data: ".$row['yourmessages']; flush();?>
</div>
</div>
<?php
}
}
?>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
EDIT: I have tried separating the PHP the HTML and put the PHP logical part outside the HTML. I'm able to get Server Sent Events via inspector in Chrome but not sure how to loop through the DB entries in JS. I'm not comfortable with JS syntax.
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
if(isset($_POST['submit'])){
$send = $_POST['mymessage'];
$sendmsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('".$send."', '')";
}
if (!empty($_GET['yourmessage'])){
$recieve = $_GET['yourmessage'];
$recievemsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('', '".$recieve."')";
}
$connect = mysqli_connect('localhost', 'root', 'Walcott34');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$sqlrecieve = mysqli_query($connect, $recievemsg);
$sqlsend = mysqli_query($connect, $sendmsg);
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
echo "data: ".$row['mymessages']."\n\n";
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
echo "data: ".$row['yourmessages']."\n\n";
}
ob_flush();
flush();
}
}
else {
?>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index2.php");
source.onmessage = function(e){
document.getElementById("mymessages").innerHTML = event.data;
document.getElementById("yourmessages").innerHTML = event.data;
};
}else {
document.getElementsById('message').innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<div id='mymessage'>
</div>
</div>
</div>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<div id='yourmessage'>
</div>
</div>
</div>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
<?php } ?>
If your after it being in one file you just need the one outer if statement which separates the two logical parts.
<?php
if ($_SERVER["HTTP_ACCEPT"] === 'text/event-stream') {
// event stream code
...
while (true) {
...
} else {
// client side code
?>
<head>
<meta name="viewport" content="w
...
<?php }
You cant intertwine the two parts like your doing:
<div class='message'>
<?php echo "data: $row['mymessages']"; flush();?>
</div>
Your serverside part is incomplete but that's beyond the scope of the question,ive commented with a link to a working example.

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;
?>

using ajax call to empty the div

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

php - Session Not Carrying Over but Variables Are

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.
While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!
index.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
}
else{
}}
else{
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded" style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
<div class="form-group">
<label for="user">Username</label>
<input type="text" class="form-control" id="email" name="user">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pass">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";
//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);
//Check Connection
if($conn->error){
die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
//echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";
$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;
//Execute
$result = $conn->query($sql);
if($conn->error){
echo "Load Error";
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if($inputpass == $row["password"]){
echo '<div class="alert alert-success fade in">
x
Your credentials are correct
</div>';
echo '<script type="text/javascript">
window.location.href = "pihome.php";
</script>';
$_SESSION["Auth"] = "yes";
$_SESSION["User"] = $inputuser;
}else{
echo '<div class="container-fluid"><div class="alert alert-danger fade in">
x
Your username or password is incorrect!
</div></div>';
$_SESSION["Auth"] =false;
//echo "Success";
}
} else {
//echo "Failed";
}
}
else{
//echo "Not Set";
}
?>
</body>
</html>
pihome.php
<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
}
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] != "yes"){
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
echo "You are logged in as: ".$_SESSION["User"];
}else{
echo "Auth Passed";
$_SESSION["Auth"] = "yes";
}
}else{
echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';
}
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>
<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>
<script>
function AJAX_JSON_Req( url )
{
var AJAX_req = new XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function()
{
if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
{
var response = JSON.parse( AJAX_req.responseText );
//document.write( response.controls[0].type );
document.getElementById("status").innerHTML = response.controls[0].type + " " + response.controls[0].state;
}
}
AJAX_req.send();
}
AJAX_JSON_Req( 'status.json' );
</script>
Logout
</div>
</body>
<html>
logout.php
<?php
$sessionstate = session_status();
if($sessionstate == 1){
session_start();
echo "Started";
session_unset();
}
else if($sessionstate == 2){
session_destroy();
echo "destroyed";
}
/*echo '<script type="text/javascript">
window.location.href = "index.php";
</script>';*/
?>
I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

Having trouble using AJAX to POST to a database

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

Categories

Resources