I recently notice that I have a duplicate line on the table, when the device is spinning or calling someone on this davay at the time of pressing the 'save' button. On the lines of UserRealTime I see that the interval is a duplicate of 5-6 milliseconds.
How to avoid duplicates using javascript or jQuery. For example, check the connection of the device to the Internet?
ajax.php
<?php
if (isset($_GET['d1']) && isset($_GET['d2']))
{
$conn=connSQL();
$query = "insert into doorname(d1, d2, UserRealTime) values ('".$_GET['d1']."','".$_GET['d2']."', getdate())";
$rs=$conn->execute($query);
$rs->Close();
$conn->Close();
}
?>
JavaScript
<script>
var httpObject = null;
function getHTTPObject()
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
return null;
}
}
function Inter()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
var d1=document.getElementById('d1').value;
var d2=document.getElementById('d2').value;
if (d1=="" || d2=="")
{
alert("sorry!!!");
}
else
{
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2, true);
httpObject.send(null);
httpObject.onreadystatechange = InterSet;
}
}
}
function InterSet()
{
if(httpObject.readyState == 4)
{
var data=httpObject.responseText;
alert("Good!!!");
}
}
</script>
This way of approach it is not a suggested practice. However, just to work around the problem here is one way of handling general duplicate DB entries.
Generate one random Token on the client side for every successful server side insert. Discard the Token on client side once the server confirms the successful insert. Following is an example:
1) Generate a random Token on the client side, like so
Generate random string/characters in JavaScript
var tokenOnClientSide = makeid();
2) Attach the generated Token to Ajax Params:
httpObject.open("GET", "ajax.php?d1="+d1+"&d2="+d2+"&token="+token, true);
3) Server side: Look if the Token already exists
<?php
if (isset($_GET['d1']) && isset($_GET['d2']) && isset($_GET['token']))
{
$query = sprintf("SELECT * FROM token_table WHERE token = '%s'", $_GET['token']);
$rs=$conn->execute($query);
if (mysql_num_rows($res) == 0) {
// carry on with insert and return success message
.....
// now store the token permanently
$query = "insert into token_table(token, time_of_exec) values ('".$_GET['token']."', getdate())";
$rs=$conn->execute($query);
}
4) Finally, unset the global token on client side
tokenOnClientSide = "";
Hope that one gets a basic idea of handling duplicates.
Related
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
<?php
session_start();
define("HOST","localhost");
define("USER","root");
define("PASS","");
define("DB","project_inv");
define("DOMAIN","http://localhost/
inv_project/public_html/dont");
?>
Database:
<?php
class Database
{
private $con;
public function connect(){
include_once("constants.php");
$this->con = new Mysqli(HOST,USER,PASS,DB);
if ($this->con) {
return $this->con;
}
return "DATABASE_CONNECTION_FAIL";
}
}
//$db = new Database();
//$db->connect();
?>
JavaScript Validation Part: It comes here and keeps on loading when am trying to take from ip, e.g. http://xx.xx.xx.xx/inv_project/public_html/dont/
//For Login Part
$("#form_login").on("submit",function(){
var email = $("#log_email");
var pass = $("#log_password");
var status = false;
if (email.val() == "") {
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>Please Enter Email Address</span>");
status = false;
}else{
email.removeClass("border-danger");
$("#e_error").html("");
status = true;
}
if (pass.val() == "") {
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Password</span>");
status = false;
}else{
pass.removeClass("border-danger");
$("#p_error").html("");
status = true;
}
if (status) {
$(".overlay").show();
$.ajax({
url : DOMAIN+"/includes/process.php",
method : "POST",
data : $("#form_login").serialize(),
success : function(data){
if (data == "NOT_REGISTERD") {
$(".overlay").hide();
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>It seems like you are not registered</span>");
}else if(data == "PASSWORD_NOT_MATCHED"){
$(".overlay").hide();
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Correct Password</span>");
status = false;
}else{
$(".overlay").hide();
console.log(data);
window.location.href = DOMAIN+"/dashboard.php";
}
}
})
}
})
While am trying to run from other computer it displays the design and content of the page but it is not validating but when am trying locally it works fine.
Don't define DOMAIN as "localhost". This will cause errors, while calling the page from other computers.
Localhost means always the computer the script is running on. Using this in a JavaScript the reference to the server is lost and it tries to connect/forward to the client-computer - with no success. This works on the first computer, because this might be the server.
I have a Server Send Event working and updating a webpage. I then assign the contents of the div receiving the SSE to a var so as to send it to a php file to insert into a database. The div's data is constantly changing in sseReceiving.php page, but how to send it and it's changing values to the database dynamically. Now it is only sending the div content to the database when the page is re-submitted. How to do it continually?
sseTriggering.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
//echo "data: New random number:". $new_data. "\n\n";
echo "data:".$new_data."\n\n";;
flush();
sseReceiving.php
<body>
<div id="serverData">Here is where the server sent data will appear</div>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
var MyDiv = document.getElementById("serverData").innerHTML;
window.location.href = "findpair.php?pair=" + MyDiv;
};
}
</script>
</body>
findpair.php
$pair = $_GET['pair'];
$qX = "UPDATE product SET prod_name = '$pair' WHERE id = 1";
$rrr = mysqli_query ($dbc, $qX) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
I have researched this issue at the links below and some have helped me get it to the stage it is at now.
http://www.coderslexicon.com/the-basics-of-passing-values-from-javascript-to-php-and-back/
send javaScript variable to php variable
Get content of a DIV using JavaScript
Detect element content changes with jQuery
I have also put header('Refresh: 5'); in the php part of the various files and no change.
You should be able to send the request via AJAX for your main function which will allow the sse events to come to your client and then go to your findpair.php function.
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("sseTriggering.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
//Send AJAX request.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do something with 'xmlhttp.responseText' if you want.
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
} else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "findpair.php?pair=" + event.data, true);
xmlhttp.send();
};
}
More info here on submitting AJAX requests with javascript.
So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
I'm trying to get some code to work for a uni assignment, I am still learning but feel like I'm going a little crazy trying to understand why a class variable is not working.
Using a PHP class such that
class Users {
//Variables
protected $_userName;
protected $_password;
protected $_login;
protected $_firstName;
protected $_lastName;
protected $_email;
protected $_phone;
protected $_addressStreet;
protected $_addressCity;
protected $_addressState;
protected $_company;
public function __construct() {
// gets the number of parameters
$numArgs = func_num_args();
$arg_list = func_get_args();
// make decisions based on the arguments number
switch($numArgs){
case "2":return $this->ConstructorWithTwoArgs($arg_list[0], $arg_list[1]);
case "10":return $this->ConstructorWithTenArgs($arg_list[0], $arg_list[1],$arg_list[2], $arg_list[3],$arg_list[4], $arg_list[5],$arg_list[6], $arg_list[7],$arg_list[8], $arg_list[9]);
default:
//Handle exception for method not existing with that many parrams
break;
}
}
//In order to log in we require minimum of user name and password
protected function ConstructorWithTwoArgs($userName, $password){
$this->_userName = $userName;
$this->_password = $password;
$this->_login = "false";
return $this;
}
//Checks users details and updates user details if valid
public function DoLogin(){
$result = false;
// Check if userName and password exist in the db
$query = "SELECT * FROM SIT203Users WHERE USER_NAME = :userName AND PASSWORD = :password";
// Create a new connection query
$ds = new Connection();
$ds->parse($query);
$ds->setBindValue(':userName', $this->_userName);
$ds->setBindValue(':password', $this->_password);
$ds->execute();
//User exists if rows are returned there will only be one as userName is unique
if($ds->getNextRow()){
$result = true;
$this->_login = "true";
$this->_firstName = $ds->getRowValue("FIRST_NAME");
$this->_lastName = $ds->getRowValue("LAST_NAME");
$this->_email = $ds->getRowValue("EMAIL");
$this->_phone = $ds->getRowValue("PHONE");
$this->_addressStreet = $ds->getRowValue("ADDRESS_STREET");
//Ensure all street details are obtained
if($ds->getRowValue("ADDRESS_STREET2"))
$this->_addressStreet .= $ds->getRowValue("ADDRESS_STREET2");
$this->_addressCity = $ds->getRowValue("ADDRESS_CITY");
$this->_addressState = $ds->getRowValue("ADDRESS_STATE");
$this->_company = $ds->getRowValue("COMPANY");
}
$ds->freeResources();
$ds->close();
return $result;
}
}
Now this class works fine for a direct call to it from;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/MyAccount.php?userName=JaieP&password=jp
<?php
require_once('initialise.php');
// Need to Validate all feilds and remove unwanted text
// The feilds to be tested are the $_REQUEST values
$userName = Validation::validateString(isset($_REQUEST['userName'])?$_REQUEST['userName']:"");
$password = Validation::validateString(isset($_REQUEST['password'])?$_REQUEST['password']:"");
$remberMe = isset($_REQUEST['remberMe'])?$_REQUEST['remberMe']:"";
// Create a new user
$newUser = new Users($userName, $password);
// Try and login
$newUser->DoLogin();
if($newUser->getLogin() == "true")
{
$_SESSION['user'] = $newUser;
// Echo out the users details plus cart details for last 3 months
//test its working to here
//echo($newUser->toString());
echo("Its working!!!");
}
else
{
//echo("falseValue");
echo($userName.$password.$remberMe.$newUser->getLogin().$newUser->getUserName().$newUser->DoLogin().$newUser->toString());
}
?>
But when I try to use it via a javascript call using the below code the _login variable fails to update and for the life of me I can't work out why?
as can be seen from this link;
http://www.deakin.edu.au/~jtparker/SIT203/xyz/flower_shop2/myaccount.html
it fails every time?
Any ideas
Many thanks in advance
Jaie
function TryLogin(){
try{
// Get the userName and password supplied
var userName = document.getElementById( "userName" );
var password = document.getElementById( "password" );
// Get the remember me value
var rememberMe = document.getElementById( "rememberMe" );
// Get the error feild
var errorDisplay = document.getElementById( "submitError" );
// set to no error
errorDisplay.innerHTML = "";
var documentMyAccount = document.getElementById( "myAccount" );
// Submit details to server for verification if not empty
if(userName.value != "" && password.value != ""){
// Now check via DB if username and password are valid
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// IF Response indicates a successful login
var myResponse = xmlhttp.responseText;
if(myResponse != "falseValue"){
// set to nothing
documentMyAccount.innerHTML = "";
// add php content
documentMyAccount.innerHTML = myResponse;
}
else{
// Do not advise what details are incorrect, just that some combination is incorrect
errorDisplay.innerHTML = "Sorry those details are not correct";
}
}
}
var submitString = "MyAccount.php?";
submitString +="userName="+userName.value;
submitString +="&password="+password.value;
submitString +="&rememberMe="+rememberMe.checked?"true":"false";
xmlhttp.open("GET",submitString,true);
xmlhttp.send();
}
else{
errorDisplay.innerHTML = "Not all details have been entered!";
}
}
catch(error){
alert(error.message);
}
}
You simply have to debug what's the final URL that is being called by your AJAX and confirm if everything is being sent as you expect and that will solve it.
Try
console.log(submitString)
before your AJAX call and you'll know if everything is being sent correctly.