SQL Query creates buttons that one can click to 'hopefully' change DIV - php

I am failing hardcore with describing this but here it goes..
I have home.php, pretty much just:
<body>
<div id='leftColumn'>
<?php include ('includes/roomQuery.php')
</div>
</body>
Now,
roomQuery.php echos my sql column 'room_name' from table 'rooms' as follows:
echo "<td>$roomName</td>";
Any of the room links will take me to room.php and populate the page with more queries respective to $roomName via $_GET.
room.php is basically:
$get = $_GET['room'];
$query
while($row = $result->fetch_assoc()){
echo $query
This is working perfectly for what it is.
====================================
however, I am trying to make my site flow better, and have been trying out the jQuery .load function. So far I have changed roomQuery.php to:
echo "<td><button>$roomName</button></td>";
here is my jQuery to replace home.php #page with room.php #page:
$(document).ready(function(){
$("button").click(function(){
$("#page").load("room.php #page",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
When I click any of the buttons that roomQuery.php spits out, it replaces #page perfectly but I cannot grasp how/if I can send $_GET['room'] to room.php so that when #page is loaded, the information is still respective to the room I clicked on. If I change jQuery to
$("#page").load("room.php?room=CL%20124 #page"
Then #page is populated with the data specifically respective to room CL 124. Is it possible to post the button text that is output from roomsQuery.php to room.php #page when the button is clicked?

Yes, you can pass data into the .load() call as the second parameter.
Firstly, you need to work out how to get the room ID from the DOM into your jQuery call, maybe you could use a data attribute on the button element like this:
<button data-room-id="123">Click me</button>
Then use jQuery like this:
$("button").click(function(){
// define your room ID here, however you do it
var your_room = $(this).data('room-id');
$("#page").load(
"room.php #page",
{
room: your_room
},
function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
}
);
});
Edit: just noticed that you might actually be using the button's value as your room ID, if so, use this definition:
var your_room = $(this).val();
If you're expecting spaces or non-alpha numeric characters in this value, you might want to consider URL encoding it before you send it.

Related

jQuery / php / mysql - how to manipulate a mysqli_query without reloading the page?

I have a table containing data read from a MySQL database via PHP. The first column holds all item names. Now, on clicking a td element in the first column of the table would link to a page with more detailed information about the item contained in the td.
Now I came up with the following idea:
$(document).ready(function() {
$('#table td:first-child').click(function() {
$('div.main').animate({
height: "50px"
}, 600);
setTimeout(function() {
$('div.data').fadeIn(1000);
}, 600);
});
});
div.main is the div-container that has the table included. What I want to do now is to slide that container up and fade a new div-container in, right below it, the new container include()s a PHP page which holds a dynamic query (pseudocode, no string escaping, simplified version):
SELECT detail FROM items WHERE items.name = $_GET['name'];
What I couldn't figure out is if and how I can tell the PHP file that is included in the in-fading div-container which item name it has to grab details for, off the database.
Right now I can read the item name via JavaScript/jQuery, but I couldn't figure a way out to pass that value to the PHP file without having to reload the page.
Any ideas or suggestions welcome!
I think what you're looking for is asynchronous JavaScript and XML (AJAX). It sounds intimidating, but fortunately jQuery makes it very easy.
You can call $.ajax() directly, but for most cases, you can use one of the convenience wrappers. In this case, I think $.load() will meet your needs.
So, let's say your PHP file is called detail_ajax.php and it returns the HTML you wish to put in your div (with class data). All you would have to do then is this:
$('div.data').load( '/detail_ajax.php', function(data){
$(this).html(data);
});
If you want to pass data TO detail_ajax.php, you can pass it along this way:
$('div.data').load( '/detail_ajax.php', { 'someField' : 'someValue' },
function(data) {
$(this).html(data);
}
});
In detail_ajax.php, if you examine $_POST['someField'], you will see the value passed in.
You can do this by using ajax. Output your query on a separate page in JSON format then fetch it using jquery ajax
you need to use ajax to do the same thing. create an event like onclick and call a
method on click call ajax set variable in js and pass it to and do as you want,
show data in particular div in response. Hope it will help you.
You are looking for $.ajax(). However, 3 things will need to take place for this to happen as you intend.
First, we need a reference held in the HTML that is generated by the table so we can streamline the server request. When you generate the table, add a unique data-name string to the TD.
<td data-name="<?php echo $row['name']; ?>">
If, for instance, the td's were generated in a foreach loop, where we expect an array to be returned.
Now, we need to detect the request on our page so we can properly return the data to the browser, we'll look for $_GET['name'] as per your example.
<?php
if(isset($_GET['name'])):
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$ret;
if($stmt = $mysqli->prepare('SELECT detail FROM items WHERE items.name = ?')):
$stmt ->bind_param('s', $_GET['name']);
$stmt ->execute();
$stmt ->bind_result($details); // we only want one column
$stmt ->fetch(); //get our row
$ret['success'] = TRUE;
$ret['html'] = '<div>'. $details .'</div>';
else:
$ret['success'] = FALSE;
endif;
echo json_encode($ret); //return to the browser
endif;
?>
Now we need to employ ajax to bridge the gap between the server and the browser.
Edit - I forgot to modify the click function.
$('#table td:first-child').click(function() {
$('div.main').animate({
height:'0px'
}, function(){
//once the animation completes
$.ajax({
url: '/',
type: 'GET', //this is default anyway
data:{name: $(this).data('name')}, //send the name from the td clicked
dataType: 'json', //what we expect back from the server
success: function(data){ //will fire when complete. data is the servers response
if(data.success !== false){
$('div').html(data.html);
$('div.main').animate({
height: "50px"
}, 600);
}else{
alert("Something went wrong");
}
}
});
}, 600);
});

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Jquery load dymanic content with parameter

I'm trying to load div content based on the a href being clicked and pass in a parameter. For example, Link 1
Clicking on Link 1 will pass value "3" to process.php, and return back the value "apple is good for you".
However, I can't seem to be able to pass the value without having a submit button. Anyway I can pass the parameter to another php file to process, and return the value?
$(document).ready(function(){
$("#testing a").live("click", function(evt){
var id= $(this).attr('id');
$.post("process.php", { id: id },
function(data) {
alert(data);
$('#result').load(data);
});
})
});
Below is my HTML
<div id="testing">
hello
</div>
<div id="result"></div>
Appreciate your help, thanks a lot!
You shouldn't be using numbers for id values. Instead, prefix them with a letter, or consider adding them to a data- atribute on the element.
Additionally, $.live() is deprecated, and we are encouraged to use $.on() from here on out for event delegation. I've gone ahead and handled this in the code below, but the id issue remains.
Lastly, $.load() and $.html() aren't the same. If you want to load data into an element, you don't call the load method (though the name could lead to that confusion).
// Short-hand version of $(document).ready();
$(function(){
// Handle anchor clicks on #testing
$("#testing").on("click", "a", function(e){
// Prevent links from sending us away
e.preventDefault();
// POST our anchor ID to process.php, and handle the response
$.post("process.php", { 'id': $(this).attr("id") }, function(data){
// Set the response as the HTML content of #result
$("#result").html(data);
});
});
});
From your process.php file, you might have something like the following:
$msg = array(
"...chirp chirp...",
"This is response number 1",
"And I am the second guy you'll see!",
"Apples are good for you!"
);
$num = $_POST["id"] || 0;
echo $msg[ $num ];

Passing a variable from within a while loop to a jquery

I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );

Categories