Accessing Through PHP a Posted Javascript Variable - javascript

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.

After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

Related

Variable from posted form stops or continues with php code after pop up box (javascript)

I have an issue with php and javascript included.
Sedning form from data index.php to edit.php
this is my edit.php file:
<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>
<?php
session_start();
// connect to database
include("connection.php");
// update records
if (isset($_POST['update'])) {
$chk=$_POST['chk'];
$manyids=implode(",",$chk);
//$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$user = $_POST['user'];
// if time is NULL ask if you are sure
if ($time == "") {
echo "<script type='text/JavaScript'>
ConfirmNull();
</script>";
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
else {
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
}
?>
Right now if the value time variable is NULL it should run javascript with the question: are you sure?
If YES continue with SQL and update the db.
If Cancell stop the php code and run windows.history.back and do NOT run SQL.
Unfortunately its updating the db when i hit Cancel.
PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.
So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:
document.querySelector('#myForm').addEventListener('submit', evt => {
if (evt.target.querySelector('[name="time"]').value === '') {
if (!confirm('Are you sure?')) evt.preventDefault();
}
});
And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.

AJAX function for retrieving postgres data not working

I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}

How can i show a webpage only for logged in users? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.
<?php
require ('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You did not complete all of the required fields')
window.location.href='index.html'
</SCRIPT>");
exit();
}
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='homepage.html'
</SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='index.html'
</SCRIPT>");
exit();
}
}
else{
}
?>
this is my control for the correct user and pass.
And here is the page i want to go if the user has logged in.
homepage.index:
<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
here some text and other stuff.
<h3>logout here<h3>
</body>
But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?
Thank you.
Your question is part of many many available tutorials, did you try to google it first?
do not use mysql extension (using mysqli in example)
do not redirect via javascript, if you can do it via php
do not redirect to html files, when you need to work with php
do not store password as plain text (using php5.5+ function to crypt it in example)
do not select *
do not echo html code
use isset before getting value from $_POST, $_GET
Feel free to google everything to know the reasons.
<?php
class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{
static function getConnection(){
if(self::$connection === null)
self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
return self::$connection;
}
/** #var mysqli */
private static $connection;
}
<?php
class UserAuthenticator
{
function __construct(){
session_start(); //you need to start session when working with $_SESSION
}
function checkLogin(){
if(isset($_POST['submit'])){
$username = $this->getPostEscaped('uname');
$password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query
if($username && $password){
$userData = Connection::getConnection()->query("SELECT password FROM login_users
WHERE username = '$username'")->fetch_assoc();
if($this->verifyPassword($password, $userData['password'])){
$this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
$this->flash('Login succesfull.');
$this->redirect('homepage.php');
}else $this->flash('Wrong username / password combination. Please re-enter.');
}else $this->flash('You did not complete all of the required fields.');
$this->redirect('index.php');
}
}
function isLogged(){ //actual answer to the question - how to check the logged user
return isset($_SESSION['logged']);
}
function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
return password_verify($password, $passwordHash);
}
function getPasswordHash($password){ //public so you can use it elsewhere
return password_hash($password, PASSWORD_DEFAULT);
}
function showFlashMessages(){
if($flashMessages = $this->getFlashes()): ?>
<script language="JavaScript">
<?php foreach($flashMessages as $message): ?>
alert('<?= $message ?>');
<?php endforeach ?>
</script> <?php
endif;
unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
}
function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
$url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header('Location: ' . $url .'/'. $to, true, 302);
header('Connection: close');
exit;
}
private function login($userId){ //actual answer to the question - how to store the logged user
$_SESSION['logged'] = $userId;
}
private function flash($message){ //do not repeat yourself
if(!isset($_SESSION['flashmessage']))
$_SESSION['flashmessage'] = array();
$_SESSION['flashmessage'][] = $message;
}
private function getFlashes(){
return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
}
private function getPost($name, $default = null){ //do not repeat yourself
return isset($_POST[$name])? $_POST[$name]: $default;
}
private function getPostEscaped($name, $default = null){ //do not repeat yourself
return ($value = $this->getPost($name))?
Connection::getConnection()->real_escape_string($value): $default;
}
}
$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();
you need to store passwords with
$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database
in homepage.php you can check logged status with
$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in
not tested anything of this, so typo is possible - sorry :)
Lets say your login was succesfull. All you have to do is this:
Session_start();
$_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)
Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()
Hope this steers you in the right direction if not ill update my answer

Php, js redirecting after successful registering, It inserts the user but won't redirect

<?php
$con = mysqli_connect("localhost", "root", "", "" ) or die("Neuspjelo spajanje");
function InsertUser(){ global $con;
if(isset($_POST['sign_up'])){
$name = mysqli_real_escape_string($con, $_POST['u_name']);
$pass = mysqli_real_escape_string($con,$_POST['u_pass']);
$email = mysqli_real_escape_string($con,$_POST['u_email']);
$country = mysqli_real_escape_string($con,$_POST['u_country']);
$gender = mysqli_real_escape_string($con,$_POST['u_gender']);
$b_day = mysqli_real_escape_string($con,$_POST['u_birthday']);
$date = date("m-d-Y");
$status = "unverified";
$posts = "No";
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con, $get_email);
$check = mysqli_num_rows($run_email);
$insert = "insert into users (user_name, user_pass, user_email, user_country, user_gender, user_b_day,
user_image, register_date, last_login, status, posts) values
('$name','$pass', '$email', '$country', '$gender', '$b_day', 'default.jpg',
'$date', '$date', '$status', '$posts')";
$run_insert = mysqli_query($con, $insert);
$result = mysql_query($insert);
if($result){
echo "<script>alert ('You're successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
}
}
?>
You can't echo javascript and run it in a page that's already loaded. This would need to be the result of an ajax call on the client side with your redirects occuring from your ajax callbacks.
If you're ok with ditching the alert, you can just issue a redirect from php:
header('Location: home.php');
To do it ajaxy:
$.ajax({
type: "GET",
url: "your_insert_user.php"
}).success(function(xhr) {
alert ("You're successfully registered!");
window.open('home.php', '_self');
}).fail(function (jqXHR, status, errorThrown) {
//something else here
});
But, why would you want to issue an ajax call just to redirect?
Additionally, you need to issue the appropriate responses from your insert script:
if ($result) { echo ""; } //issues a "200 OK"
else { header("HTTP/1.1 422 Unprocessable Entity"); } //fires the failure callback in ajax
I would pass a conditional GET or POST paramater to home.php with some value flag and display your message there.
Based on what you post above, you are dealing with two separate issues here.
You say "it inserts" so I'm assuming that means that the mysql query to insert the new row into your database completes successfully. Then you send some HTML code, containing a (somewhat mangled) Javascript snippet, to the browser, which is supposed to issue a redirect request to the client's web browser, which doesn't have the desired result, seeing as you write that it "won't redirect".
Keep in mind that redirection is performed by the browser, is dependent on the browser's capabilities and/or settings, and requires proper javascript in the first place.
How do properly request a redirect from the browser has been discussed before on SO.
First of all,remove this line $result = mysql_query($insert); then modify your code and add this, hope it will work:
$run_insert = mysqli_query($con, $insert);
if($run_insert){
echo "<script>alert ('You\'re successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}

AJAX to call PHP file which removes a row from database?

Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});

Categories

Resources