Update information in database using php - javascript

I'm quite new to programming, and im trying to update a certain column in a database using php and javascript.
The data base only has 2 columns, seatnums and status. Basically, i want the status to reset back to 1 if the status is currently 0. Could anybody point me in the right direction?
I have a class inside a div in my HTML:
<a class='two' href="javascript:databaseReset() ">Reset</a>
My javascript function (Part im struggling with):
function databaseReset();
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
function over(id) {
selectedseat=$(id).attr('title');
$(id).attr('src','images/mine.gif');
$(id).attr('title', 'Available');
}
function out(id) {
$(id).attr('src','images/available.gif');
}
my php file:
<?php
include("dbconnect.php");
$query="UPDATE seats SET status=1 WHERE status=0";
$link = mysql_query($query);
if (!$link) {
die('error 2');
}
?>

I assume it was simply a typo, but your function call needs to wrap brackets around the ajax call:
function databaseReset(){ //<---*****Add these braces*****
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
}; //<---*****Add these braces*******
your code seems to declare the function, but not assign its functionality
Also, the data section is unnecessary, as it is not used. In fact, since you are not posting data, you can use the "GET" method instead.
Beyond that your code looks good, can you please specify what the issue is?

Related

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.

How do I pass javascript variable to Ajax script?

In an html button I have this onclick event:
onclick='javascript:updateStatus(59)'
Then I have this function
function updateStatus(){
$.ajax({
type: 'post',
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
And this is update-status.php
$sql = "UPDATE requests SET status='Closed' WHERE requestid=$requestid";
$updatestatus = mysqli_query($con, $sql);
if (!$updatestatus) {
die("Database query failed: " . mysqli_error($con));
} else {
return "success!";
}
Ultimately, I want the number from the original onclick event (in this example it's 59, but could be any number) to get passed into the $requestid variable in update-status.php.
What is the best/proper way to accomplish this?
Figured out to use "data" in the function after more googling, sorry.
Since you are using the JQuery AJAX function, just use another parameter in the configuration object, data. You're also missing an argument for the function.
function updateStatus(i){
$.ajax({
type: 'post',
data: 'requestid='+i,
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
You could also create a map and send the map, like so
...
data: {"requestid" : i},
...
You're server side code should be updated though. You don't want to be using input from the client without first sanitizing it. This opens up the threat for SQL Injection attacks.
for example, what if the value of requestid is
1 or '1'='1' --
or
1; drop table requests
First, take the passed in argument in your javascript function and send it to your PHP script like this:
function updateStatus(id){
$.ajax({
type: 'post',
url: '/update-status.php',
data: {id: id},
success: function(data){
}
});
return false;
}
In your PHP access it through $_POST['id']. However, make sure you escape the value to prevent SQL injection attacks.
$requestid = $_POST['id'];

Transfer data to javascript array with mysql data request via php and $.ajax

I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Cakephp master/details add

I have two tables, has-many relationship,
in the master add.ctp, allow user to upload 0~5 files(file path information are stored in details table)
I want to dynamically display attachment(detail) form in the master/add.ctp
1, user choose number of files want to upload from dropdown list,
echo $this->Form->input('attachments', array( 'options' => array(1, 2, 3, 4, 5),'empty' => '(choose one)', 'onchange' => 'showNumber(this.value)'));
then forloop
{
echo $this->Form->input('attachment_path', array('type'=>'file','label' =>'Attachment, Maximum size: 10M'));
}
//but I don't know how to capture this.value, I know Javascript can not pass value to php.
or user click 'add another attachment' link, then detail form shows up.
How to achieve this function, any help would be appreciated.
I have read this article:
Assign Javascript variable to PHP with AJAX
and get same error: the variable is undefined
Edit:
http://cakephp.1045679.n5.nabble.com/Adding-fields-to-a-form-dynamically-a-complex-case-td3386365.html
'For each field use a default name with [] at the end (which will make
it stack like a array) example: data[][book_id] after the fields have
been submitted'
Where should I place the []?
I think you should use Ajax for this.
Simply create an ajax call on select.change() and then a method in the controller that returns the necessary info.
You can return an array of data using echo json_encode(array('key' => 'value')) directly on your controller (or better in a custom view) and access it with Javascript:
success: function(data) {
alert(data.key);
}
Edit...
In your javascript use something like...
$('select').change(function(e) {
var select = $(this);
$.ajax({
type: "POST",
dataType: "json",
url: "/attachments/youraction",
data: { data: { id: select.find(":selected").val() } },
success: function(data) {
for (i in data) {
var input = $('<input>', {type: "file", label: data[i].Attachment.label})
$('form.your-form').append(input);
}
}
})
});
Then in "Yourcontroller" create "youraction" method:
<?php
class AttachmentsController extends AppController
{
public function youraction()
{
if (!$this->RequestHandler->isAjax() || !$this->RequestHandler->isPost() || empty($this->data['id']))
{
$this->cakeError('404');
}
// Do your logic with $this->data['id'] as the select value...
$data = $this->Attachment->find('all', array('conditions' => array('id' => $this->data['id'])));
// ....
// then output it...
echo json_encode($data);
// This should be done creating a view, for example one named "json" where you can have there the above echo json_encode($data);
// Then..
// $this->set(compact('data'));
// $this->render('json');
}
}
It's more clear now?? If you have doubts about ajax + cakephp you should do a search on the web, where you will find a lot of tutorials.
I use this approach to achieve this function. (finally got it :))
http://ask.cakephp.org/questions/view/foreach_loop_with_save_only_saving_last_member_of_array
Yes, AJAX can do lots of things, to me, it's very hard to understand the logic in a day..
Anyway, Thanks again.

Categories