Sending Jquery value to PHP page - php

I'm really struggling to get this working so any help would be much appreciated!
Basically I have a JQGRid that displays bookings with double click event as follows:
ondblClickRow: function(rowid)
{
rowData = $("#bookings").getRowData(rowid);
var brData = rowData['bookref'];
getGridRow(brData);
},
This gets passed to getGridRow function:
function getGridRow(brData) {
$.ajax({
url: 'bookings-dialog.php',
data: {'rowdata' : brData },
dataType: 'json', //this is what we expect our returned data as
error: function(){
alert("It failed");
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error inserting the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(data){
//empty our dialog so we don't end up with duplicate content
$('.cp-booking-info').empty();
//we have told the browser to expect JSON back, no need to do any parsing
//the date
$('.cp-booking-info').append('<p class="pno-margin">Booking Date: '+data.bookref+'</p>');
//now let's manipulate our dialog and open it.
$("#cp-bookings-dialog").dialog({
show: { effect: 'drop', direction: "up" },
hide: 'slide',
height: 625,
width: 733,
title: 'Booking Reference: - '+ brData
});
}
});
And this is the bookings-dialog.php:
<?php
require_once('deployment.php');
require_once('bootstrp/all.inc.php');
require_once('models/sql.php');
require_once('models/bookingdocket.php');
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$rowdata = $_POST['rowdata'];
$query = ("SELECT * FROM tblbookings WHERE bookref = '$rowdata'");
$stmt = $dbh->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_BOTH);
BookingDocket::set_id($row['id']);
BookingDocket::set_bookref($row['bookref']);
BookingDocket::set_bookdate($row['bookingdate']);
BookingDocket::set_returndate($row['returndate']);
BookingDocket::set_journeytype($row['journeytype']);
BookingDocket::set_passtel($row['passengertel']);
BookingDocket::set_returndate($row['returndate']);
$booking_ref = BookingDocket::get_bookref();
return json_encode(array('bookref' => $booking_ref,
)
);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
$dbh = null;
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title Work</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="lib/jq-ui/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" href="lib/jq-grid/ui.jqgrid.css" />
<script type="text/javascript" src="scripts/js/utils/util-sha256.js"></script>
<script type="text/javascript" src="lib/jq-core/jquery-1.4.4.min.js" ></script>
<script type="text/javascript" src="lib/jq-ui/jquery-ui-1.8.16.custom.min.js" ></script>
<script type="text/javascript" src="lib/jq-grid/grid.locale-en.js"></script>
<script type="text/javascript" src="lib/jq-grid/jquery.jqGrid.min.js" ></script>
<script type="text/javascript" src="scripts/js/interface-datagrids.js"></script>
<script type="text/javascript" src="scripts/js/image-preload.js"></script>
<script type="text/javascript" src="scripts/js/general-interface.js" ></script>
<script type="text/javascript" src="scripts/js/general-controlpanel.js" ></script>
<script type="text/javascript" src="scripts/js/general-validation.js"></script>
</head>
<body>
<div id="cp-bookings-dialog">
<div class="cp-tiles-wrapper-dlg">
<div class="cp-booking-info left">
</div>
</div>
</div>
</body>
</html>
What I am trying to achieve is that when you double click a booking, the booking reference (e.g. BR12345) is passed to bookings-dialog.php and used in the the query (e.g. SELECT * FROM tblbookings WHERE bookref = '$rowdata'). I have been trying to use JSON to achieve this but at the moment when I double click a row, it is just failing at the moment and I am unsure why.
Any suggestions?

Try:
$.ajax({
type: 'POST', //ADD THIS .ajax defaults to GET and in the php you expect POST
url: 'bookings-dialog.php',
data: {'rowdata' : brData },

The default HTTP type for AJAX calls is a GET. You should change to a POST.
$.ajax({
type:'POST',
...
http://api.jquery.com/jQuery.ajax/

Related

Ajax POST with mysqli database query

I am trying to get Ajax to POST to another.PHP file in the same directory as the main index. The idea is that I want an online diary that people can write into and have it instantly updated in the database.
Currently, my ajax looks like this
$('#diary').on('input propertychange', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
My PHP looks like this, on the updatedatabase.php page
<?php
session_start();
if ($_POST['content']) {
$link = mysqli_connect("location", "username", "password", "databasename");
if (mysqli_connect_error()) {
echo "Could not connect to database";
die;
}
$query = "UPDATE `users` SET `Diary` = '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE email = '".mysqli_real_escape_string($link, $_SESSION['email'])."' LIMIT 1";
if (mysqli_query($link, $query)) {
echo "Success";
} else {
echo mysqli_error($link);
echo "Failure";
}
}
?>
Full HTML + PHP at start of main page:
<?php
session_start();
$link = mysqli_connect(databaseinfo);
if (mysqli_connect_error()) {
echo "Could not connect to database";
die();
}
if (empty($_COOKIE['userId']) && (empty($_SESSION['email']))) {
header('Location: index.php');
}
$query = "SELECT email FROM users WHERE email = '".mysqli_real_escape_string($link, $_COOKIE['userId'])."' ";
if (!mysqli_query($link, $query)) {
header('Location: login.php');
die();
}
if(isset($_POST['logout'])) {
unset($_SESSION['email']);
setcookie('userId', '', time() - 60 * 60);
header('Location: login.php');
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
body {
background-image: url("images/landscape.jpg");
}
h1 {
text-align: center;
margin: 15px auto 30px auto;
}
#diary {
min-height: 40vw;
}
</style>
</head>
<body>
<div class="container">
<div class="container">
<h1>Secret Diary</h1>
<form method="POST">
<div class="form-group">
<button type="submit" name="logout" id="logout" class="btn btn-info">Logout</button>
</div>
</form>
</div>
<div class="form-group">
<div class="form-group">
<textarea class="form-control" name="diary" id="diary" rows="3" placeholder="shhh"></textarea>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#diary').on('input propertychange', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
</script>
</body>
</html>
I have tried changing from .on to .bind, I've tried different variations of the ajax code and update database code, I've tried looking around StackOverflow.
p.s I understand there are a couple of security errors in the mysqli query injections. This is mainly for my own practice and learning journey but I am struggling to figure this one out.
Many thanks in advance.
Use .on('change') to bind to the input event.
Also, don't use the slim minified jquery library if you're going to use ajax, it's not included. See jQuery 3 slim ajax basic example
EDIT: I got the script working, with this piece of html/js:
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#diary').on('change', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
</script>
You should use the change in jQuery like this:
$('#diary').on('change', function() {
code...
});
or
$(document).on('change', '#diary', function() {
code...
});
or if the #diary is not dynamically created (in runtime) you could do:
$('#diary').change(function() {
code...
});

Generating dynamic JSTree - JStree displays only when the database name is hard coded

In my website, I have a drop down select option that lists databases available in MySQL. Within each database, i have a table named tree. Whenever the select option is changed to a new database, or page reload happens, I do a post of database name to a php file.
I am using the following scripts on my page:
<!-- Color CSS Styles -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>*/
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/themes/default/style.min.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script src="https://use.fontawesome.com/f87c84f770.js"></script>
<link rel="stylesheet" href="lightslider.css"/>
<script src="lightslider.js"></script>
<script src="jtree.js"></script>
The code to post the database name is as follows:
index.php
$.post('autorefreshtree.php', {'folder':wd}, function(data) {
console.log(data);
});
autorefreshtree.php
session_start();
include('connect.php');
$database = $_POST['folder'];
//$database="IPL2010";
$connect = mysqli_connect($hostname, $username, $password,$database );
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connection successful";
}
category_tree(0);
function category_tree($catid){
global $connect;
$sql = "select * from `tree` where `parentid` ='$catid'";
$result = $connect->query($sql);
while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' . $row->nodename;
category_tree($row->tree_id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
endwhile;
}
mysqli_close($connect);
When I run the code, I get the Connection Successful message logged on to console, the tree is getting generated, and the complete ul li parameters along with the data gets printed on to console. However, the actual tree structure could not be seen.
When I make the following change in my autorefreshtree.php:
//$database = $_POST['folder'];
$database="IPL2010";
hard code the database name, both the tree is displayed as well as the console output could be seen.
The following is the display logic:
$(document).ready(function() {
var wd = localStorage.getItem('wd');
$.post('autorefreshtree.php', {'folder':wd}, function(data) {
console.log(data);
});
})
//Function to autorefresh tree
var requestUrl = 'autorefreshtree.php';
$(document).ready(function(){
$("#annotateDirectories").jstree({
'core' : {
'data' : {
'url' : requestUrl,
}
},
"checkbox": {
"keep_selected_style" : true,
'tie_selection' : false,
'two_state' : true
},
'plugins': ['wholerow','search','contextmenu','checkbox','state','sort']
});
});
(function(){
$.ajax({
type:'get',
url:requestUrl,
datatype:"html",
success:function(data) {
$('#annotateDirectories').jstree(true).settings.core.data = data;
$('#annotateDirectories').jstree(true).load_data('#');
}
});
});
//Function to retain the checked status of tree
var selectedBox = sessionStorage.getItem("annotateDirectories");
$('#annotateDirectories').val(selectedBox);
$('#annotateDirectories').change(function() {
var dropval = $(this).val();
sessionStorage.setItem("annotateDirectories", dropval);
});
Based on your description, the logic reason should be $_POST['folder'] is empty, i.e., wd is empty.
You connection to database is successful because your host, user and password is correct, but database is empty so that no database is selected.
I hope this code is not in production, but even in practice, you shouldn't query database in a loop.
jstree can be constructed by just a list of node and parent_node.

How to create an auto-complete search in Ajax and PHP?

I am creating a basic autocomplete ajax script to fetch the mysql database search results but am unable to display the results in the php page.
I can see the data getting fetched from the database in search.php as an array, but the same doesn't get displayed in the check.php page. Is this something because of some kind of css, or some other issue?
Any suggestions would be of great help!!
Here is the code >
check.php
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<style type="text/css">
li.ui-menu-item{
font-size: 12px !important;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('#regionsearch').autocomplete({
source: 'search.php',
minLength:1
});
});
</script>
</head>
<body>
<form action="" method="POST">
Search: <input type="text" name="search" id="regionsearch"/>
</form>
</body>
</html>
search.php
<?php
$dblink = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db('user_information');
if(isset($_REQUEST['term']))
exit();
$rs = mysql_query('Select * from registered_users where first_name like "'.ucfirst($_REQUEST['term']).'%" order by id asc limit 0,10',
$dblink);
$data = array();
while($row=mysql_fetch_assoc($rs, MYSQL_ASSOC)){
$data[] = array(
'label'=>$row['first_name'],
'value'=>$row['first_name']
);
}
echo json_encode($data);
flush()
?>
Yes, since you are using a jquery ui plugin, you will need to embed the appropriate css.
To follow what you've already done, use this line in your html template :
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"/>
You should as well se the doc to fetch remote data and adapt your code :
https://jqueryui.com/autocomplete/#remote-jsonp
$(document).ready(function(){
$('#regionsearch').autocomplete({
source: 'search.php',
minLength:1,
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
});

How do I access the datafields in the source object of a jqxlistbox

I'm trying to bind a JQXListbox to JSON data and display two fields in the result.
I want to access the datafields in the source object as strings in order to concatenate them so as I can set the resulting string as the displayMember property of jqxListBox. I've tried calling ToString() on the source.datafields[x] array but that doesn't work either.
I'm not sure if the terminology was correct there. Thanks for any help you can give.
Here is the code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="scripts/jqwidgets/styles/jqx.base.css" rel="stylesheet" type="text/css">
<link href="scripts/jqwidgets/styles/jqx.classic.css" rel="stylesheet" type="text/css">
<script src="scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxcore.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxbuttons.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxscrollbar.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxdata.js" type="text/javascript"></script>
<script src="scripts/jqwidgets/jqxlistbox.js" type="text/javascript"></script>
</head>
<body>
<div id="jqxlistbox"></div>
<script type="text/javascript">
var string;
$(document).ready(function() {
// prepare the data
var source =
{
datatype: "json",
datafields: [
{name: 'firstname'},
{name: 'lastname'}
],
url: 'my url is here'
};
string = source.datafields[0] + source.datafields[1];
alert(string);
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxlistbox").jqxListBox(
{
source: dataAdapter,
theme: 'classic',
width: 200,
height: 250,
displayMember: 'string',
valueMember: 'firstname'
});
});
</script>
</body>
</html>
I think that the "beforeLoadComplete" callback of the jqxDataAdapter plug-in will help you to customize the loaded data through the plug-in. For more information about that function, please look at: jqxDataAdapter plug-in

CodeIgniter Ajax CSRF Jquery Cookie Method behaving unexpectedly

Javascript Section:
var token = $.cookie("csrf_cookie_name");
var tx = document.getElementById("tx"+working_row).value;
var mods =document.getElementById("mods"+working_row).value;
var pos = document.getElementById("pos"+working_row).value;
var startdate = document.getElementById("startdate"+working_row).value;
var enddate = document.getElementById("enddate"+working_row).value;
var fordx = document.getElementById("4dx"+working_row).value;
var qty = document.getElementById("qty"+working_row).value;
var price = document.getElementById("price"+working_row).value;
obj = new Object();
obj={'csrf_token_name':token,'tx':tx,'mods':mods,'pos':pos,'startdate':startdate,'enddate':enddate,'fordx':fordx,'qty':qty,'price':price};
alert(obj.csrf_token_name);
$.post("index.php/auth/fee_schedule",obj, function(data){
alert(data);
});
The issue I'm having is that the token variable isn't being included in the post. I'm not sure why. The Alert is [Object Object] so, null. The header of the page has the following:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Medata Preauthorzation System</title>
<link rel="stylesheet" href="<?php echo base_url();?>css/screen.css" type="text/css" media="screen">
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.sexy-combo.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url();?>css/jquery-ui-1.8.13.custom.css" type="text/css" media="screen">
<link rel="icon" type="image" href="/medata/favicon.ico">
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.impromptu.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/cookie.js"></script>
</head>
So the Library and Cookie Functions are included. I use the cookie function 10 other times on the same page to do posts and it works fine, but I don't put any of them into objects with other variables, so it's just inline alla
$.post("index.php/auth/tx_history/"+tx_code, { csrf_token_name: $.cookie("csrf_cookie_name") }, function(data){
//alert(data);
$("#price"+rowid).val(data);
});
I'd Love some Suggestions, i've been hitting my head against this code most of the afternoon for non-stop issues.
Maybe:
var token = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");

Categories