Jquery PHP/Mysql image manager - php

I'm working on a CMS at the moment and have been looking for a suitable Jquery/Php image manager but can't find anything that really suits my needs. So I've decided to have a go at building the image manager myself. The bad news is I'm not particularly up to speed with my Jquery...actually I know very little. But I'm working my way through it.
The end result will display an unordered list of images.
<ul>
<li><img src="imgsrc" /></li>
<ul>
When the user clicks on an image the ID of that image is sent to a Jquery function and stored in an array. The image is highlighted with a border added by addclass(). If the user clicks on a subsequent image that image ID is also sent to the Jquery array and the second image is also highlighted.
This continues until the user doesnt click on any further images. Naturally if the user clicks on an image that is already contained in the Jquery array then it is removed and the highlighted effect is also removed.
Following this the user will select a catalogue item from a select menu that sits below the image list. The ID of that item is also passed to Jquery.
When the user clicks submit the Jquery array and select ID are sent to a PHP script that updates a MySQL table, linking the image ID to the catalogue item ID.
Where I'm up to currently is...I have a lovely unordered list of images.
My questions are
How do I send the image id to the jquery array, and subsequently remove that id if the same image is clicked again
How do I send the Jquery array to the PHP script to be executed
I have got some of this working in code snippets at the moment, but as Jquery is far from my forte Im just rinsing and repeating until I get the code right. Any help would be great.
Mark
So Ive been trying this code snippet, but I think i could be written better.
$(document).ready(function() {
$("img").click(function(event) {
var test = (event.target.id);
if($('img[id=' + test + ']').is('.error'))
$('img[id=' + test + ']').removeClass("error");
else
$('img[id=' + test + ']').addClass("error");
});
});
</script>
Surely there's another way to target the img id without having to use 'img[id=' + test + ']'
Mark
Edited again
$(document).ready(function() {
$("img").click(function(event) {
var img_id = (event.target.id);
var imgArray = new Array();
if($('img[id=' + img_id + ']').is('.selected')) {
$('img[id=' + img_id + ']').removeClass("selected");
$('span[id=check_' + img_id + ']').removeClass("check-ok");
removeArray();
}
else {
$('img[id=' + img_id + ']').addClass("selected");
$('span[id=check_' + img_id + ']').addClass("check-ok");
addArray();
}
function removeArray() {
alert('Removing from the array');
}
function addArray() {
alert('Adding into the array');
}
});
});
Trying to figure out how to insert the images into the array, and then remove them from the array.

I'm not really sure what all the bits of your code are doing, but something like this should at least make it a bit more DRY:
function showMessage(selected) {
if( true === selected )
{
alert('Removing from the array');
}
else
{
alert('Adding to the array');
}
}
$(document).ready(function() {
$('img').click(function(event, ui)
{
$(this).toggleClass('selected');
var id = $(this).attr('id');
$('#check_' + id).toggleClass('check-ok');
showMessage( $(this).hasClass('selected') );
});
});
And in jsfiddle (although I replaced img with div for speed).

Related

Dropdown search from database, get images for different model/brand and display it

My problem is to display an image that is associated with the mysql results... Say the result has ID=250 and Name=brand.model, then I want a piece of code to search in a folder for an image with the name id_brand.model.jpg on the server.
Database structure is id, master, name. When user selects Brand + Model from dropdown it should get image from folder (could also get image from database, which one is better nowadays) and images all have unique name's what should be echoed as part name.
(Pictures to help understanding what i mean http://imgur.com/a/7XwVd )
Here's pastebin's to what i have coded yet.
http://pastebin.com/kQF2qP64
Any help is appreciated.
First you need to bind the change event of the select to send the name to a function to search the file, then append the file/s to the DOM:
Javascript (Ajax)
// Every time a category is selected we request the files
$('#category').on('change', function() {
// If we have an element with images loaded, lets delete it
var searchResult = $("#search-result").empty();
// Now we serialize the form data, add an id to the form
var searchBrand = $('#gender').find('option:selected').text();
var searchModel = $('#category').find('option:selected').text();
var fileName = searchBrand + '.' + searchModel + '.jpg';
var searchData = { filename: fileName }
// Now we create the ajax request with the form data
var request = $.getJSON('search_images.php', searchData);
// If the request success we show the images
request.done(function(data) {
// For each image found we add a new image to the DOM
$.each(data, function(index, image_uri) {
// First let's create the image element
var img = $("<img>", {
"class": "result-image",
"src": image_uri
});
// Then we append it to the DOM
searchResult.append( img );
});
});
// If the search fails, we notify that no results were found
request.fails(function() {
alert('No results found');
});
});
PHP (search_images.php)
<?
// Get the file name
$filename = $_GET['filename'];
// Find all the images
$images = glob("images/file/path/*_{$filename}");
// Return the images as json
echo json_encode($images);

Jquery / Ajax used on PHP page in a for loop

I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/

jqGrid Custom Edit Dialog

I am working to an application that uses jqGrid. The problem is that the edit dialog that should appear at row edit must have a specific layout. So I would prefer to load it via ajax and then send the data back to jqGrid manually. I searched a lot on the forums but I could not find an example of how to do it.
So, I just need jqGrid to fill the edit dialog pop-up with custom content from a PHP script.
UPDATE: THe idea is that I have a form generator, where the user sets the position/width/heigh/visibility of the edit fields... and this must be used in the edit dialog.
You can use editfunc or addfunc option of the navGrid. If for example editfunc are defined then instead of editGridRow jqGrid will be called editfunc with the id of selected row as the parameter.
Alternative you can use custom button (see this answer as an example).
To modify data in the table after ther custom edit dialog you can use setRowData function.
UPDATED: If you need just make some modification of layout of the edit dialog you can use beforeShowForm for th modifications.
You can check this Tutorial, which is the official demo website of jqGrid Plugin. I am sure that there are examples of some "Row Editing" in that category. You can view lots of other examples of jqGrid also, in this demo website.
You can also check the Home page.
If you have any more problems, you can ask it here. I did use some of those examples in one of my client's (confidential) website, so it will be easy to manipulate according to your needs.
Hope it helps.
My edit dialog had too many fields and so became too high, so I had to put the fields side by side in 2 columns. I did it as follows:
I tried various ways, using wrap(), etc, but found that the values are not posted to the server if you modify the original table structure. So I just cloned the tr elements, put them in new tables, and hid the old ones. I did not hide the whole table, so that the validation will still be visible. I put an onchange on the cloned elements to update the old ones. This works great. Parameter tableName is your jqgrid element id.
var splitFormatted = false;
function SplitFormatForm(tableName, add) {
if (!splitFormatted) {
splitFormatted = true;
$("#FrmGrid_" + tableName).append('<table><tr><td><table id="TblGrid_' + tableName + '_A" class="EditTable" border="0" cellSpacing="0" cellPadding="0" /></td><td><table id="TblGrid_' + tableName + '_B" class="EditTable" border="0" cellSpacing="0" cellPadding="0" /></td></tr></table>');
var cc = $("#TblGrid_" + tableName + "> tbody").children("tr").length;
var s = (cc / 2) - 1;
var x = $("#TblGrid_" + tableName + "> tbody").children("tr");
var i = 0;
x.each(function (index) {
var e = $(this).clone();
var oldID = e.attr("id") + "";
var newID = oldID;
if (oldID.substring(0, 3) === "tr_") {
newID = "clone_" + oldID;
$(this).css("display", "none");
e.change(function () { $("#" + oldID + " > .DataTD > .FormElement").val($("#" + newID + " > .DataTD > .FormElement").val()); });
e.attr("id", newID);
if (i++ < s) {
$("#TblGrid_" + tableName + "_A").append(e);
}
else {
$("#TblGrid_" + tableName + "_B").append(e);
}
}
});
//This hack makes the popup work the first time too
$(".ui-icon-closethick").trigger('click');
var sel_id = "'new'";
if (!add) {
sel_id = jQuery('#'+tableName).jqGrid('getGridParam', 'selrow');
}
jQuery('#'+tableName).jqGrid('editGridRow', sel_id, { closeAfterAdd: true, width: 800, afterSubmit: function (response, postdata) { return [response.responseText == 'OK', response.responseText]; } });
}}
Call this code in your editOptions as follows:
afterShowForm: function () { SplitFormatForm("SiteAccountsGrid", false); }

Printing results from function on page onclick?

Honestly, I'm not even sure the best way to go about this, but essentially, I have a function in an include file that takes a $type parameter and then will retrieve/print results from my db based on the $type passed into it... What I'm trying to do is have a series of links on a page that, when you click on a certain link, will run the function and display the results accordingly...
So, on the initial load of the page, there is a table that displays everything (and I'm simplifying the table greatly...)
<table>
<tr><th>Item</th><th>Type</th></tr>
<tr><td>Milk</td><td>Dairy</td></tr>
<tr><td>Yogurt</td><td>Dairy</td></tr>
<tr><td>Chicken</td><td>Meat</td></tr>
<tr><td>Zucchini</td><td>Vegetable</td></tr>
<tr><td>Cucumber</td><td>Vegetable</td></tr>
</table>
And, then, in a sidebar, I have a series of links:
Dairy
Meat
Vegetable
I'd like to filter the initial table (and back and forth, etc.) based on the link that is clicked, so that if the user clicks "Vegetable", the function from my include file will run and filter the table to show only "Vegetable" types...
The first idea that comes to mind is to add a class attribute to the <tr> tags and id attribs to the <a> tags so that you can easily filter that way:
<tr class="dairy"><td>Milk</td><td>Dairy</td></tr>
<tr class="meat"><td>Chicken</td><td>Meat</td></tr>
Dairy
Meat
Then in your JavaScript (I'm using jQuery here):
$('a').click(function(evt){
var myId = $(this).attr('id');
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
This has the added benefit of allowing you to localize the text without having to change your code.
Ok I created a proper answer. You can do it the way Darrel proposed it. This is just an extension for the paging thing to avoid cookies:
$('a').click(function(evt){
var myId = $(this).attr('id');
// append a idndicator to the current url
var location = "" + document.location + "";
location = location.split('#',1);
document.location = location + '#' + $(this).attr('id');
//append to next and previous links
$('#nextlink').attr({
'href': $('#nextlink').attr('href') + '#' + $(this).attr('id')
});
$('#previouslink').attr({
'href': $('#previouslink').attr('href') + '#' + $(this).attr('id')
});
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
Some code that is executed after page load:
var filter = window.location.hash ? '[id=' + window.location.hash.substring(1, window.location.hash.length) + ']' : false;
if(filter)
$('a').filter(filter).click();
This simulates/executes a click on page load on the link with the specific id.
But in general, if you have a large database, you should filter it directly with SQL in the backend. This would make the displayed table more consistent. For example if page 1 may only have 3 rows of class 'dairy' and on page 2 10 of class 'dairy'.
If youre printing out the whole tabel up front there is no need to go back to the server you can simple hide all teh rows of a given type. For example with jQuery:
$('#sidebar a').click(function(){
// grab the text content of the a tag conver to lowercase
var type = $(this).text().toLowerCase();
/* filter all the td's in the table looking for our specified type then hid the
* row that they are in
*/
$('#my_data_table td').contents().filter(function(){
return this.nodeType == 3 && this.toLowerCase() == type;
}).parent('tr').hide();
return false;
});
Really though the suggestion abotu adding a class to the TR is better because filtering on text content can get tricky if there is content youre not expecting for some reason (hence my conversion to all lower case to help with this).

Move divtag and store position in mysql?

I want users on my website to be able to "move" div tags once they are 'unlocked' and then for a php script to store the positions in mysql database. So once the user re-logs in the div tags are positioned in the correct place.
I know how to postion div tags in css, and am using php varibles within css to pull the data from the database. I just dont know how to get the position of the div tag in order to store it? Maybe using ajax or something?
any ideas welcome, thanks.
What do you mean by position? Is it "left, right, center..." or the position in pixels?
If it's in pixels, just use the top and bottom css property. If it's a custom position, just do a callback when you change the position.
You can easily get the position using javascript and once you have it you want to save that asynchronously, so yeah ajax is nice. Look up jquery for that one: http://docs.jquery.com/Ajax/jQuery.post
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
Also, from the way your formulated your question it looks that you don't have a lot experience with ajax. I suggest you look up some documentation online or find a nice book (search SO, there's a bunch of topics about this)
When the position of an element changes, you will want to post the pixel values to a PHP script using AJAX. Here is a brief example using jQuery...
function storeElementPosition(elem) {
var off = $(elem).offset();
$.post("storeElementPosition.php",
{ elem : $(elem).attr("id"), left : off.left, top : off.top },
function(resp) {
alert(resp);
}
);
}
Use jQuery, it'll make life a whole lot easier. ..
HTML:
Save
JavaScript:
$('#savelayout').click(function(){
var postData = {};
$('.xy').each(function(){
var id = $(this).attr('id');
var pos = $(this).position();
if (id && id.length){
postData[$(this).attr('id')] = pos.left.toString() + ',' + pos.top.toString();
}
});
$.post('savelayout.php', postData, function(data, textStatus){
if(textStatus == 'success'){
alert('Positions saved successfully.');
}
});
});
Replace .xy in $('.xy') with the CSS selector that will target all the elements you want saved. Once you do that, if you have two savable elements with with "divid1" and "divid2" id's, the data posted to PHP ($_POST) will look like this:
array(
'divid1' => '123,351',
'divid2' => '512,136'
);
You can then explode each string by the comma and grab each int as the x and y coordinate.

Categories