I don't know if I've even asked the question properly, but I have a codeigniter application that some heaving lifting in the back end. While the app is busy executing commands(ajax commands), I'd like to show some sort of a status / message box / div. When the task is done, I'd like to clear the div / box.
What would I need to google to find a solution like this?
Thanks.
Edit:
This is what my jquery / ajax call looks like right now...
$('#availVLANS').click(function() {
$(this).attr("disabled","disabled");
$.ajax({
url:"<?php echo site_url('controller/methodABC/');?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
//alert(returnDataFromController[i].VlanId);
htmlstring = htmlstring + "<tr><td><a href=>"+returnDataFromController[i].VlanId+"</a></td><td>"+ returnDataFromController[i].Name+"</td></tr>";
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='" + BASEPATH + "index.php/switches/changeportvlan/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' name='newVlanID' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' name='saveVlan' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
}
});
$(this).removeAttr("disabled");
});
Just use an animated GIF image in an absolutely positioned DIV overlayed on top of the whole page. Just make sure that you overlay an invisible DIV over top of the entire page to prevent clicks on interface elements behind the progress window. Something like this;
╔════════════════════╗
║ #progress-overlay ║
║ ╔════════════════╗ ║
║ ║ #progress-indicator
║ ╚════════════════╝ ║
╚════════════════════╝
The #progress-overlay is a background for the indicator and what you're going for is like a LightBox2 effect but using a progress indicator and small box in the middle of the screen.
You can get animated gif's from here;
http://preloaders.net/
Make sure that your progress/something-is-happening div sits at the top level of the document structure, so somewhere at the top of the body, before any of your other container DIV's. This is done so that the #progress-overlay is rendered at the same level in the DOM as the top level element of your website. When you absolutely position the #progress-overlay, it will appear overtop of everything else on the page.
<html>
<head>
....
</head>
<body>
<div id="progress-overlay">
<div id="progress-indicator">
<img src="images/myprogress.gif" /> Please Wait...
</div>
</div><!--progress-overlay-->
<div id="website-wrapper">
.... web site, layout, content, etc...
</div>
</body>
</html>
The #progress-overlay is hidden by default and then shown overtop when needed. Something like;
#progress-overlay{
position: absolute;
width: 100%;
height: 100%;
background: #000;
opacity: 0.2;
}
#progress-indicator{
position: relative;
margin: 0 auto;
top: 40%;
width: 200px;
height: 50px;
}
Using JQuery you could easily make this appear on demand using;
$(document).ready(function(){
$('#progress-overlay').hide();
});
function showProgressIndicator()
{
$('#progress-overlay').show();
}
You can make use of onreadystatechange event:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
If you're doing it through jquery, just show a div with a message and/or a spinner.
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
}
});
If you're using jQuery, I propose the following solution:
The jQuery:
$(document).ready(function(){
$("#the_button").click(function(){
var url = "the_controller/the_method"
var data = {the: "data"}
//before the POST takes place, fade-in the message
$("#the_message").fadeIn();
$.post(url, data, function(r){
if(r.success){
//when the post is finished, and it was successful, fade-out the message.
$("#the_message").fadeOut();
}
else console.log("something bad happened");
}, 'json');
});
});
The HTML:
<!-- HIDE IT BY DEFAULT -->
<div id='the_message' style='display:none;'>
Please wait.
</div>
The Controller:
class The_controller extends CI_Controller{
function the_method(){
$p = $this->input->post();
the_task($p);
if(the_task_success) return json_encode(array("success" => true));
else return json_encode(array("success" => false));
}
}
Related
I was trying to parse data to my controller so I can insert it into the database using JQuery and it was returning null. It's for a review star system so doesn't use conventional form fields however the network tab in inspect elements shows that data is actually posted to the controller just, not able to read it for some weird reason.
Update: The data is being inserted fine on desktop however the confirmation (flashdata) message is shown correctly not sure why. Additionally on mobile view no data or message is shown. Does anyone know why? I have updated the code below..
Here's the code from my view:
<?php if($this->session->flashdata('review_submitted')){ ?>
<div class="alert alert-success alert-dismissible container show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Thank you!</strong> Your review has been submitted.
</div>
<?php } ?>
<form id="myForm" name="myForm">
<br>
<div class="form-group text-left div-style">
<h3 style="font-family: MontserratLight;letter-spacing: 2px; line-height: 32px;">Full Name <b>*</b></h3>
<input name="name" class="form-control" style="background: #f7f7f7; border: 1px solid #801424;" required />
</div>
<div class="rate">
<div id="1" class="btn-1 rate-btn"></div>
<div id="2" class="btn-2 rate-btn"></div>
<div id="3" class="btn-3 rate-btn"></div>
<div id="4" class="btn-4 rate-btn"></div>
<div id="5" class="btn-5 rate-btn"></div>
</div>
<script>
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-active');
};
$('#myForm').on('submit', function(e){
var url = "<?php echo base_url(); ?>index.php/reviews/add_review";
// $('#myForm').append(therate);
var dataPost = $('#myForm').serialize() + "&rate=" + therate;
$.ajax({
type : "POST",
url : url,
data: dataPost,
success:function(){
}
});
});
});
});
</script>
and using the controller I simply use the following to get the data and add it to the database:
public function add_review(){
$name = $this->input->post('name');
$rating = $this->input->post('rate');
$dataDB = array(
'full_name' => $name,
'rating' => $rating
);
if($this->functions->submit($dataDB)){
$this->session->set_flashdata('review_submitted', true);
redirect(base_url() . 'reviews/index', 'refresh');
}
}
Here's some CSS that I used, perhaps the problem is to do with the mobile browser not having a cursor?
.rate{
width:245px; height: 40px;
margin-bottom:0px;
}
.rate .rate-btn{
width: 45px; height:40px;
float: left;
background: url(rate-btn.png) no-repeat;
cursor: pointer;
cursor:hand;
pointer-events: auto;
}
.rate .rate-btn:hover, .rate .rate-btn-hover, .rate .rate-btn-active{
background: url(rate-btn-hover.png) no-repeat;
}
When passing data through ajax, I think it is better to use JSON dataType. Reform the data type (string -> data object). Besides, I don't think it is really necessary to concat the 'to-be-sent' data into a string.
If you want dynamic data to be sent, you can push elements by condition
$.ajax({
type : "POST",
dataType: 'text' //it is not necessary if you are not returning any data (if you return json, put 'JSON'),
url : "<?php echo base_url(); ?>index.php/reviews/add_review",
data: dataRate, //change to {key:value,key:value}
success:function(data){
}
});
This is just to address your issue with your AJAX Posted Values not appearing where you are expecting them ONLY.
There are a zillion ways you can code this but here is just one which I have changed about to perform debugging. Even I learned a new trick doing this.
Just Nit Picking but what stuck out when reading your code is your use of therate when everywhere else in your JS you use camel case so it should be theRate.It's a good idea to choose a standard and stick to it.
Plus you had what appeared to be nested events in your JS. Some attempt at getting theRate to work correctly? Anyway...
First things. Get back to something basic and work your way back up. (Although in this case I didn't strip your view back to bare bones, but I did with your controller.
Your View.
I had to change this up a bit and hopefully the comments explain things.
I called it rating_view.php
<form name="my-form" id="my-form">
<div class="rate">
<div id="1" class="btn-1 rate-btn">1</div>
<div id="2" class="btn-2 rate-btn">2</div>
<div id="3" class="btn-3 rate-btn">3</div>
<div id="4" class="btn-4 rate-btn">4</div>
<div id="5" class="btn-5 rate-btn">5</div>
</div>
<input type="submit">
</form>
<!-- Added for viewing debug response -->
<div id="json-debug-output"></div>
<!-- Some styles added as non were provided -->
<style>
.rate-btn-hover {
background: blue;
}
.rate-btn-active {
background: yellow;
}
</style>
<script src= <?= base_url('assets/js/jquery_v3.4.1.js'); ?>></script>
<script>
$(document).ready(function () {
// Define your Dom Elements ONCE for efficiency etc
let domRateButton = $('.rate-btn');
let domMyForm = $('#my-form');
let theRate = 0; // Declares this as a Global Var.
let domJsonDebugOutput = $('#json-debug-output');
// Hover
domRateButton.hover(function () {
domRateButton.removeClass('rate-btn-hover');
let theRate = $(this).attr('id');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-hover');
}
});
// Click
domRateButton.click(function () {
console.log('Rating Button Clicked');
theRate = $(this).attr('id');
domRateButton.removeClass('rate-btn-active');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-active');
}
});
// Submit
domMyForm.on('submit', function (e) {
e.preventDefault(); // This was missing
console.log('Posting Rate = ' + theRate);
$.ajax({
type: "POST",
// dataType: 'text',
dataType: "json",
url: "<?php echo base_url(); ?>reviews/add_review",
data: {'act': 'rate', 'post_id':<?= $post_id; ?>, 'rate': theRate},
success: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
},
error: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
}
});
});
});
</script>
Note in the AJAX the changes to dataType from text to json. Also note that data is an array.
I also changed the scope of theRate from local to a global so it was "findable" amongst the functions.
NOT SURE how your form was setup but I added e.preventDefault(); to prevent the form submitting for testing.
Personally I cringe at having PHP vars embedded in any JS code and I usually have my JS as external files and pass in the values from PHP by reading them using JS but that's got it's Pros and Cons as well. So I left that alone for the sake of not going too far with this.
For your Controller - Called Reviews.php
public function show() {
$data['post_id'] = 1; // This comes from somewhere
$content = $this->load->view('rating_view', $data, TRUE);
echo $content;
}
/**
* Called by AJAX
* Do we need to test this is only called by AJAX?
*/
public function add_review() {
// Return everything that was sent for debugging
echo json_encode($this->input->post());
// var_dump($this->input->post());
exit();
}
So here I just had a method show() show the form and the add_review to simply bounce back what was sent. You can do all sorts of things with this. One nice aspect in this case is you do not need to use console.log) as you can view it all on the page (BUT ONLY FOR DEBUGGING). It's another option.
So have a play with that and start making changes to your code and see what works. Remember - get back to basics and pick on the bit that isn't working.
Next you will find you might be getting tripped up on your redirect. But that's for another post.
I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.
There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven't found any that will help with using a While loop in php.
I have a database of "needs" and I want to display all the "needs" that match the persons username and status=inprogress. This could be 1 need or 1,000,000 needs depending on if the criteria is met.
I want to save the position of the need (DIV) automatically when it's moved. Is this possible? I wanted to store the values in a database using SQL if I can.
Here the code I currently have that displays the "needs" (divs)
Header
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
#set { clear:both; float:left; width: 368px; height: 120px; }
p { clear:both; margin:0; padding:1em 0; }
</style>
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div"
});
});
</script>
Body
<div id="set">
<?
$query = mysql_query("SELECT * FROM needs WHERE (needsusername='$username' OR workerusername='$username') AND status='inprogress'");
while ($rows = mysql_fetch_assoc($query)) {
$title = $rows['titleofneed'];
$status = $rows['status'];
echo "
<div class='ui-widget-content'>
$title<br>Status: $status<br>
</div>
";
}
?>
</div>
Insert Query
$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$needid=$_POST["need_id"];
//Setup our Query
$sql = "UPDATE coords SET x_pos=$x_coord, y_pos=$y_coord WHERE needid = '$needid'";
//Execute our Query
if (mysql_query($sql)) {
echo "success $x_coord $y_coord $needid";
}
else {
die("Error updating Coords :".mysql_error());
}
You can use the stop event of draggable to get noticed when an element has reached a new position. Then you just have to get the offset as described in the docs.
Assuming you have a setup like that:
<div id="set">
<div data-need="1"></div>
<div data-need="2"></div>
<div data-need="3"></div>
<div data-need="4"></div>
<div data-need="5"></div>
</div>
I've used a data attribute to store the id of the "need", you can later on use that id to store the position of the "need" in the database.
Now as mentioned before, use the stop event to send an ajax call to the server with the id of the need and the x and y postion of it. Be aware hat this is the position of the screen so if you have different screen sizes you should probably use positions relative to a parent container with a desired position.
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
stop: function(event, ui) {
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var need = ui.helper.data("need");
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { x: pos_x, y: pos_y, need_id: need}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
This way every time a draggable element reaches a new positions e request will be sent to your_php_script.php. In that script you then only have to grab the post parameters and store them in the database.
There is a working fiddle, of course the ajax request is not working but you can see whats going on in the console.
I have a page with 2 Div containers ( Left and Right ).
PartsList page has 5 dynamically generated DIVS.
Custom page has 5 dynamically generated DIVS.
The div with id "layout" isnt getting recognized with the jQuery .on(). Please help. Thank you for you time :).
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript">
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");});
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
</script>
<body>
<div class="main">
<div class="left">
//Load Left page.
</div>
<div class="right">
//Load Structure page.
</div>
</div>
</body>
</html>
PartsList
<?php
for ($x = 1; $x < 6; $x++)
{
$divs = <<<here
<div id = 'div$x' class = 'list'><strong>Div: $x</strong></div>
here;
echo $divs;
}
?>
Custom
<?php
echo '<div id="layout">';
for ($y = 0; $y < 5; $y++)
{
echo "<div id='x$y' style='
position: absolute;
width: 200px;
height: 100px;
top: ".(100 * $y)."px;
border: 2px solid blue;
cursor: pointer;
'></div>";
}
echo '</div>';
?>
in jquery 1.7+ use on like
$(document).on('click','dynamicElement',function(e){
//handler code here
});
in the earlier versions use delegate
$(document).delegate('dynamicElement','click',function(e){
//handler code here
});
you can replace the document with parent element of the dynamically generated element
From the Jquery online manual:
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
url: string containing the URL to which the request is sent.
data: map or string that is sent to the server with the request.
complete(responseText, textStatus, XMLHttpRequest)A callback function that is executed when the request completes.
You probably need to put the .on function as a callback of the .load for that Custom.php page.
Something like this EXAMPLE:
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
});
I think you've got the wrong syntax for the .on() function it should be something like:
$('document').on('click', '#layout > div', function() {
alert($(this).attr('id'));
});
You bind to the document and when a user clicks on a child div in layout the event 'bubbles' up the DOM to the document where it is caught.
Okay. I found the answer anyhow. For people who were thinking why it didnt work. It was because of the stupid QUOTES.
$("document") should have been $(document) since document isnt a tag <.
And tada thats it.
Sigh.
Thanks for the help everyone :)
I am editing my question after in depth searching about my problem basically my website is a fashion display website it displays shoes cloths and bags etc now its obvious that i will be having lots of pics i was solving my problem with jquery and javascript that when a user clicks a thumbnail on the index page or he goes to the menu and clicks the shoes link javascript opens the larger image in a new tab but now i m switcing to php what i did is below
I made a mysql database having paths to the images like images/zara/thumbnails/shoes for thumbnails and images/zara/shoes for the larger images
when the user clicks on the links for ex(shoes) the link text will be grabbed by jquery like this
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: 'POST',
url: 'thegamer.php',
data: {'txt'}
});
});
});
Further pass it to the php file now here i m facing a problem what i need at the moment is
that how will php make search on the basis of that var txt in the database retrieve the thumbnails of the shoes open a new tab say(shoes.html) and display all the available shoes thuumbnails in divs
Here's the jquery code that should work:
<script>
$(function () {
$(document).on('click', 'div.prodcls img', function (e) {
e.preventDefault();
window.open($(this).attr('src').replace('/thumbnails', ''), '');
});
});
</script>
And some css for good measure:
<style>
div.prodcls img:hover {
cursor: pointer;
}
</style>
Here's a working fiddle: http://jsfiddle.net/DenGp/
Css:
#imagePopup{ float:left; z-index:10; position: absolute;}
Add some positioning
HTML:
<div id="prodtwoid" class="prodcls">
<img src="images/thumbnail/zara/2.png" alt="ZARA"/>
</div>
<div id="prodthreeid" class="prodcls">
<img src="images/thumbnail/puma/1.png" alt="PUMA"/>
</div>
<div id="prodfourid" class="prodcls">
<img src="images/thumbnail/hermes/1.png" alt="HERMES"/>
</div>
//This is you popup div
<div id='imagePopup' style='display:none'>
</div>
JS:
$('.prodcls').click(function(){
var src = $(this).attr('src').replace('/thumbnail', '');
$("#imagePopup").html("<img src='"+src+"'/>")
$("#imagePopup").toggle();
});
Updated answer:
HTML: (give every image a link):
<a href='showImage.php?img=path/of/image.jpg'><img src='path/of/thumb.jpg'/></a>
showImage.php:
$sImagePath = $_GET['img'];
echo "<div class='imgDiv'>";
echo "<img src='$sImagePath' />";
echo "</div>;
You can open actual image in new browser tab without jQuery:
For Example:
<div id="prodoneid" class="prodcls">
<a href='images/zara1.png' target='_blank'>
<img src="images/thumbnail/zara/1.png" alt="ZARA"/>
</a>
</div>
Perhaps a lightbox is what you really need? take a look at this library: http://www.huddletogether.com/projects/lightbox2/
You have an error in your AJAX code (your forgo to include the actual var:
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: 'POST',
url: 'thegamer.php',
data: {'txt':txt} //added :txt here
});
});
});
Now in PHP:
$txt = $_GET['txt'];
//Now lookup $txt in you msyql db
//And echo the result, so JS can read it.