I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:
HTML:
<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>
Javascript code:
function chkId()
{
$("#chkresult").html("Please wait...");
$.get("check_id.php", function(data) { $("#chkresult").html(data); });
}
The check_id.php file:
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
echo "Available!";
}
else if ($total > 0)
{
echo "Not Available!";
}
?>
But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.
I do not see the $id variable in your PHP script that is used by your $id_query.
Try adding that above $id_query
A few things I notice:
Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.
Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.
Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.
EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!
$.ajax({
type: "POST",
url: "check_id.php",
data: {
id:id; //the id requested by the user.You should set this
},
dataType: "json",
success: function(data){
$('#chkresult').html(data);
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
In your php
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Not available');
}
?>
Related
I want to prevent direct access to a certain PHP file called prevented.php
My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?
Here's my code:
index.php
<?php
$_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
$.ajax({
type: "POST",
url: "def.php",
data: {
token: '<?php echo $_SESSION["token"]; ?>'
},
cache: false,
success: function(data) {
console.log (data);
if (data) {
console.log (data + ' valid');
} else {
console.log (data + ' invalid');
}
location.href = "prevented.php";
},
error: function () {
console.log('error');
}
});
</script>
def.php
<?php
session_start();
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
echo false;
die('invalid in def');
} else {
define('_DEFVAR', 1);
echo true;
die ('valid in def');
}
?>
prevented.php
<?php
include "def.php";
if (defined('_DEFVAR')) {
die ('valid in prevented'); // instead of this I would show the content of the page
} else {
die ('invalid in prevented');
}
?>
Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.
index.php:
<?php
session_start();
$_SESSION['flag'] = true;
?>
click here for the protected page
protected.php:
<?php
session_start();
if ($_SESSION['flag'] ?? false) {
echo "you have previously visited index.php";
} else {
echo "you have not previously visited index.php";
}
?>
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.
My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.
I am trying to add some data to a relational database, and would like the session_user_id to be the foreign key for that database. When a user clicks a button, I want to make a database entry with the session_user_id and some other information I have POSTed to the page. My ajax posts to the php webpage page which it is run on (meaning all my scripts are on the same page)
I am currently getting a Uncaught ReferenceError: $sess_user_id1 is not defined. The jquery is firing. While I would love to get the undefined variable fixed, overall this does not seem like a very direct way to to this, and has added a bunch of confusing variables, when all the variables I need were already in my PHP statement. Is there any way to trigger the PHP entry without going through ajax and having to define the variables again?
Here is my php, which is at the header which is on the same page as my JS and HTML:
<?php
$markerid = $_POST["id"];
$name = $_POST["name"];
$type = $_POST["type"];
$point = $_POST["point"];
$lat2 = $_POST["lat"];
$lng2 = $_POST["lng"];
$locationdescription = $_POST["locationdescription"];
$locationsdirections = $_POST["locationdirections"];
session_start();
if (!isset($_SESSION['sess_user_id']) || empty($_SESSION['sess_user_id'])) {
// redirect to your login page
exit();
}
$sess_user_id1 = $_SESSION['sess_user_id'];
if ((isset($_POST['usid'])) && (isset($_POST['usid']))) {
$user_id_follow = strip_tags($_POST['usid']);
echo $user_id_follow;
$query = "INSERT INTO markerfollowing ( userID, markerID, type )
VALUES ('$user_id_follow', '$markerid', '$type');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close();
}
?>
Here is the HTML button:
<div class="btn pull-right">
<button class="btn btn-large btn-followmarker" type="submit"id="followmarker">Add me to the list</button>
</div>
Here is the jquery/ajax post:
<script/javascript>
$(document).ready(function () {
$("#followmarker").click(function(){
$.ajax({
type: "POST",
url: "", //
data: { usid: <?php echo '$sess_user_id1'; ?>},
success: function(msg){
alert("success");
$("#thanks").html(msg);
},
error: function(){
alert("failure");
}
});
});
});
</script
A sincere thanks for any and all help. I haven't worked with relational databases before.
<?php echo '$sess_user_id1'; ?>
is wrong. If you wont to get
data: { usid: 123} at $sess_user_id1 is 123, you should write
data: { usid: <?php echo "$sess_user_id1"; ?>}
See your html source code in your brawser. I think there is data: { usid: $sess_user_id1}, and javascript is not understand what is the $sess_user_id1
This is the only one problem that I can see now, but I don't understand your current task whole to say more.
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}