i have a PHP code that will obtain the total images of a certain website via CURL, and put it inside an PHP loop.
$z=1;
for ($i=0;$i<=sizeof($images_array);$i++) {
....<img src = "$images_array[$i]" id="$z"> ..
$z++;
}
a user can then scan through the array with a prev/next button and the current image being shown will be displayed in my $('$current_image').val(1);
$.post("curl_fetch.php?url="+ extracted_url, {
}, function(response){
$('#loader').html($(response).fadeIn('slow'));
$('#current_image').val(1); // insert loop value in .val()
when i click a button, i want to get the value of the array, and not the loop value
$(function() {
$(document).on('click','.submit', function () {
var img = $('#current_image').val(); //get the array value, not the loop value
alert(img);
});});
now, how do i properly get the array value in my $('#current_image').val(1); in Jquery.
Your question is a little confusing but it sounds like you want to fetch a list of images using curl and then be able to page through them one by one using jQuery. One way to do this would be to build a javascript array of the image URLs and then just update the value of the img src using that array.
<!-- load the page with the first image -->
<img src="<?php echo $images_array[0]; ?>" id="visible_img"></img>
<button id="previous"><< previous</button>
<button id="next">next >></button>
<!-- setup a javascript array of images and listen for clicks -->
<script type="text/javascript">
var curIdx = 0;
var imageUrls = ["<?php echo implode('","', $images_array); ?>"];
// display the previous image (if there is one)
$("#previous").click(function() {
if (curIdx > 0) {
curIdx--;
$("#visible_img").attr("src", imageUrls[curIdx]);
}
});
// display the next image (if there is one)
$("#next").click(function() {
if (curIdx < imageUrls.length - 1) {
curIdx++;
$("#visible_img").attr("src", imageUrls[curIdx]);
}
});
</script>
Related
so i have a php loop, i am using jquery slide toggle to hide/show a table with sql results. currently the table is loaded using php only, but as there is a lot going on its causing some loading problems i need to fire the ajax with the slide toggle btn, so it only requests the current items details when the button is pressed. i can get it to call the php file from the jquery but im having difficulty passing the value for each item across, so it can perform the request on the database. here is what the php foreach loop content looks like;
<span class="searchitem">
// some visible content here
<span value="item name" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
this html is repeated i use jquery slidetoggle to hide the slide_area, what i need to do is populate the slide_area with results from php, the php file needs the name to return the results the name is passed via get with the url, so i only need append the url with the actual name from btn's value, im sure this cant be that difficult but here i am.
here's the jquery:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function ()
{
$('.searchitem').each(function () {
$(this).find('.slide_area').hide();
$(this).find('.btn').click(function ()
{
var ajax_load = "<img src='images/spinner.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item.php?name=";
var loadName = $(".btn");
var Name = URLEncode(loadName);
var loadString = loadUrl + Name;
$(this).parent().find('.slide_area').slideToggle(1500).html(ajax_load).load(loadString);
});
});
});
//]]>
</script>
i need to get the value from btn and append the loadURL, im open to sending the data a different way like through post if needed, updated the jquery still not working what am i doing wrong here?
Thanks.
The easiest way would to use the Phery library http://phery-php-ajax.net/
the key here is the data-phery-remote="toggle" that will call the PHP function automatically on click, and can be reused everywhere
<span class="searchitem">
// some visible content here
<span value="item name" data-phery-remote="toggle" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
The logic is reversed, the load will happen with only one AJAX call, instead of two.
Phery::instance()->set(array(
'toggle' => function($data){
$r = new PheryResponse;
/* do your code, fill $html_content */
$r->this()->siblings('.slide_area')->html($html_content)->toggle();
return $r;
}
))->process();
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') } );
So say I've got a series of images created with a php loop ->
<img src="http://..._1.jpg" class="profile-thumb" id="12345678">
<img src="http://..._2.jpg" class="profile-thumb" id="12345677">
<img src="http://..._3.jpg" class="profile-thumb" id="12345676">
The user can select the image elements by clicking on them jquery style a la ->
$(".profile-thumb").click(function () {
if ($(this).hasClass("active")) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
So that when you click an image it adds an '.active' class to the image element ->
<img src="http://..._3.jpg" class="profile-thumb active" id="12345676">
How would I pass all the selected elements IDs into an array for use in a form process with PHP?
User journey:
Click photo -> Adds ID to array -> Click a submit button -> Uses POST array to perform a function with all IDs (e.g. send an email to all users using the IDs identified as active)
I want to pass the array to a loop with an AJAX call and echo output to the #post-info div ->
$.get('post.php', function(data) {
$('#post-info').html(data);
});
How will I then read the POST array with a foreach loop?
Solution:
HTML:
<button id="share" class="off">
<span>Sharer</span>
</button>
<div id="sharer">
<!-- Array will echo here -->
</div>
Javascript:
$("#share").click(function () {
//Create var array
var list = $('.active-profile').map(function(){return this.id;}).toArray();
$.post('sharer.php', {ids:list}, function(data) {
$('#sharer').html(data);
});
});
PHP (sharer.php)
foreach ($_POST['ids'] as $id) {
echo 'ID: ';
echo $id;
}
The javascript array (list) is sent via jquery POST and echo'd in the #sharer div
$('.profile-thumb.active').map(function(){return this.id}).toArray();
Also, instead of if-hasClass-removeClass-else-addClass, you can simply use:
$(".profile-thumb").click(function () {
$(this).toggleClass("active");
});
Demo: http://jsfiddle.net/ErVbS/
To sent an array of values to php you need to use a slightly different syntax. For each id you can create a url that looks something like.
http://test.com/?img_id[]=1&img_id[]=2&img_id[]=3
This will let you get the value img_id as an array in php.
$_POST['img_id'] // array of values.
foreach ($_POST['img_id'] as $id) {
print $id;
}
// 1
// 2
// 3
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);
})
})
The values don't seem to be coming out and showing up on the page. It should be creating divs that pop up with the google_color and the background set to the hex value.
The app is suppose to take pixel image data and match it to my swatch library known as formatted_colors.js, which is an array. The array looks like this:
var colors = [];
colors["000000"] = "black"; colors["100000"] = "black"; colors["200000"] = "black";
Maybe I'm not suppose to use the .each function? Although it is a loop.
Here is a snippet:
<div class="rounded_color" hex="<?php echo $css_color ?>" xy="<?php echo $x.$y ?>"></div>
<div id="<?php echo $x.$y ?>"></div>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script src="formatted_colors.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//iterate through pixels and match rounded color to array in formatted_colors.js
$(document).ready(function() {
$(".rounded_color").each(function(){
var google_color = getColor($(this).attr("hex")); // finds a match of "hex" value in formatted_colors.js and return name to google_color
$('#'+$(this).attr("hex")).html(google_color); // set the div's html to name which is google_color
alert('#'+$(this).attr("id")); //testing if value is there, but shows #undefined
$('#'+$(this).attr("hex")).css('background-color:', google_color);
})
// get name of color function from formatted_colors.js
function getColor(target_color){
if (colors[target_color] == undefined) { // not found
return "no match";
} else {
return colors[target_color];
}
} // end getColor function
}) // end ready function
</script>
Sorry, I'm new to this so I'm not sure what to do exactly now.
Here is my entire code: http://pastebin.com/HEB3TWZP
Thanks in advance!
You don't need to concatenate #. this is the current element in the iteration.
Also you might want to do something like var $this = $(this); Cleans up your code and you aren't recreating the jQuery object over and over again within the same iteration.