Problems with PHP SQL HTML & AJAX submission - php

So I have yet another problem,
I am trying to get an AJAX script to work, but upon click the page will reload but fail to UPDATE the database field.
The code im using I have working for other similar scripts on the site but for some reason this one, using the same code doesnt work, the code used follows below;
HTML code to send the call to AJAX:
<input onClick="read('<? echo $id; ?>')" id="read" name="read" type="checkbox" value="1" style="position:relative; top:2px; width: auto">
The code to confirm user selection and send onto a form handling file:
function read(ID) {
if(confirm('Are you sure you have read this carefully, you will not be alerted again "' + ID + '" ?')) {
$.get('http://<? echo ROOT . ADMIN . INCLUDES; ?>formHandling.php', { read: ID }, function(data) {
window.location.href = 'http://<? echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].""; ?>';
});
}
return false;
}
Lastly the code to handle the SQL query:
if (isset($_GET['read'])) {
// Pass the GET data and associate them to variables
$read = trim($_GET['read']);
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
$result = mysql_query($query)or die("Database query died: " . mysql_error());
unset($_GET['readConfirm']);
}
Thanks in advance for all that help.
Regards,
Dan.

Don't you mean:
$query = "UPDATE cms_motd SET read='1' WHERE id='$read'";
Instead of:
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
Edit:
I don't know if it is a copy&past error:
$result = mysql_query($query);or die("Database query died: " . mysql_error());
Needs to be:
$result = mysql_query($query) or die("Database query died: " . mysql_error());

I have some challenges with the fact that you do the query but don't give your code any feedback to continue. For example, what if the query fails? Do you just press on?
Here's how I handle these sort of Ajax transactions (yes, longhand!)
$('#read').click(function() {
$("#div").dialog({ //Shows dialog
height: 250,
width: 450,
modal: true,
buttons: {
"Cancel": function() {
$( this ).dialog( "close" );
},
"Save": function() {
$.ajax({
url: "url.php", //
timeout: 30000,
type: "POST",
data: $('#form').serialize(),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
$('#updatediv).html(data.stuff);
src="web/imgs/icons/24deleteB.png"></td>';
}
$( this ).dialog( "close" );
}
}
});
});
Now, the URL.php will do the query and return a json_encoded string back to the AJAX that will then be able to know if the transaction was succesful via the success/error functions. You could do additional conditioning on the success case to ensure that something was saved a particular way or that a result matched a case that you wanted it to before doing something. On success, I show just a simple .html inner html type action, but you could do any quantity or variety of things such as show/hide, inner html, etc. The choice is yours. Also, note that I use Jquery UI dialogs instead of system dialogs, so you'd need Jquery UI to make it look pretty if you used this verbatim. Finally, rather than onclick note that I'm using the .click functionality that Jquery provides, which is just a hair cleaner.

Related

Jquery Ajax call to PHP don't give me any data back with dataType JSON

I'm working everyday with ajax and php at work, so it's nothing new. But now i tried a little project at home and i can't get it to work. I really don't know what i have done wrong. I just select a value from a dropdown and press a Button. The button has a onclick to a function calles "showTable". It selects the value of the dropdown and send it via ajax call to my index.php where i do a simple select to my database and wanna return the results, so i can build a table with it. But my ajax call always go to the error case, even if the result of the select is correct.
If i console.log my error, it just says "parseerror" but the network part always says 200 ok
So, this is my function within my index.html...
<script>
function showTable() {
var coin = $('#selectCoin').val();
$.ajax({
type: 'POST',
url: 'index.php',
dataType: "json",
data: {
act: 'showTable',
'coin' : coin
},
success: function(data) {
alert("ok")
},
error: function(request, error) {
alert("error")
}
});
}
</script>
And this is my php part
if($_POST) {
switch ($_POST["act"]) {
case 'showTable':
$token = $_POST["coin"];
$token_buy = $token.'_buy';
$token_sell = $token.'_sell';
$sql = "SELECT * FROM $token_buy";
$stmt = $PDO->prepare($sql);
$stmt->execute(array());
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
break;
}
}
I tried to update the composer and added the
"ext-json": "*"
Also i tried to remove the dataType Attribute from my ajax call. After that it don't get into the error case, but also i don't get my data from backend.
If i let me show the error with following function
error: function(jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText)
}
It says:
parseerror: SyntaxError: unexpected token "<", "<!DOCTYPE"...is not valid JSON: and continue with the whole html part in the error message

Passing a Jquery variable to use in a PHP script

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.

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!

How can I pass data from jQuery to php for saving into a database?

I've read about the jQuery.ajax method and believe this should be what I need -- but so far can't get it to work.
I created a test mysql database with a table called "users", added rows to that table for "name" and "location", and then made sure I could save data to it using the command line, which I could. Then I made a test page with a button on it and added this copy to my scripts file (the $.ajax part comes straight from the jQuery api examples):
$('#button').click(function(){
saveData();
});
function saveData(){
$.ajax({
type: "POST",
url: "process.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data was saved: " + msg );
});
}
I do indeed get an alert message, "Data was saved", but nothing has actually been saved to my database. I must be doing something wrong with process.php, but not sure what. Here's the code in process.php (I set variables for database, db_host, user, etc that I don't display here):
// 1. Create a connection to the server.
$connection = mysql_connect($db_host, $db_user,$db_pwd);
// make sure a connection has been made
if (!$connection){
die("Database connection failed: " . mysql.error());
}
// 2. Select the database on the server
$db_select = mysql_select_db($database, $connection);
if (!$db_select){
die("Database selection failed: " . mysql.error());
}
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}
It's has already been told by others, about using 'success' and 'error' which would be indeed a better method to capture the success/error callback. But that's really not the problem why nothing is inserted. Your Ajax call looks good besides that.
Another problem that i see is that you're only passing the following params:
data: { name: "John", location: "Boston" }
But in your PHP code you do check if a submit button was set:
if (isset($_POST['submit']))
This is obviously not the case because the only things that are sent are the things you pass in the 'data' attribute of the Ajax call. Instead use:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
In this example, $_POST['submit'] is not set because you are no sending the form as usual, you are rsendin data with ajax and there isn't any variable called "submit".
This may work better:
if ((isset($_POST['name'])) && (isset($_POST['location']))) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
}
"Done" doesn't mean "succeeded". Instead of done:, use this to see if it finished successfully or not:
success: function(data)
{
alert(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
}
all that
.done(function( msg ) {
alert( "Data was saved: " + msg );
});
is telling you is that the ajax request is done. Your probably need to look at .success instead. Additionally, your code doesn't show this so I'm assuming that it's not doing this but in order for msg to have anything in your php needs to actually return something. (PHP people help me out with this I'm a .Net guy helping with the JS :) )
Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. Check that by putting in the following else clause to your code. If you're hitting that die statement, then remove the if test
if (isset($_POST['submit'])) { // Form has been submitted.
$name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));
// INSERT THE DATA
$query = "INSERT INTO user ( name, location )
VALUES ( '{$name}','{$location}' )";
// Confirm if the query is successful.
$result = mysql_query($query, $connection);
} else {
die("$_POST['submit'] didn't exist");
}
Its a simple mistake. You left submit while posting to process.php while you are checking its existence before updating DB
$('#button').click(function(){
saveData();
});
function saveData(){
$.ajax({
type: "POST",
url: "process.php",
data: { name: "John", location: "Boston",submit:"submit" }
}).done(function( msg ) {
alert( "Data was saved: " + msg );
});
}

PHP and JavaScript Change Status in MySQL

So I have a to-do list of items that are dynamically populated by user input. Each has a checkbox next to it, when checked, the status of the to-do item in MySQL database should be modified.
I thought of doing it this way:
echo "<input type='checkbox' onclick='changeState($theid);' />";
where $theid is the row id in the table.
What would the javascript/jquery changeState() function look like to be able to update the database properly?
Here is the javascript code that seems to not work at all (it is placed in the <head> of the HTML file:
<script language="javascript">
function changeState()
{
jQuery('body').delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('updatedata.php', {
'rowid': jQuery(this).attr('data-state-id')
//'state': jQuery(this).is(':checked')
});
});
}
</script>
any ideas why?
You should read more about AJAX calls, preferably with .post() function, and then update the data in database on the server side.
Good luck.
Based on the examples from the documentation of jQuery's .post(), you can implement something like this (in JavaScript with jQuery):
var changeStatus = function(id){
$.post("updateState.php", { 'id': id } );
};
and on the server side (eg. in updateState.php):
$id = (int)$_POST['id'];
// here make some query using $id to update the state
// in a manner you prefer
EDIT:
But I would prefer something like that:
1) on server side, displaying the checkbox (notice different quotes and (int) cast):
echo '<input type="checkbox" data-state-id="' . (int)$theid . '" />';
2) somewhere in JavaScript (see jsfiddle as a proof):
jQuery(main_container).delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('update_state.php', {
'id': jQuery(this).attr('data-state-id'),
'state': jQuery(this).is(':checked')
});
});
3) somewhere on server side (in update_state.php):
$id = (int)$_POST['id'];
$state = (bool)$_POST['state'];
$query = 'UPDATE `states` SET `state`="' . $state . '" WHERE `id`="' . $id . '";';
// here execute the query, obviously adjusted to your needs
You don't need to think of this as: "JavaScript will update the SQL Record", think of this as "JavaScript will tell a API to update that id."
So basically what you have to do is make an API with PHP; and then make JavaScript do the correct API Call via $.ajax, that should do the trick.
$.ajax({
url: '/path/to/api.php',
type: 'POST',
dataType: 'xml/html/script/json/jsonp',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});

Categories