how to store web push endpoint url in database - php

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.

Related

Cordova and php - compare two values in different tables

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.

Retrieving multiple values via PHP/jQuery/Ajax

I'm using the following jQuery to retrieve values for a 'Live Search' field:
$(document).ready(function(){
/* LIVE SEARCH CODE - START HERE*/
var UserID = ('<?php echo $_SESSION['UserID'] ?>');
$(document).ready(function(){
$('.clLiveSearchAccount').on("keyup" , "[id*=txtAccountID]", "input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var ParentTransID = $(this).prev().val();
alert(UserID);
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("Apps/Finance/incGetAccounts.php", {term: inputVal, usr: UserID }).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".clLiveSearchAccount").find('#txtAccountID').val($(this).text());
$(this).parent(".result").empty();
});
});
I'm using this PHP ajax handler:
<?php
/* ------------------------------------------------ */
$link = mysqli_connect("xxx", "xxx", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$term = mysqli_real_escape_string($link, $_REQUEST['term']);
$user = mysqli_real_escape_string($link, $_REQUEST['usr']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM tblAccounts WHERE Name LIKE '%" . $term . "%' AND UserID=" . $user;
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['Name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
But how do I send back (and accept) an additional value, so the String Name and Integer Key?
It seems you are looking to send JSON data. Put the HTML you want to echo in a variable.
$html ="<h1>PHP is Awesome</h1>";
$myVariable = 3;
echo json_encode(array( 'variable1' => $myVariable, 'html' => $html ));
and you'll need a success callback in your javascript
success: function($data) {
var html = $data.html;
var myVar = $data.variable1;
// other stuff
}
look up a tutorial on PHP JSON
W3schools always a good place to start
https://www.w3schools.com/js/js_json_php.asp
I always do this return format in ajax.
Success Response
// PHP
$result = [
'success' => true,
'variable' => $myVariable,
'html' => $html,
];
Fail Response
// PHP
$result = [
'success' => false,
'err_message' => 'Error message here!',
],
use json encode when returning the data to the ajax example json_encode($result) and also dont forget to add dataType setting in your ajax so that it will expect json format response.
Ajax fn
$.ajax({
url: 'path to php file',
type: '' // specify the method request here i.e POST/GET
data: {} // data to be send
dataType: 'JSON',
success: function(res) {
if (res.success) {
...
} else {
// you can put the error message in html by accessing res.err_message
}
}
});

insert in database using php, json and jquery

i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.

POST - 500 (internal server error )

In my case I am sending POST request by $.post using JQuery and PHP.
But I am gettinh this error in while posting data.
POST https://xxxxxxxxxxxxx/xxxxxxxxxxx/php/control/LoginControl.php 500 (Internal Server Error)
here is my jquery code :
var url = 'php/control/LoginControl.php';
$.post(url,
{
task : "login_verify",
username:_username ,
password:_user_password,
})
.error(function(er){
console.log(er);
})
.success(
function(data){
if(data == true){
window.location = 'index.php';
}else{
$("#user_password" ).css({border:'1px solid red'});
}
}
);
PHP - LoginControl.php
<?php
try{
if(isset($_POST) && $_POST['task'] == 'login_verify'){
$user_name = $_POST['username'];
$password = md5($_POST['password']);
require '../class/login.php';
if(class_exists('Login')){
$user = Login::verifyCredentials($user_name,$password);
if($user != NULL){
if(isset($_SESSION)){
session_destroy();
}
session_start();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
echo true;
}else{
echo false;
}
}
}
} catch (Exception $ex){
echo $ex;
}
?>
note: I deploy successfully this code on live test server. and it is completely working fine. But on new server I am getting this error. I am using SSL on this new server this might be issue.
Please comment if its not enough information.
Please help.
Here's an edit to your scripts. Maybe something along the lines of this will help.
JS:
$(function()
{
var url = 'php/control/LoginControl.php';
$.post(url, {
task: "login_verify",
username: _username,
password: _password
}, function(data, status, xhr)
{
// success
if(data.error===false)
window.location = 'index.php';
else
$("#user_password").css({border: '1px solid #ff0000'});
}).error(function(xhr, status, error)
{
console.log("Error loading page. Status: "+status+" | Error: "+error);
});
});
PHP:
<?php
// Session must be started before session checking and destroying can happen
session_start();
// Set error true by default
// Error is always returned.
// If no error, it'll be set to false in if statement
// So a value will always be returned.
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
require_once __DIR__.'/../class.login.php';
if(class_exists('Login'))
{
$uname = $_POST['username'];
$passwd = $_POST['password'];
$user = Login::verifyCredentials($uname, $passwd);
if(!empty($user))
{
if(isset($_SESSION))
session_destroy();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
}
else
$return['error'] = false;
}
}
echo #json_encode($return);
One thing I did notice in your PHP script that I corrected in my edits, is you're using $_SESSION and session_destroy() when no session is open. You must first define session_start() before any of the session methods or magic variables become available to you. That's why I placed it at the very top of the PHP script.
Also, if you want to use another data type rather than json, it's easiest just to use the $.ajax() function
var loginData = {
username: _username,
password: _password,
task: 'login_verify'
};
$.ajax({
url: url,
type: 'post',
data: loginData,
dataType: 'html',
success: function(data, status, xhr)
{
// If page loading was a success. i.e. 200 OK status message
},
error: function(xhr, status, error)
{
// error. Status other than 200
}
});
======================================================================
EDIT: New Code
Take a look at this, see if this will help.
PHP:
<?php
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
if(!empty($_POST['formData']['username']))
{
if(!empty($_POST['formData']['password']))
{
$return['error'] = false;
$message = "The AJAX call was successfull! The data passed is listed below.\n\n"
. "task: " . $_POST['task'] . "\n"
. "username: " . $_POST['formData']['username'] . "\n"
. "password: " . $_POST['formData']['password'];
$return['message'] = $message;
}
else
$return['message'] = 'Password is empty!';
}
else
$return['message'] = 'Username is empty!';
}
else
{
$return['message'] = 'Invalid request! ' . $json->task;
}
echo #json_encode($return);
JavaScript:
$(function()
{
$("#login").click(function()
{
var jdata = {
task: 'login_verify',
formData: {
username: $("#username").val(),
password: $("#password").val()
}
}
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: jdata,
cache: false,
success: function(data, status, xhr)
{
var dataStatus = (data.error===true) ? "Error" : "Success";
var message = "Status: " + dataStatus + "\n"
+ data.message;
alert(message);
},
error: function(xhr, status, error)
{
alert('Error: ' + error);
}
});
return false;
});
});
This code, works. I have a live version of it. Exact code and all.
AJAX/PHP Example
I hope this helps

Passing json to php and getting response

I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");

Categories