I have a Question. Instead of having the record insert rather once, It inserts twice into the DB table. I am using a Javascript function to send the Data to a PHP , Now it saves the data to a Database, No doubt , but rather than have one Record, It saves twice. And i do not have a reason as to why this is so.
My javascript used to save data looks like this :
function submitFormData(){
var xhr = new XMLHttpRequest();
var url = 'submit_request.php';
var fullname = document.getElementById("fullname").value;
var address = document.getElementById("address").value;
var address2 = document.getElementById("address2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var telephone = document.getElementById("telephone").value;
var email = document.getElementById("email").value;
var vehicle_type = document.getElementById("vehicle_type").value;
var vehicleNo = document.getElementById("vehicleNo").value;
var visit_date = document.getElementById("visit_date").value;
var visit_purpose = document.getElementById("visit_purpose").value;
var whom_tosee = document.getElementById("whom_tosee").value;
var login_time = document.getElementById("login_time").value;
var params = 'fullname='+fullname+'&address='+address+'&address2='+address2+'&city='+city+'&state='+state+'&telephone='+telephone+'&email='+email+'&vehicle_type='+vehicle_type+'&vehicleNo='+vehicleNo+'&visit_date='+visit_date+'&visit_date='+visit_date+'&visit_purpose='+visit_purpose+'&whom_tosee='+whom_tosee+'&login_time='+login_time+'';
var txt = 'Please confirm the following Information\n FullName : '+fullname+'\n Address : '+address+'\n Address2 : '+address2+'\n City: '+city+'\n State: '+state+'\n Telephone: '+telephone+'\n Email: '+email+'\n Vehicle Type: '+vehicle_type+'\n Vehicle #: '+vehicleNo+'\n Visit Date: '+visit_date+'\n Visit Purpose : '+visit_purpose+'\n Who To see : '+whom_tosee+'\n Login Time : '+login_time+'';
var response = confirm(txt);
if(response == true){
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
// alert('Sending Data');
var finalurl = url +'?'+params;
window.location = finalurl;
}
}
xhr.send(params);
}else{
window.location ='e-vmsreserve.php';
}
}
And the PHP used to save the Data into the DB looks like this
<?php
session_start();
if(!isset($_SESSION['userID']))
{
header("location: index.php");
}
?>
<?php
require_once('inc/config.php');
$con = mysqli_connect($host,$user,$pass,$db) or die ('Cannot connect: '.mysqli_error());
$query = "SELECT * FROM evmsdbusers WHERE username = '".$_SESSION['userID']."'";
$result = mysqli_query($con,$query) or die('Bad Query: '.mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$fullname = $row['fullname'];
$username = $row['username'];
$designation = $row['designation'];
}
?>
<?php
require_once('inc/config.php');
$con = mysqli_connect($host, $user, $pass, $db) or die('Cannot connect, Reason:'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_GET['fullname']);
$address = mysqli_real_escape_string($con,$_GET['address']);
$address2 = mysqli_real_escape_string($con,$_GET['address2']);
$city = mysqli_real_escape_string($con,$_GET['city']);
$state = mysqli_real_escape_string($con,$_GET['state']);
$telephone = mysqli_real_escape_string($con,$_GET['telephone']);
$email = mysqli_real_escape_string($con,$_GET['email']);
$vehicle_type = mysqli_real_escape_string($con,$_GET['vehicle_type']);
$vehicleNo = mysqli_real_escape_string($con,$_GET['vehicleNo']);
$visit_date = mysqli_real_escape_string($con,$_GET['visit_date']);
$visit_purpose = mysqli_real_escape_string($con,$_GET['visit_purpose']);
$whom_tosee = mysqli_real_escape_string($con,$_GET['whom_tosee']);
$login_time = mysqli_real_escape_string($con,$_GET['login_time']);
$invitee_username =$username;
$sql = "insert into new_reservation (fullname,address,address2,city,state,telephone,email,vehicle_type,vehicleNo,visit_date,visit_purpose,whom_tosee,login_time,visitor_username) values ('".$fullname."','".$address."','".$address2."','".$city."','".$state."','".$telephone."','".$email."','".$vehicle_type."','".$vehicleNo."','".$visit_date."','".$visit_purpose."','".$whom_tosee."','".$login_time."','".$invitee_username."')";
mysqli_query($con, $sql) or die ('Bad Query, Reason: '.mysqli_error($con));
$message = "Appointment Reserved!";
echo '<script type="text/javascript">';
echo 'alert("'.$message.'");';
echo '</script>';
?>
Now what i do not seem to understand is why I am having 2 records,Though not duplicate but it should have only one record.
First of all, your code is wide open for SQL injection, using $_GET is open invitation for SQL injection. I suggest you to use Prepared statement, this will prevent your code for SQL attack.
Issue in your code is window.location = finalurl; this line, this will redirect to same php file with same params, and your query will insert twice due to $_GET values.
So, you just need to show your response when you got response 200, no need to redirect on same url 'submit_request.php' with same params.
Some useful links:
Are PDO prepared statements sufficient to prevent SQL injection?
Prepared Statement Manaul
One more suggestion always exit(); after header(); otherwise your code will not terminate.
php - Should I call exit() after calling Location: header?
Thank You DevPro, Somehow I managed to see where the error was. when performing a get request, it should be in the pattern url+'?'+parameters
I remembered that and tried it in my code, somehow it saves fine now and no Duplicate records or double insert. In case someone needs it in future :), PHP Remains the same.
I did it like this xhr.open('GET', url+"?"+params, true);
function submitFormData(){
var xhr = new XMLHttpRequest();
var url = 'submit_request.php';
var fullname = document.getElementById("fullname").value;
var address = document.getElementById("address").value;
var address2 = document.getElementById("address2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var telephone = document.getElementById("telephone").value;
var email = document.getElementById("email").value;
var vehicle_type = document.getElementById("vehicle_type").value;
var vehicleNo = document.getElementById("vehicleNo").value;
var visit_date = document.getElementById("visit_date").value;
var visit_purpose = document.getElementById("visit_purpose").value;
var whom_tosee = document.getElementById("whom_tosee").value;
var login_time = document.getElementById("login_time").value;
var params = 'fullname='+fullname+'&address='+address+'&address2='+address2+'&city='+city+'&state='+state+'&telephone='+telephone+'&email='+email+'&vehicle_type='+vehicle_type+'&vehicleNo='+vehicleNo+'&visit_date='+visit_date+'&visit_date='+visit_date+'&visit_purpose='+visit_purpose+'&whom_tosee='+whom_tosee+'&login_time='+login_time+'';
var txt = 'Please confirm the following Information\n FullName : '+fullname+'\n Address : '+address+'\n Address2 : '+address2+'\n City: '+city+'\n State: '+state+'\n Telephone: '+telephone+'\n Email: '+email+'\n Vehicle Type: '+vehicle_type+'\n Vehicle #: '+vehicleNo+'\n Visit Date: '+visit_date+'\n Visit Purpose : '+visit_purpose+'\n Who To see : '+whom_tosee+'\n Login Time : '+login_time+'';
var response = confirm(txt);
if(response ==true){
xhr.open('GET', url+"?"+params, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
alert('ok');
}
}
xhr.send(null);
}
}
Thanks everyone!
Related
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
I have a js function that calls in an xml request to fetch data from a separate php file. I can get a returned data through echoing it from the separate php file.
Here's my current code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
//On Data Receive
countryHeader.innerHTML = this.responseText;
}
};
xhttp.open("GET", "country.php?c=" + countryName, true);
xhttp.send();
And on my php:
include("conn.php");
$c = htmlentities($_GET["c"]);
$sec_country = mysqli_real_escape_string($con, $c);
//Searches the db
$sql = "SELECT * FROM countries WHERE country_code = '$sec_country' LIMIT 1";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1)
{
//Get Data
$row = mysqli_fetch_assoc($result);
$countryName = $row['country_name'];
$countryPrice = $row['country_price'];
echo $countryName." is worth $".$countryPrice;
}
else
{
//Invalid Code/No Data
echo "No Country Found";
}
If I send in a country code for example like rus, it would return Russia is worth $1B mainly from the echo $countryName." is worth $".$countryPrice;
But what if I want to separately send $countryName and $countryPrice?
For example responseText.a and responseText.b
You can send JSON response from PHP. Here is a reference -> https://www.w3schools.com/js/js_json_php.asp
I need to insert a value got from a document.getElementById into a sql query.
I need to do this because i'm trying to autofill a second input box depending on the result of the first (i.e. if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
Here is the code:
<?php
echo (" <form NAME='Form1' id='Form1' method=post class=statsform action=page.php > " );
echo (" <input type=text name=city id=city size=50 class=formfield value='$city' onBlur='Assigncode();' > " );
echo (" <input type=text name='Country' id='Country' size=12 value='$Country' > " );
?>
<script>
function Assigncode() {
var elemento = document.getElementById("city");
var elementoCod = document.getElementById("Country");
if (elemento != null && elemento.value != '') {
var city = elemento.value;
if (elementoCod == null || elementoCod.value == '') {
<?php
$query2 = "SELECT * FROM table WHERE city = 'put here the getElementById of the city' ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
$country = mysql_result($result2,0,"T_Country");
?>
eval( "document.Form1. Country").value = '<?php echo($country)?>';
}
}
}
</script>
Any suggestion?
Thanks
Here is a slightly modified version of an AJAX example script found on Wikipedia. It should give you the basic idea on how to proceed. If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
send-ajax-data.php:
<?php
$city = $_GET['city'];
$query2 = "SELECT * FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country = mysql_result($result2,0,"T_Country");
echo $country;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query.
I need to set PHP session variable or change is to "" or get it via javascript . for some reason the variables are not set and not get . Can the javascript there are any restrictions on this? Here is the sample code:
JS (get variable):
function getSessionVariable(variable){
if(typeof variable=="string"){
var xhttpSession = new XMLHttpRequest();
xhttpSession.open('POST','session.php',false);
xhttpSession.onreadystatechange= function(){
if(xhttpSession.readyState==4 && xhttpSession.status==200){
return xhttpSession.responseText;
}
}
xhttpSession.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhttpSession.send("sessionValue="+variable+"&command=get");
}
JavaScript code above gets a normal result, which shows by the debugger, but for some reason the variables which are assigned for example function getSessionVariable('userName') is undefined (despite the fact that the debugger shows such as "return = 'Bob' ")
session.php
if(isset($_REQUEST['command']) && $_REQUEST['command']=='get' &&
isset($_REQUEST['sessionValue'])){
$value = $_REQUEST['sessionValue'];
$res = $_SESSION[$value];
echo ($res);
}
Same thing when changing values:
function logInCheck(){
var userName = getSessionVariable('userName');
if(document.getElementById('name').value!= userName && userName!=undefined){
if(getCookie('logined')=="true"){
var xhttpSession = new XMLHttpRequest();
xhttpSession.open('POST','session.php',true);
xhttpSession.onreadystatechange = function(){
if(xhttpSession.readyState==4 && xhttpSession.status==200){
xhttpSession.abort();
}
}
xhttpSession.send("command=end")}
}
session.php
if(isset($_REQUEST['command']) && $_REQUEST['command']=="end" && isset($_REQUEST['userName'])){
$userName = $_REQUEST['userName'];
$result = mysql_query('SELECT user_id FROM users WHERE userName="{$userName}"');
$row = mysql_fetch_array($result);
$user_id =$row['user_id'];
mysql_query("DELETE FROM userlist WHERE user_id= '{$user_id}'");
$_SESSION['userName']="";
$_COOKIE['logined']="";
}
Thanks in advance for any help.
For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.