How to create an auto-complete search in Ajax and PHP? - 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 );
}
});
});

Related

Posting data using jQuery Ajax to another php file [duplicate]

This question already has answers here:
What is the order of inline onclick vs addeventlistener and why?
(3 answers)
Closed 2 years ago.
I have two PHP pages. On one of the pages, I want to post data to the other page when a button is pressed. However, when I try to access the post array from the other page, it appears empty. Would appreciate if someone could show me where I'm going wrong. (Also I'm not allowed to use a html form to post)
Page called test2.php:
<?php
if(isset($_POST['testing1'])){
die(json_encode($_POST));
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: {
testing1: 'string1',
testing2: '111'
},
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
$testvar = json_encode($_POST);
echo $testvar;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
the reason the it's failing is because you have so much html on test1.php
alert(data) is having an issue because there is so much content.
JSON.parse(data) is failing because it's not just json it's also html
test1.php should just simply parse post to json and echo it
<?php
echo json_encode($_POST);
?>
When you press the button 2 things are happening in same time :
The ajax call that sends data to the page test1.php
The page redirection beacause of the onClick attribute on the button.
The ajax request calls the page test1.php which is not the same instance as the page you call when you use the onClick attribute. So I think you could try placing "location.href = 'test1.php'" in the success function and store $_POST in a session variable. That way the data will reach the test1.php page before your redirect.
success: function(data){
alert(data);
output = JSON.parse(data);
location.href = 'test1.php';
}
Maybe like this:
Page called test2.php:
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: "yourData="+"{
testing1: 'string1',
testing2: '111'
}",
dataType:"json",
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
if(isset($_POST["yourData"]){
$testvar = json_decode($_POST["yourData"]);
echo $testvar->testing1."<br/>";
echo $testvar->testing2;
}else{
echo"is not set";
}
if(!empty($_POST["yourData"]){echo $_POST["yourData"];}else{echo"is empty";}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
NB:
dataType:"json" used if you want to get a json answer;
if you use dataType:"json" that mean you have to change the method json_decode() in my code to json_encode();
isset() check if name of associative array is exist;
! means not;
empty() check that if the value of that name in associative array is empty (like ' ');
!empty() check that if the value of that name in associative array is not empty (not like ' ').

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...
});

Access JavaScript variables value in php to store in mysql

Just simple,
I am trying to access the variable in javascript inside the php while working with elrte,
bleow is my index.php file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>One textarea with elRTE and file upload plus one text field with elFinder</title>
<!-- jQuery and jQuery UI -->
<script src="js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.7.custom.min.js" type="text/javascript" charset="utf- 8"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.7.custom.css" type="text/css" media="screen" charset="utf-8">
<!-- elRTE -->
<script src="js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="css/elrte.min.css" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="css/elrte.full.css" type="text/css" media="screen" charset="utf-8">
<!-- elFinder -->
<link rel="stylesheet" href="css/elfinder.css" type="text/css" media="screen" charset="utf-8" />
<script src="js/elfinder.full.js" type="text/javascript" charset="utf-8"></script>
<!-- elRTE and elFinder translation messages -->
<!--<script src="js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>
<script src="js/i18n/elfinder.ru.js" type="text/javascript" charset="utf-8"></script>-->
<script type="text/javascript" charset="utf-8">
// elRTE with elFinder on a textarea
$().ready(function() {
var opts = {
cssClass : 'el-rte',
lang : 'en', // Set your language
allowSource : 1,
height : 450,
toolbar : 'maxi', // 'tiny', 'compact', 'normal', 'complete', 'maxi', or 'custom' (see advanced documentation for 'custom')
cssfiles : ['css/elrte-inner.css'],
fmAllow : 1,
fmOpen : function(callback) {
$('<div id="myelfinder" />').elfinder({
url : 'connectors/php/connector.php',
places : '',
lang : 'en', // Set your language
dialog : { width : 900, modal : true, title : 'Files' }, // Open in dialog window
closeOnEditorCallback : true, // Close after file select
editorCallback : callback // Pass callback to file manager
})
}
}
$('#editor').elrte(opts);
// Text field with elFinder
var opt = {
url : 'connectors/php/connector.php',
places : '',
lang : 'en',
editorCallback : function(url) {document.getElementById('field').value=url;}, // The id of the field we want elfinder to return a value to.
closeOnEditorCallback : true,
docked : false,
dialog : { title : 'File Manager', height: 500 },
}
$('#open').click(function() { // The id of the button that opens elfinder
$('#finder').elfinder(opt) // The id of the div that elfinder will open in
$('#finder').elfinder($(this).attr('id')); // it also has to be entered here.
})
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
});
})
})
</script>
</head>
<body>
<?php
$q=mysql_query("select * from aw_about_us")or die(mysql_error());
$r=mysql_fetch_array($q);
extract($r);
?>
<div id="finder"></div>
<table cellpadding="5" cellspacing="5" border="0" width="100%">
<form name="feedback" id="frm" method="post">
<tr>
<td>Title : </td>
<td><input type="text" id="atitle" size="75" value="<?=$abt_title?>"></td>
</tr>
<tr>
<td>Tag Line : </td>
<td><input type="text" id="atag" size="75" value="<?=$abt_small_line?>"></td>
</tr>
<tr>
<td colspan="2"><textarea id="editor" id="acontent" cols="50" rows="4">
<?=$abt_content?>
</textarea></td>
</tr>
<!--<input type="text" id="field" name="field" size="60"/> -->
<!--<input type="button" id="open" value="Browse..." /><br>-->
<tr>
<td><input type="submit" id="btnsub" value="Submit"></td>
</tr>
</form>
</table>
<?php
/*echo $_GET['val'];
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
*/?>
</body>
</html>
I am able to get the value of elrte inside the javascript variable, but now I wanted store this value inside the mysql database, as I am using PHP I want to access this value inside a php so that I can store it in database,
I tried using window.open("abc.php?val="+content); but the value is very large so get method cannot be acceptable here, so is there any way to get this value inside the php? or any alternate way to do this?
** Edit :**
Now it gives me a value of content variable after making following changes, but I want all 3 variables, but unable to get
$('#btnsub').click(function() {
var content = $('#editor').elrte('val');
var title = document.getElementById('atitle').val;
var tag = document.getElementById('atag').val;
alert('title'+title);
$.ajax({
type: "POST",
url: 'abc.php',
data: {title : title, tag : tag, content : content},
success: function(html) { $('result').append(html); },
dataType: 'html'
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and php file
<?php
include('inc/conn.php');
if(isset($_POST['updabt']))
{
$cont=$_POST['updabt'];
$q1=mysql_query("update aw_about_us set abt_title='$title', abt_small_line='$tag', abt_content='$cont'") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
Now how to get all three variables??
You'll need to submit the value to your PHP script using a POST request to your server. You can do this with Ajax requests, and I believe jQuery has built-in methods for Ajax which are cross-browser.
You need 2 pages, one which will send AJAX (this you have) and one wich will respond (below):
<?php
///ajax.php
if(isset($_POST['updabt']))
{
extract($_POST);
$q1=mysql_query("update aw_about_us set abt_title='$atitle', abt_small_line='$atag', abt_content=''") or die(mysql_error());
if($q1==true)
{
?><script>alert("Page Updated Successfully!!");</script><?php
}
else
{
?><script>alert("Page Not Updated!!");</script><?php
}
}
?>
In javascript you create AJAX post
data['updabt'] = '';
$.ajax({
type: "POST",
url: 'ajax.php',
data: data,
success: function(html) { $('result').append(html); },
dataType: 'html'
});
You can use AJAX (easiest with a library such as jQuery) to submit the variables to another PHP script that will INSERT the values to your database.
Start by reading the following...
jQuery.ajax
jQuery.post
This is actually very simple once you get your head around the subtleties of AJAX.
Here is a simple example to get you off and running. Suppose you wanted to log something to your PHP error log...
This would be my JavaScript function:
var log = function(val) {
$.post("ajax.php", {"mode": 'log', "val": val}, function() {});
}
ajax.php would be a collection of functions, ideally a class...
public function __construct() {
$arrArgs = empty($_GET)?$_POST:$_GET;
/**
* using 'mode' I can send the AJAX request to the right method,
* and therefore have any number of calls using the same class
*/
if (array_key_exists('mode', $arrArgs)) {
$strMethod = $arrArgs['mode'];
unset($arrArgs['mode']);
$this->$strMethod($arrArgs);
}
}
protected function log($arrArgs) {
error_log($arrArgs['val']);
}
The same idea can easily be adapted to write data to a database.

Sending Jquery value to PHP page

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/

Saving Changes in SlickGrid with php

I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>

Categories