Cordova and php - compare two values in different tables - php

I have a webapplication where I push data to a table (User_Info) which includes a random generated token and Sur- and Lastname. Now when I type in the cordova application the token it gets sends to a table named (User_Token). Now I want to check if that token in User_Token matches the generated token in User_Info. If they match I want to show that specific data.
This is my cordova html:
<input type="text" class="valueToken" name="usertoken" >
<button type="submit" class="postToken" id="submit" />PostToken </button>
This is my cordova js:
$('.postToken').click(function(){
console.log($('.valueToken').val());
var tokenValue = $('.valueToken').val();
$.ajax({
type: "POST",
url: "http://example.com/fysioWebapp/php/get_token.php",
data: { dataString: tokenValue },
cache: false,
success: function(){
alert("Order Submitted");
}
});
});
and this is the php on server side:
<?php
include("connect.php");
$stringData = $_POST['dataString'];
echo $stringData;
ini_set('display_errors', 1);
$insertToken = "INSERT INTO User_Token(Oefening_Token) VALUES ('$stringData')";
$tokenresult = mysqli_query($conn, $insertToken);
if($tokenresult){
echo "Successful";
}else {
echo "Error description: " . (mysqli_error($conn));
}
?>
So how can I achieve to check if it matches after that button press and if it matches show data.
This is btw the ajax get call:
$.ajax({
url: "http://example.com/fysioWebapp/php/get_schema.php",
type: "GET",
success: function(data) {
/* ...use the data to fill in some HTML elements... */
$('#myDiv').html(data);
},
error: function() {
/* ...show an error... */
}
});
and this the php to get data from that table:
<?php
include("connect.php");
$sqlGetSchema = "SELECT * FROM `Oefeningen`";
$result = $conn->query($sqlGetSchema);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$token = $row["Token"];
$surname = $row['Surname'];
$lastname = $row['Lastname'];
echo "<div class='". $token . "'><p>Token: " . $token . "</p>";
echo "<p>Surname: " . $surname ." Lastname:" . $lastname. "</p>";
}
} else {
echo("Error description: " . mysqli_error($conn));
}
$conn->close();
?>
So basically what I want to achieve is to compare the input value from cordova app in table User_Token with token in the other table. When it matches it has to show all content of matched token row.

Related

jQuery Ajax sending data to php with one button click but two different actions

What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();
// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });
}
});
});
});
$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();
//I want the button to change its text to Following and when hovering it should say unfollow if user is followed
}
});
});
});
followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "<span>Followed!</span>";
$stmt->close();
} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');
$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "<span>Unfollowed!</span>";
$stmt->close();
} else {
echo "DID NOT WORK";
}
profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php
if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";
} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}
echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "<i class='fa fa-bell'></i>";
// echo "</button>";
echo "<div id='followmessage'></div>";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}
What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},
And for the unfollow button, use submitUnfollow instead.

how to store web push endpoint url in database

Am trying to save the endpoint url,key and token to the database but am getting few errors leaving the code down plz check
main.js
var endpoint = sub.endpoint ;
var key = btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))) ;
var token = btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth')))) ;
var axn = "subscribe" ;
$.ajax({
type: "POST",
url: "push_endpoint_save.php",
dataType : "json",
data:{
"endpoint" : endpoint,
"key" : key,
"token" : token,
"axn" : axn
}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: "application/json; charset=utf-8", // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
console.log(data) ;
}
});
push.php
var_dump($_POST); die;
session_start();
if (isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'];
}
else {
$userid ="";
}
// CONNECT TO THE DATABASE
include_once("php_includes/conn.php");
$_POST = json_decode(file_get_contents('php://input'), true);
$endpoint = $_POST['endpoint'] ;
$key = $_POST['key'] ;
$token = $_POST['token'] ;
$axn = $_POST['axn'] ;
$user_likes = mysqli_query($conn,"INSERT INTO endpointurl (endpoint,p256dh,auth) VALUES ('$endpoint','$key','$token')");
if ($conn->query($user_likes) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $user_likes . "<br>" . $conn->error;
}
and this is the database structure
enter image description here
am unable to receieve the endpoint,key,token in the php file
<?php
var_dump($_POST); die;
session_start();
if (isset($_SESSION['user_id'])) {
$userid = $_SESSION['user_id'];
}
else {
$userid ="";
}
// CONNECT TO THE DATABASE
include_once("php_includes/conn.php");
$_POST = json_decode(file_get_contents('php://input'), true);
$endpoint = $_POST['endpoint'] ;
$key = $_POST['key'] ;
$token = $_POST['token'] ;
$axn = $_POST['axn'] ;
$user_likes = mysqli_query($conn,"INSERT INTO endpointurl (endpoint,p256dh,auth) VALUES ('$endpoint','$key','$token')");
if ($conn->query($user_likes) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $user_likes . "<br>" . $conn->error;
}
?>
TryIt
<script src="https://code.jquery.com/jquery-2.2.4.min.js" ></script>
<input type="submit" name ="this is an example" value= "Try clicking me Now" onclick="justTrying()">
<br>
<br>
<div id="responce"></div>
<script>
function justTrying(){
var endpoint = 'User Your Value' ;
var key = 'Replace it with your value' ;
var token = 'replace this one also' ;
var axn = "subscribe" ;
$.ajax({
type: "POST",
url: "post.php",
dataType : "html",
data:{
"endpoint" : endpoint,
"key" : key,
"token" : token,
"axn" : axn
}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
cache: false, // To unable request pages to be cached
success: function(data){
console.log(data) ;
$("#responce").html(data);
}
});
}
</script>
You are manually multipart/form-data encoding your request, then asking php to Json decode it.

Update Text Value in PHP form display using jQuery & MySQL database

I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>

trying to check live email availability using ajax

function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
the code is working fine.......but if email already exist in database then form should not be submitted...i m new to java script what to do ?
<?php
include('conection.php');
if(!empty($_POST["email"])) {
$result = mysql_query("SELECT * FROM user WHERE email='" . $_POST["email"]
. "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
echo "<span class='status-not-available'> Email Already
Registered</span>";
}else{
echo "<span class='status-available'> Email Available.</span>";
}
}
?>

How to update rows in jQuery with PHP and HTML

My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
jQuery (insert generated HTML/wait for action)
PHP (generate html)
Go back to step 1)
(EDIT: Corrected an error and changed script to answer)
PHP
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});
place all your event-handlers outside the ajax function and use the live() method instead. And you need to include what data to send when using ajax. From visualjquery:
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});
I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to this question dealing with similar problem.
Like peirix and TheVillageIdiot pointed out, the live plugin maybe useful. However, there are some other things you may got wrong in your code:
First, your HTML isn't valid. You have to put quotes around attribut values. You could do this within quotes by escaping inner quotes with a backslash:
echo "<input type=\"text\" class=\"inputfield_visible\" />";
since this looks not that nice, you could leave the PHP part and write pure HTML if you change this:
<?php
...
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
To that (IMHO by far more readable):
<?php
...
?>
</tbody>
</table>
<input type="text" class="inputfield_visible" />
<button class="new">Neu</button>
Secondly, and that seems to be even more important, it looks to me like you have a SQLInjection vulnerability, because you pass the field values directly to mysql without using mysql_real_escape_string first. I'm not that into PHP, so maybe I got that wrong, but what happens if you enter ';-- into you input fields?

Categories