ajax form like structure - php

I will make this as short and descriptive as possible (considering my case is way longer).
Lets say I have 2 database tables with the following structures:
User table:
id ---- username---- gold
Items table:
id----- item_name---- item_price
What I am trying to achieve is brainstorming, I tried this with over 20 script combinations. I need to be able to echo out all items in the table to a good layout (done)
Have a text box for the user to type in the value required to be bought.
an a href to submit the amount, deduct the price of the item from the amount of gold the user has, then add 1 to the inventory. I am not requiring php code, as it is easy. All I need is help with trying to update the value typed in "Live". The layout of the "shop" will look something like this:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input type = 'text' name = 'to_buy_value'/>
<a href = 'javascript:;' class = 'buy'>Buy</a>
}
I hope the above code gives you enough reference.
TL;DR (after db structure?)
1- A text box with an a href as the submit.
2- table update is done on-the-fly (no reloads). Ajax.
3- Be able to buy more than 1 item at a time without page reloads
4-no help with php code required unless necessary.
I'd appreciate any sort of help.

Here's a very rough solution for you. In your while loop you could attach the item's database id to the id of the element:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input id="purchaseAmount{$_row->id}" type="text" name="value_to_buy" />
<a id="purchaseButton{$_row->id}" href="#" class="buy">Buy</a>
}
Then bind a javascript function to your "Buy" link which will make an AJAX request:
$('.buy').bind('click', function() {
// Grab the item id and amount
var itemId = $(this).attr('id').substring(14);
var itemAmount = $('purchaseAmount' + itemId).val();
$.ajax({
url: 'someurl/purchaseItem.php',
data: { item: itemId, amount: itemAmount },
success: function(data) {
// Update the player's gold and inventory on screen
}
});
});
The "purchaseItem.php" file could return a simple JSON object that holds the player's current gold and item amount for the inventory. Or you could return HTML, depending on how your page is setup.

Some time ago, I had project in which I had to do sort of a CMS just for news management, add, edit, delete, etc. As Satya commented, the way is with AJAX if you want to do it nicely.
What I did was a loop, just like yours, for each row fetched with PHP mysql_fetch_assoc add a tr in a table (yeah, I know, tables...). I know that you didn't wanted PHP help, but I think this will help you.
$res=mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
foreach ($row as $col => $val) {
if ($col != "column you dont display or isn't 'ID' column" && $col != "another column you dont display, and so on") {
if ($col == "ID") $id = $val;
//use this to echo values in table/tr/td/div/span or whatever you use to display values
if ($col == "gold") {
echo 'whatever you want to echo using the gold value';
}
if ($col == "name of last column you are displaying") {
echo 'whatever you display for that column';
echo '<input type="text" value="Introduce quantity">';
//If you are on HTML5 you could just use id="{$id}" as it will be easier
echo '<a href="#" class="buy" id="i_{$id}" value="Introduce quantity">';
}
}
}
One of the most important things here is to keep track of the ID of each item, this way you can relate them when sending the POST request to the server.
I recommend you to use jQuery for that matter, it's very easy to use
<script type="text/javascript">
$(document).ready(function () {
$(".buy").click(function(e) {
e.preventDefault();
// You get the id attribute of the button clicked, which contains the
// item ID. Then you substr the string to get just the id number. Example:
// The id of the clicked element is "i_2254" you use substr to get just the
// 2254 and send it to the php that process the buy
// If you choose the HTML5 id form I said above in the PHP, then var id=$(this).attr("id")
var id = $(this).attr("id").substr(2);
$.ajax({
type: "POST",
url: "buy_item.php",
async:false,
data: "itemID="+id,
success: function(data) {
// Here is where the magic occurs, this is what happens when you
// get the response, here is where you update the
// inventory, quantity, etc WITHOUT reloading.
// The variable data is the response of the server
// you just echo what you need on buy_item.php, and
// that will be data here
// A simple example is to change the value of an input
// with id="gold", you echo gold on php and...
$('#gold').val(data);
}
});
});
});
});
</script>
In the buy_item.php is where you UPDATE the gold values of the table, and add the item to the item table. Use $_SESSION variable to store user session name and update the gold and items of that user.
I suggest you to investigate about AJAX and jQuery(optional), it would help a lot!
I think basically this will solve your problem, and I hope for an invitation for the game :P

Related

Display Table with AJAX, select row, display row in other table, save into database

I have been given very specific instructions on how to do a certain feature.
On the website Im working on you can create events and edit those. Those events can have guests, which are different from normal members that attend an event.
Every guest has to be invited by a member. So I have a table displaying members and in that very Table I have a picture. When you click on said picture it will display a list of guests, that arent part of the event yet.
All of this already works, but now comes the part that I am unable to do.
Now the admin needs to be able to select a guest. After a row is clicked it must be taken out of the table and displayed in a seperate HTML Table, in case multiple guests can be chosen.
After that the admin needs to press a submit button, to invite the guest to the event.
Now my explicit questions are:
How can I make my row selectable? I found this but I get the error TypeError: $(...).selectable is not a function if I try to use it. Edit: I have also since found this. When I use this I dont have any errors in my console, but it still does not work. Could it be that it doesnt recognize my table?
How can I display the row in a seperate HTML Table? With $("#row").click(function() maybe?
I tried doing enough research, to warrant asking such a specific question, so please refrain from saying "just google it". Instead I would be thankful for linking me to the right source! I dont want somebody to do it for me, Id just be thankful for any help! :) I am still very new to jQuery and AJAX.
Here is my jQuery for displaying the table, for context:
$(document).ready(function(){
$("#show_guests").click(function(){
event.preventDefault();
$.ajax({
url: '/widenmoos/administrator/components/com_memberportal/anlassansicht/Gast_Liste.php',
success: function(data,status)
{
createTableByForLoop(data);
},
async: true,
dataType: 'json'
});
});
});
function createTableByForLoop(data)
{
var eTable='<table id="Selectable_Guest_Table"><tr><th>Guest</th>'
for(var i=0; i<data.length;i++)
{
eTable += "<tr>";
eTable += "<td>"+data[i][0]+ " " +data[i][1] + ", " +data[i][2]+"</td>";
eTable += "</tr>";
}
eTable +="</table>";
$('#forTable').html(eTable);
}
Try with the following code:
I'm dynamically creating a new table to contain the selected guests. You can then use the same way I'm storing each rows' guest attributes to move parameters and use them whenever you need to send the emails.
function createTableByForLoop(data)
{
var eTable= $("<table />").attr("id","Selectable_Guest_Table").append(
$("<tr />").append(
$("<th />").html("Guest")
)
);
for(var i=0; i<data.length;i++)
{
eTable.append(
// you can store whatever data comes from the js object in this way:
// (in case you can stringify the entire object and store it as row attribute)
$("<tr />").attr("data0",data[i][0]).attr("data1",data[i][1]).attr("data2",data[i][2]).append(
$("<td />").html(data[i][0]+ " " +data[i][1] + ", " +data[i][2])
).click(function()
{
var data0 = $(this).attr("data0");
var data1 = $(this).attr("data1");
var data2 = $(this).attr("data2");
$("#selected_guests").append(
$("<tr />").append(
$("<td />").html(data0+" "+data1+" "+data2)
)
);
// Remove row from original table
$(this).remove();
})
);
}
var selectedGuestsTable = $("<table />").attr("id","selected_guests").append(
$("<tr />").append(
$("<th />").html("Selected Guest")
)
);
$('#forTable').append(
eTable,
selectedGuestsTable
);
}
The best way, by the way, is to pass only the guest id on both tables rows, referring then the entire object from the data array when needed.

Hot to get all the images to display without reloading the page in PHP?

After User Clicks Sumbit Button Data passes through one half of the path to images and then the code below links it to the second half. I want to know how I can display all this without Page Reload? I know it might be done with AJAX but I have no idea on how to do so. So please can someone help?
<?php
$albumnamepath = $_POST['field'];
echo $albumnamepath;
$display = "SELECT * FROM paths WHERE user_id = '$session_user_id' AND album_name = '$albumnamepath'";
$result = mysql_query($display);
echo "<table>";
$i = 0;
while ( $row = mysql_fetch_array($result) ) {
if ($i % 4 == 0) { //3 == 0.
echo '<tr>';
}
echo "<td>".'
<ul class="img-list">
<li><div class="picbox"><img src="'.$albumnamepath.$row['thumbnail'].'"><span class="text-content"><span>'.$row['caption'].'</span></span>'."</li>
</ul>
</td>";
//echo '<a href="'.$albumnamepath.$row['location'].'" class="swipebox" title="'.$row['caption'].'"><img src="'.$albumnamepath.$row['thumbnail'].'">';
if ($i % 4 == 3) { //3 == 2.
echo '</tr>';
}
$i++;
}
//Here is a check in case there is not a multiple of 3 images in a row.
if ($i % 4 != 0) { //4 != 0.
echo '</tr>';
}
echo "</table>";
?>
Thank you.
I don't think Ajax would help you very much, since you'll be using ajax to get, essentially, the entire page. Ajax is usually used if you want to change a part of the page, and the data either has to come from the server real-time (i.e. after the page is loaded), or is expensive to calculate or deliver in full (e.g. a very long, or infinite list, and if most users only use a small amount). Otherwise, it's more efficient to send all the data in one go, and then manipulate it in the browser.
I would suggest the following approach: divide the table rows into groups of table rows; e.g. 5 rows (chosen arbitrarily). Change the block of code where you echo '' to:
if ($i % 4 == 0) { //3 == 0.
$block=ceil($i/(4*5));
echo '<tr class="block_$block">';
}
This means each block of 5 rows (by 4 across) will be a different class - "block_1", "block_2" and so forth.
Then, you can hide and display blocks using Javascript. To hide a block, use the following javascript code:
var trToHide = document.getElementsByClassName("block_1");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="none";
}
To unhide a block:
var trToHide = document.getElementsByClassName("block_3");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="block";
}
Obviously, you will want to use variables to keep track of which block is displayed; then you can have a "Next" and "Back" button, which hides the current block, adds/subtracts one, then displays the (new) current block. You will also want to have all blocks except the first one hidden at the start. Left as an exercise to the reader.
Answer:
You have to use ajax request.
You use form to set filters? Then you can use .ajaxSumbit (but you need jQuery Form Plugin for it).
Also, you can add form submit handler, where you will prevent form default submit action and send ajax request instead of it. Look this example:
File getImages.php:
// in this file you will do same actions as you do now to output table with images
Note, that getImages.php must contain only table with results or message, that there are no results.
File with form, where you set filters:
// some html with forms etc
<form id='myForm'>
// some inputs etc
</form>
<div id='results'></div>
And javascript:
$("#myForm").submit(function(e) { // use e parameter for preventDefault();
$.ajax({
type: "POST",
url: "path/to/getImages.php",
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#results").html(data);
}
});
return false; // <-- deny sumitting from and reloading page
//e.preventDefault(); // <-- this do same as `return false;` <-- deny sumitting from and reloading page
});
Explanation:
Browser load page with form, where you can set filters. User sets filters and pressing button submit. Browser will send ajax request to file getImages.php with some parameters (filters, user set filter before sending the form). This script generates some output with table, with img tags etc and return it. Browser receives this output and puts it to element with id #results:
<div id='results'></div>
^
------------------^
Data, generated by script getImages.php will be inserted here.
So, filtered images will be received and shown without page reload :)
Is it what you need?
Hope this will help you.

Cannot Modify/Manipulate Dynamic Content From Ajax/JSON Response for A Dynamic PHP Form

I need a dynamic form which is supposed to work like this:
When user press "ADD" button, appear a new ..<.div> DOM to select a package.
Depending on the package, the row must change color (by adding/removing some classes).
But I can't get it working. Here is my HTML:
<button onclick='addDay();'>
<div class='content'>
</div>
My Javascript:
//FUNCTION 1: LOAD AJAX CONTENT
function addDay()
{
baseUrl = $('input#helper-base-url').val();
//Set caching to false
$.ajaxSetup ({
cache: true
});
//Set loading image and input, show loading bar
var ajaxLoad = "<div class='loading'><img src='"+baseUrl+"assets/images/loading.gif' alt='Loading...' /></div>";
var jsonUrl = baseUrl+"car/add_day/"+count;
$("div#loading").html(ajaxLoad);
$("div#content").hide();
$.getJSON(
jsonUrl,
{},
function(json)
{
temp = "";
if(json.success==true)
{
temp = json.content;
}
//Display the result
$("div#content").show();
$("div#content").html($("div#content").html()+temp);
$("div#loading").hide();
});
}
//FUNCTION 2: MODIFY AJAX CONTENT
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
});
My PHP
function add_day($count)
{
$temp = "<div class='row".$count."'>
<select id='switch".$count."' class='switch'>
<option value='1'>Package 1</option>
<option value='2'>Package 2</option>
</select>
</div>";
$result = array(
'success' => true,
'content' => $temp,
);
$json = json_encode($result);
echo $json;
}
PS. The form is not as simple as this but to make the problem solving easier, I remove the details. But I can't seem to change the class on the fly. Do we have a solution or a good work around here?
Edit 1:
Sorry I didn't make myself clear before. I had no problem with getting the id or variable (it was okay, when I alert it the right value comes out - but after I add the class, no color changes is seen). I run it:
a. On button click, load Ajax content.
b. Ajax content (which results contains a ) loaded successfully.
c. FAIL: On change, add class "package1" to the div row. (So, I had no problem with getting the right id or class name. When I alert the variables it gives the right result, BUT the color doesn't change. I can't check whether class is successfully added or not.)
$("#content").on("change", "select.switch", function (e) {
e.preventDefault();
$('.row' + $(this).attr('id').replace('switch', '')).addClass('package1');
});
Assuming that everything else is ok
//Get which row is to be changed in background's color
id = this.id;
id = id.substr(6);
//Add class "package1" which change row's background color
row = "row"+id;
row.addClass('package1');
This is the problem. To get the attibute id you have to do
var id = $(this).attr('id').substr(6);
You have to use $(this) and not this by the way to use all of jQuery functionalities.
Same below
$(row).addClass('package1');
So, full code:
//Get which row is to be changed in background's color
var id = $(this).attr('id').substr(6);
//Add class "package1" which change row's background color
$('.row'+id).addClass('package1');
Changing the class to id solved the problem (using #row0 instead of .row0). Sorry and thank you for your time :)

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

Update value in MySQL from PHP using Ajax, change image

I've searched the database but haven't really found anything that would answer my question. I'm new with Ajax so I'll try to describe it as good as I can.
I am trying to build a rating system for images with only two options: Accept/Reject.
I have a paginated gallery with 10k images and they all need to be rated (for the competition). There's a special system for rating (accepting/rejecting) and then there's this overview gallery. Every thumbnail that has already been rated should display a clickable text/image, for example "Accepted", depending on the database value. You'd be then able to click on this text/image and it would change to "Rejected" and the mysql database entry would also change at the same time.
Left: initial state of the "Accepted" image. /
Right: changed value of the button (text or image) and updated database.
(source: shrani.si)
So what would be the easiest way to do this? There are hundred images on each paginated site with these buttons below, and you have to be able to change the value back and forth (many times, something like editable star rating system with only two stars, heh).
As you said ajax should be used and I advice you to use jquery functions
Then viewing the images should be simple for you when you loop through the database result
while looping you should test the value of the image is it accpted or rejected in order to link it with the associate JS function that I will talk about later and in that function an ajax request should be made to update that row
function change_status_image(id,status,clicked)
{
$.post("update.php",{image_id:id,image_status:status},function(data){
//your callback to do something like update the value of the button
});
}
This will make an ajax request and sends two variables image_id and image_status in the update.php you should use something like this
$q = mysql_query("UPDATE tbl_name SET column_name = '".mysql_real_escape_string($_POST['image_status'])."' WHERE image_id = '".mysql_real_escape_string($_POST['image_id'])."' ";
about the function make a div or button and link the onclick att to change_status_image
for example
<img onclick="change_status_image(img_id,reverse_current_status)" >
Use jQuery. You need two scripts:
/rate.php
/rate.js
rate.php looks like this:
<?php
// If there are values in $_POST['edits'], then this is an ajax call.
// Otherwise just display the gallery
if ((!empty($_POST['edits']) && (count($_POST['edits']))) {
foreach ($_POST['edits'] as $edit) {
alter_image($edit); // some function to update the database
}
echo "success";
exit;
}
$images = get_images(); // Some function to get the images from the database
?>
<?php foreach ($images as $image): ?>
<div class="gallery-image">
<img src="<?php print $image -> src ?>" />
<button>Accept</button>
<button>Reject</button>
<input name="id" value="<?php print $image -> id ?>"/>
</div>
<?php endforeach; ?>
rate.js looks like this:
$(function() {
// attach click event handler to buttons
$('.gallery-image').on('click', 'button', function() {
var $this = $(this),
ajaxSettings = {
url: '',
type: 'post',
data: {
edits: [
{
id: $this.parent().find('input[name=id]').val(),
action: $this.html()
}
]
},
success: function(response) {
if (response === 'success') {
// something to indicate success
} else {
// something to indicate error
}
}
}
$.ajax(ajaxSettings);
})
})

Categories