PHP and JavaScript Change Status in MySQL - php

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

Related

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

Trying to get information from database with jQuery

I am VERY new to jQuery, and I have been trying to get information from my SQL database whenever the user chooses a new option in a datalist form. This is the code:
<form>
<input list="chemicals" name="chemicalsearch">
<datalist id="chemicals">
<?php while ($info3=mysql_fetch_array($info2)) {
echo "<option value='$info3[name]'>$info3[formel]</option>";
}
?>
</datalist>
</form>
<script type="text/javascript">
$('#chemicals').on('change', function() {
var record_id = $(this).val();
var data = {
'id': record_id
};
$.ajax({
type: "GET",
url: '/Chemistry%20Calculator/getchemical.php',
data: data,
success: function(response) {
document.getElementById('formel').innerHTML = data.formel;
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
</script>
And then the PHP file:
<?php
include_once 'connect.php';
$info="SELECT * from chemicals where name='$id'";
$info2=mysql_query($info) or die("Wrong link. This page does not exist.");
$info3=mysql_fetch_array($info2);
$name = $info3['name'];
$formel = $info3['formel'];
$massa = $info3['molmassa'];
$array = array($name, $formel, $massa);
$data = json_encode($array);
echo $data;
?>
Please be patient with me here, as I have never used jQuery before. And yes, I am aware of the fact that I'm using the old MySQL syntax, I will change that as soon as I get this working.
Any help would be greatly appreciated :)
You are not writing what exactly is the problem, either from the side of php or javaScript. But anyway, correct your syntax to php regarding the variables. Like below:
<?php while ($info3=mysql_fetch_array($info2)) {
echo '<option value="'.$info3[name].'">'.$info3[formel].'</option>';
}?>
and later on your query...$info='SELECT * from chemicals where name="'.$id.'"'
The success method is a function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified;
A string describing the status;
The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
In your case:
success: function(data, textStatus, jqXHR) {
//The "data" returned from server is assigned to HTML element here
document.getElementById('formel').innerHTML = data;
}
A side note: usage of mysql_* functions is deprecated, use PHP PDO instead.
EDIT: Do not forget to include jQuery library in your file, before trying to execute the code $(“#chemicals")..... The error of $ being undefined means exactly that.

ajaxFileUpload on xhr.setRequestHeader is not a function

In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.

Updating a page element in a php script

Page elements are defined like this.
<div id="readf" class="tabbertab">
<h2>First Reading</h2>
<div id='titlefe' class='rtitle'>
</div>
<div id='readfe' class='rtext'>
</div>
</div>
I make an ajax call to a php script to add data to these page elements.
<script>
$('#readings').ready(function(){
$.ajax({
url: "loadenglish.php",
type: "GET",
data: { },
cache: false,
async: true,
success: function (response) {
if (response != '')
{
alert (response);
}
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
});
</script>
The php script gets the data and does a script echo to add the data.
<?php
$titlefe = 'text 1';
$readfe = 'text 2';
echo "<script type='text/javascript'> $('#titlefe').append('".$titlefe."'); $('#readfe').append('".$readfe."'); </script>";
?>
The alert statements shows that the php script gets the right information. But the page elements are not updated. Is there a different way to add $titlefe to element id titlefe?
In addition to what MK_Dev posted you can use PHP function json_encode();
<?php
//loadenglish.php
$params = array(
'titlefe' => 'text 1',
'readfe' => 'text 2',
);
echo json_encode($params);
Also there is a jQuery function $.getJSON(), which is a shortcut for $.ajax() function usage like yours.
Try eval(response); after your alert in the success callback.
Returning javascript methods is not a good idea. You should return data in JSON format and use javascript on the client side to perform the actual update.
Your PHP return statement should look like:
echo "{ 'titlefe': '" + $titlefe + "', 'readfe': '" + $readfe + "' }";
and your success call back should look like this:
success: function(response) {
$('#titlefe').text(response.titlefe);
$('#readfe').text(response.readfe);
}
If you insist on returning JavaScript, you should be using getScript() instead of an Ajax get.

Problems with PHP SQL HTML & AJAX submission

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.

Categories