Passing a Jquery variable to use in a PHP script - php

I know I've asked this question before but I still need help with this, basically:
I have a booking grid as shown below which is on bookings.php
On this booking grid I have a dblClick event:
ondblClickRow: function(rowid)
{
rowData = $("#bookings").getRowData(rowid);
var brData = rowData['bookref'];
getGridRow(brData);
$("#cp-bookings-dialog").dialog({ hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});
},
This also opens a Jquery Dialog window on bookings.php:
<div class="cp-tiles-wrapper-dlg">
<div class="cp-booking-info left">
<p class="pno-margin">Booking Date: <strong>Booking Reference is = <? echo BookingDocket::get_bookref(); ?></strong></p>
<p class="pno-margin">Return Date: <strong><? echo BookingDocket::get_bookdate(); ?></strong></p>
<p class="pno-margin">Journey: <strong></strong></p>
<p class="pno-margin">Passenger Tel: <strong></strong></p>
<p class="pno-margin">E-mail: <strong></strong></p>
</div>
</div>
Where brData is the 'Booking Reference' value that I want to use in my PHP script. At the moment this dblClick event is being sent to the following Ajax request:
function getGridRow(brData) {
$.ajax({
url: 'scripts/php/bootstrp/all.request.php',
type: 'POST',
data: {
fnme: 'getDGRow',
rowdata: brData,
id: null,
condition: null
},
dataType: 'text/xml',
timeout: 20000,
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(response){
// Refresh page
//response = brData;
//alert(response); <-- This alerts the correct Booking Reference value
}
});
Which gets sent to all.request.php
// Switch to determine method to call
switch ($_REQUEST['fnme']) {
case 'getDGRow':
header('Content-type: text/xml');
GetBookings::getGridRow($_REQUEST['rowdata']);
break;
And finally to the PHP script where I want to use this Jquery value:
class GetBookings {
public static function getGridRow($rowdata) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT * FROM tblbookings WHERE bookref = '$rowdata'";
//echo $query; <-- this passes the correct Booking Reference to £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']);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
$dbh = null;
}
}
?>
I'm not sure why, but this doesn't seem to be working. Basically at the time when the Jquery Dialog window is opened, $rowdata is null, but when I echo the query, it shows that $rowdata has the correct value.
I have tried putting the code for the jquery window into a seperate php file and in the sucess ajax script I have added the following:
$('#cp-bookings-dialog').load('bookings-dialog.php', function() {
alert('Load was performed.');
});
but this doesn't make any difference. I know all the code is correct because if I set $rowdata to 'BR12345' for example, it displays the values I need in the jquery booking dialog. What I believe needs to be done is for the PHP query to run after the value $rowdata has been passed to the PHP script.
Anybody got any idea of how I can do this?

You need to return a JSON encoded object from your PHP script to use in your pop up. Your echo call is evaluated before the AJAX call is made, and worse, it does not know about GetBookings state at all (the state is only valid for a single request).
And why is everying static? That looks like a bad software design.

Related

Using MySQL results in javascript

I have a web application where I need to get values from a MySQL database.
The series of event is as follows:
PHP code creates HTML page (works fine)
Click a button on the page, updating a cookie (works fine)
Use cookie in a MySQL query (This does not work)
Get a record from the above MySQL query result and pass to HTML page with jQuery
The problem with bullet 3 is that the MySQL query is only run when I load the page (of course). But I need a method to run a query, based on user input (stored as the cookie), without reloading the PHP script.
How can this be done?
My engineering c-coding brain has a really hard time wrapping this ajax thing. Here is the code so far, still not working:
The popup(HTML) I want to update with new strings when a button on the same page, is clicked:
<div id="popup" class="popup" data-popup="popup-1">
<div class="popup-inner">
<h2 id="popup-headline"></h2> //Headline, created from a cookie. Could be "Geography"
<div id="dialog"></div> //From Will's suggestion
<p id="question"></p> //String 1 from online MySQL DB goes here "A question in Geography"
<p id="answer"></p> //String 2 from online MySQL DB goes here "The answer to the question"
<p class="popup-small-button"><a data-popup-close="popup-1" href="#"><br>Close</a></p> // Hides the popup
<a class="popup-close" data-popup-close="popup-1" href="#">x</a>
</div>
</div>
Then i have my file with custom functions. It executes whenever the popup is shown:
<script>
jQuery(function() {
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
data: {
my_var1: 'question',
my_var2: 'answer'
},
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
</script>
My server.php file contains now this:
<?php
require("db.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
And my db.php contains this:
<?php
function myfunction($var1, $var2) {
$db = mysqli_connect('MyOnlineSQLPath','username','password','database1_db_dk');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $_COOKIE('category'));
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
?>
What I need, is the "question" and "answer" from the SELECT query.
TL;DR I need question and answer strings to go into <p id="question"></p> and <p id="answer"></p> in the HTML, both without refreshing the page. The getCookie('category') is a cookie stored locally - It contains the last chosen category for a question. The function getCookie('category') returns an integer.
Let me know if you need any more info on this.
Here is some template AJAX that may help you out. I used this in another project. This won't require a page refresh. You will have to include the code to send your cookie's data in the 'data' section.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<meta charset="utf-8">
</head>
<body>
// your HTML here
<script>
<div id="dialog"></div>
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
$.ajax({
type: 'post',
url: 'myphpfile.php',
data: {
my_var1: 'myval',
my_var2: 'myval2'
},
success: function(data) {
$("#dialog").html("<span>Success!</span>");
$("#dialog").fadeIn(400).delay(800).fadeOut(400);
}
});
}
</script>
</body>
</html>
Then in the file 'myphpfile.php', you'll have code like the following:
<?php
require("../mycodebase.php");
if(isset($_POST['my_var1']) && isset($_POST['my_var2'])) {
myfunction($_POST['my_var1'], $_POST['my_var2']);
}
?>
Finally, in mycodebase.php (which is stored in a place inaccessible to the public/world), you'll have a function that actually runs your query and returns your result:
function myfunction($var1, $var2) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("UPDATE mytbl SET col1=? WHERE col2=?;");
$stmt->bind_param("ss", $var1, $var2);
$stmt->execute();
$result = (($db->affected_rows) > 0);
mysqli_close($db);
return $result;
}
UPDATE
That function above is to run an UPDATE query, so the result returned just indicates whether you successfully updated your data or not. If you want to return an actual result, you have to extract the result from the query as follows:
function myfunction($cat) {
$db = mysqli_connect('localhost','myuser','mypass','dbname');
$stmt = $db->prepare("SELECT question, answer FROM t_da_questions WHERE category_id=?;");
$stmt->bind_param("s", $cat);
$stmt->execute();
$retval = false;
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
if(!is_null($row['question']) && !is_null($row['answer'])) {
$retval = new stdClass();
$retval->question = row['question'];
$retval->answer = row['answer'];
}
}
mysqli_close($db);
return $retval;
}
Then your server.php file will look like:
<?php
require("db.php");
if(isset($_COOKIE['category'])) {
json_encode(myfunction($_COOKIE['category']));
}
?>
Here's the JS:
jQuery('[data-popup-open]').on('click', function(e) {
function myfunction(myparams) {
// your logic here: testing myparams for valid submission, etc.
alert("hey");
jQuery.ajax({
type: 'post',
url: 'server.php',
// data section not needed (I think), getting it from the cookie
success: function(data) {
data = JSON.parse(data);
jQuery('#question').html(data["question"]);
jQuery('#answer').html(data["answer"]);
}
});
}
});
This is untested -- I may have gotten an argument wrong, but this is at least very close if it's not already there.

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Query string parameters from Javascript do not make it to processing PHP script

I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!

Problem to display server side data mysql to phone WebOS!

I am new to WebOS Dev and just started before a week. So, need a little bit help.
From last 2 days I'm stuck in one problem.
I want to display my server side data to client mobile, with the help of palm sample project I am able to display static posted data on client mobile(display every time same posted data values).
But, I want to post value from text box(Display data which is posted via textbox).
if you already installed webos SDK then you can find the sourcecode from here
C:\Program Files\Palm\SDK\share\samplecode\samples\Data\....
just try to run both method AJAX GET and AJAX POST , i want to do some thing like in AJAX GET method(Google ex.)
my modified code is
ajaxPost-assistant.js (i want to add textbox in this code and display data which is posted by this page )
var myassistant = null;
function AjaxPostAssistant()
{
}
AjaxPostAssistant.prototype.setup=function()
{
myassistant = this;
this.textFieldAtt = {
hintText: 'hint',
textFieldName: 'name',
modelProperty: 'original',
multiline: false,
disabledProperty: 'disabled',
focus: true,
modifierState: Mojo.Widget.capsLock,
limitResize: false,
holdToEnable: false,
focusMode: Mojo.Widget.focusSelectMode,
changeOnKeyPress: true,
textReplacement: false,
maxLength: 30,
requiresEnterKey: false
};
this.model = {
'original' : 'Palm',
disabled: false
};
this.controller.setupWidget('sendField', this.textFieldAtt, this.model);
this.buttonModel1 = {
buttonLabel : 'Push to send post',
buttonClass : '',
disable : false
}
this.buttonAtt1 = {
//type : 'Activity'
}
this.controller.setupWidget('post_button',this.buttonAtt1,this.buttonModel1)
Mojo.Event.listen(this.controller.get('post_button'),Mojo.Event.tap,this.handlePost.bind(this));
}
AjaxPostAssistant.prototype.handlePost=function(event)
{
var posturl='http://openxcellca.info/Parthvi/webos/ajaxpost1.php';
var postdata='fname=Ajay';
var myAjax = new Ajax.Request(posturl, {
method: 'post',
evalJSON: 'force',
postBody: postdata,
contentType: 'application/x-www-form-urlencoded',
onComplete: function(transport){
if (transport.status == 200)
myassistant.controller.get('area-to-update').update('Success!');
else {
myassistant.controller.get('area-to-update').update('Failure!');
}
myassistant.controller.get('server-response').update('Server Response: \n' + transport.responseText);
},
onFailure: function(transport){
myassistant.controller.get('area-to-update').update('Failure!\n\n' + transport.responseText);
}
});
}
AjaxPostAssistant.prototype.activate = function(event) {
/* put in event handlers here that should only be in effect when this scene is active. For
example, key handlers that are observing the document */
}
AjaxPostAssistant.prototype.deactivate = function(event) {
/* remove any event handlers you added in activate and do any other cleanup that should happen before
this scene is popped or another scene is pushed on top */
}
AjaxPostAssistant.prototype.cleanup = function(event) {
/* this function should do any cleanup needed before the scene is destroyed as
a result of being popped off the scene stack */
}
ajaxPost-scene.htm
<div x-mojo-element="Button" id="post_button"></div>
<div id="area-to-update"></div>
<br>
<div id="server-response"></div>
ajaxpost1.php
<?php
$con = mysql_connect("localhost","user","pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$qry = "SELECT * FROM user WHERE fname='.$_POST['fname'].'";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result))
{
echo "Name:-".$row['fname'];
echo "<br />";
echo "E-mail:-".$row['email'];
echo "<br />";
echo "Phone:-".$row['phone'];
echo "<br />";
}
mysql_close($con);
?>
Please help me, I want to make one sync app for my college project.
And I need to complete in this 3 weeks.
I'm no WebOS expert, but first make sure that your php server side script is sending JSON. It's much clearer to handle the response: see my question here
Then it should be pretty easy.

jQuery ajax delete script not actually deleting

I have a little personal webapp that I'm working on. I have a link that, when clicked, is supposed to make an ajax call to a php that is supposed to delete that info from a database. For some unknown reason, it won't actually delete the row from the database. I've tried everything I know, but still nothing. I'm sure it's something incredibly easy... Here are the scripts involved.
Database output:
$sql = "SELECT * FROM bookmark_app";
foreach ($dbh->query($sql) as $row)
{
echo '<div class="box" id="',$row['id'],'"><img src="images/avatar.jpg" width="75" height="75" border="0" class="avatar"/>
<div class="text">',$row['title'],'<br/>
</div>
/*** Click to delete ***/
x</div>
<div class="clear"></div>';
}
$dbh = null;
Ajax script:
$(document).ready(function() {
$("a.delete").click(function(){
var element = $(this);
var noteid = element.attr("id");
var info = 'id=' + noteid;
$.ajax({
type: "GET",
url: "includes/delete.php",
data: info,
success: function(){
element.parent().eq(0).fadeOut("slow");
}
});
return false;
});
});
Delete code:
include('connect.php');
//delete.php?id=IdOfPost
if($_GET['id']){
$id = $_GET['id'];
//Delete the record of the post
$delete = mysql_query("DELETE FROM `db` WHERE `id` = '$id'");
//Redirect the user
header("Location:xxxx.php");
}
Ah just spotted your error, in the href you're generating you're not setting the id attribute. It should be something like:
x
Of course that's just an immediate example, you must escape these kinds of things but this should let you access the item in jQuery.
You may want to modify your delete script to not just redirect after the DB query. Since it's being called via AJAX, have it at least return a success/error code to the javascript:
// can't return $delete unconditionally, since *_query() returns an object
if ($delete) {
return(json_encode(array('code' => 1, 'msg' => 'Delete succeeded')));
} else {
return(json_encode(array('code' => 0, 'msg' => 'Delete failed: ' . mysql_error()));
}
It's bad practice to assume a database call succeeded.

Categories