i'm creating a gallery which is loaded from a directory. first im creating a div tag for each album folder in the directory. then im using jquery ajax to get the folder name that was clicked and create div tags for each image in that folder. im sending the id of the folder to an external php page to grab the file paths for the images. im not sure how to output actual html. quite new to ajax/php coding so explanations are helpful.
jquery ajax:
var jq=$.noConflict();
jq(document).ready(function(){
jq(".album-select").click(function(event){
var id=event.target.id;
jq.ajax({
type: "POST",
url: "image_loader.php",
data: {phpid:id},
success: function(data){
jq('#mydiv').html("");
jq('#mydiv').append(data);
}
});
image_loader.php
<?php
if (isset($_POST['phpid'])) {
$album_fill = $_POST['phpid'];
}
$dir = 'images';
$slash = '/';
$dir_image = "$dir$slash$album_fill";
$dir_contents = scandir($dir_image);
foreach($dir_contents as $file){
if($file !== '.' && $file !== '..'){
$dir_imagepath = "$dir_image$slash$file";
echo '<div style="position:absolute; width:100px; height:100px; top:1100px; left:500px;">';
echo '<img src="',$dir_imagepath,'">';
echo '</div>';
}}?>
first of all change your success function as follows:
success: function(data){
$('#mydiv').html(data);
}
secondly, make sure your ajax call is returning an HTML page.
Take this
jq('#mydiv').html("");
jq('#mydiv').append(data);
And make it this
jq('#mydiv').html(data);
Related
I've got a php function that i would like to run from a Html button I've got.
The php function is on a separate file than the Html button.
So I've managed to do this with:
<input type="submit" name="test" id="bt1" value="RUN" /><br/>
But that is not what i want to do. I want to call the php function with:
<button id="bt1" class="button button5">< Random </button>
as there are other actions coupled with the button that need to run at the same time.
Side note: My php function gets info from a json file.
I've got 3 files.
File 1 (AF.php) this is where the button is
File 2(Display.php) This is where my jquery/javascript/ajax scripts are
File 3(Names.php) This is where the php function is. I want to use button from File 1 to run php function from File 3.
So here is what I've tried so far:
File 1(AF.php)
button id="bt1" class="button button5">< R30K</button>
File 2(Display.php)
$(document).ready(function () {
$("#bt1").on("click", (function () {
getName("Names.php");
})
});
function getName(Names.php) {
$.ajax({
url:"Names.php" + Names.php,
success:function (Names.php) {
$("#res" + Names.php).html(result)
}
});
File 3(Names.php)
<?php
function group1(){
$jsondata = file_get_contents("Clients.json");
$json = json_decode($jsondata, true);
$output = '<ul>';
foreach($json['Reps']as $reps){
$output .='<h4>' .$reps['Client']."<h4>";
$output .= "<li>".$reps['repCode']."</li>";
}
$element = $json['Reps'][array_rand($json['Reps'])];
echo $element['Client'];
echo " ";
echo $element['repCode'];
}
if(array_key_exists('bt1',$_POST)){
group1();
}
?>
Desired outcome would be that I can run my function from File 3 with that Html buttom from File 1.
You're help is greatly appreciated.
Your HTML with that button and your jQuery code must be in the same document that is loaded by your browser, either by putting them in the same file or using php include/require.
That jQuery code will not run because you put "Names.php" everywhere (Why?). Try this:
$( function(){
$("#bt1").click(function() {
$.ajax({
url: 'Names.php',
type: 'get',
success: function(data) {
$("#res").html(data);
},
});
});
});
This will put the ajax response string into any element with id="res".
Code was tested and works.
Edit:
I just noticed that you are using $_POST in your php script to check if the button was clicked, so you will have to modify the jQuery ajax function:
Change type: 'get', to type: 'post',
Add data: 'bt1=1', after 'type: 'post'.
I'm trying to use AJAX so that you don't see the reload refresh.
i want if i change the select button from 1 to 5 that you can see 5 live change and that i can use the 5 in a php variable.
i got this:
<script>
$(document).on('change', '#hoeveelheid', function(e) {
var j_Hoeveelheid = this.options[e.target.selectedIndex].text;
$.ajax({
type: 'POST',
url: 'do.php',
data: {aantal : j_Hoeveelheid},
success: function (data) {
$('.test').html(data);
}
});
}
</script>
Now is my question what i need to set in the do.php file?
so that my script works without any refresh visible.
what i need to set in the do.php file?
At php file you are sending this object:
data: {aantal : j_Hoeveelheid},
so you need to get the key aantal at php end.
You can do this in your php file:
<?php
$aantal = $_POST['aantal'];
echo $aantal . " is the posted value of dropdown.";
?>
I have a site with a giant portfolio with a ton of high-res images.
I do not want to resize these images, but I would like to be able to pull them in async.
Come forth jQuery .ajax
But my code is wrong, somehow. What it does is seem to pull in the page, instead of the image "src"
Can you help:
// Load in the images via ajax:
var $imgs = $('.ajax-image');
$imgs.each(function(i){
var $imgsrc = $(this).attr('src');
var $url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
$(this).attr('src', html);
}
});
});
and the PHP:
$path = $_GET['i'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
echo 'data:image/' . $type . ';base64,' . base64_encode($data);
Image tags are simply: <img src="http://example.com/images/image.ext" />
What am I doing wrong here? and how can I fix it?
As I mentioned in my comment, I don't see how this would do what you want but to address your current problem: It is probably caused because of this in the context of the success function, is not the same as the this in the context of your each() function.
You should save the element so that you can access it in the success function:
$imgs.each(function(i){
var el = $(this),
$imgsrc = el.attr('src'),
$url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
el.attr('src', html);
}
});
});
Edit: There is no real need to use ajax / php here to set the source of the image. You could also generate some images in javascript (in batches), add an onload() function for the images and set the source of your html elements when they are loaded and then get the next batch. See for example this question: JavaScript: Load an image from javascript then wait for the "load" event of that image
Your php page is getting an error because you are not passing in anything for parameter i. Your php is therefore throwing a 404 error - a full HTML response.
I think you have a javascript syntax error that is causing this:
url : '/php/pull-image.php?i=' . $imgsrc,
Replace this line with:
url : '/php/pull-image.php?i=' + '<?php echo json_encode($imgsrc); ?>' ,
My div contains a PHP function having an sql query which fetch latest threads from threads table. The structure of my page is something like this;
Section # 1 --- Link 1
Section # 2 --- Link 2
Section # 3 --- Link 3
What I want to do is to make it so like when Link 1 is clicked it shows the latest threads from Section 1, and when Link 3 is clicked then it shows latest threads of Section 3.
PLEASE NOTE: I know that I can use slidetoggle() jQuery function to show and hide div, but I want to make it so that WHEN link is clicked THEN runs the sql query to show latest threads. I'm using the following jQuery;
jQuery(document).ready(function($)
{
$('a[id^="forum_name"]').on('click', function (e)
{
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type: "POST",
url: 'latest_threads.php?fid='+fid,
dataType: 'json',
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
});
});
});
My PHP file latest_threads.php has the following code;
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
$forum['forum_threads'] = kalachi_forum_threads($fid);
}
?>
and My HTML is like;
{$forum['threads']}
<div id="forum_threads_{$forum['fid']}" style="display: none;">{$forum['forum_threads']}</div>
But it doesn't works, please help!
jQuery:
jQuery(document).ready(function($){
$('a[id^="forum_name"]').on('click', function (e){
e.preventDefault();
var fid = $(this).attr("fid");
$.ajax(
{
type : "post",
dataType: "html",
url : "misc.php?action=forum_threads&fid="+fid,
cache: false,
success : function(response)
{
$("#forum_threads_"+fid).stop().slideToggle("fast").html(response);
}
});
});
});
PHP:
<?php
define("IN_MYBB", 1);
require_once "./global.php";
if ($mybb->input['fid'] != "")
{
require_once MYBB_ROOT."inc/functions.php";
$fid = intval($mybb->input['fid']);
echo $forum['forum_threads'] = kalachi_forum_threads($fid);
exit;
}
?>
In HTML:
Change the last line to this:
<div id="forum_threads_{$forum['fid']}"></div>
You're not outputting your response as far as I can see.
Try something like this:
...
$forum['forum_threads'] = kalachi_forum_threads($fid);
echo $forum['forum_threads']
exit();
...
I added the echo line to output the actual response back to your browser.
You can read Ajax tutorial.
But in your case, you should know, the data that you are showing in your div in this part of your code :
success: function (data)
{
$("#forum_threads_"+fid).html(data).stop().slideToggle("fast");
}
is the response of your php code.
Your php response is any output of your php code, it can be a simple echo 'something' or a html code, or including a html file etc.
generete a html code or include a html file in your php code, anything that you want to show in your div.
Note: always put a die() or exit() in the end of your php code.
This is a simple example :
HTML :
<div id="c1" onclick="javascript:loadcontent(1);">click</div><br>
<div id="c2" onclick="javascript:loadcontent(2);">click</div><br>
<div id="c1" onclick="javascript:loadcontent(3);">click</div><br/
Javascript (jquery) :
<script>
function loadcontent(id) {
$.post("yourphp.php", {id: id}, function(data) {
if (data) {
$("#c" + id).html(data);
}
else
{
alert("error");
}
});
}
</script>
PHP - yourphp.php :
<?php
$id = $_POST['id'];
require 'filename'.$id.".html";
die;
?>
Then you must create 3 html files with names : filename1.html , filename2.html , filename3.html
and put any content in them that you want to show in your divs with id c1,c2 or c3 .
Thats it
I need to get a value from a select box and use it for a PHP function further down on the page.
I have index.php with a regular select drop down. The value and option in the select box is the name of a folder. When I pick a folder, I want to get that value through jquery/ajax without updating the entire page. I'm then going to use that value in another php function further down on the page where I list the file names found in that folder.
I also have a script.js file. What I have so far is:
$(document).ready(function() {
$("#select-folder").change(function() {
// Get selected value and send to index.php
});
});
I'm new to jquery and ajax so I don't quite know how to send this value without updating the entire page or if it's even possible? Perhaps I need to include the javascript as a script tag on the index.php page?
Updated to add new code
This is in my index.php file and works to get the folder name to send it to file.php
<script>
$(document).ready(function() {
$("#select-folder").change(function() {
var value = $(this).val();
console.log(value);
$.ajax({
url: "/files.php",
data: "site=" + value,
type: 'POST',
success: function(var1, var2) {
console.log(var1 + var2);
}
})
});
});
</script>
Then, in file.php I get the folder name and loop through all the files inside the folder.
But when I output with this code:
echo '<p>' . $file . '</p>';
It outputs in the console log and not in the index.php
Problem solved
I realized after a lot of searching that I should add the code into a div through ajax or it wouldn't show up because of page loads.
I added this piece of code to the success part of the javascript from above:
$('#show-files').html(var1);
Thanks to everyone for their help.
$.post('/index.php', { selectedId: this.value }, function(resultHTML){
$('#containerId').html(resultHTML);
});
This code sends selected value to index.php page which returns part of html and we put this part somewhere on page (in this case in element with id containerId)
For example.
We have next folder (tree) structure:
./images
|--/foto1
|---- 1-1.jpg
|---- 1-2.jpg
|---- -13.jpg
|--/foto2
|---- 2-1.jpg
|---- 2-2.jpg
|---- 2-3.jpg
./index.php
Select index/foto1 folder in you select element with value "images/foto1"
$(document).ready(function() {
$("#select-folder").change(function() {
var folderName = $(this).val(); // get a folder to display.
$.ajax(
url: "index.php",
type: "POST",
data: {'folder':folderName},
dataType: "json"
success: function(data){
console && console.log(data);
// data variable will contains array of files
$("#result").html('');
for(i=0,c=data.length;i<c;i++)
$("#result").append( data[i]+'<br>');
}
);
});
});
index.php contains next code:
<?php
$files = array();
if( isset($_POST['folder']) && file_exists($_POST['folder']) && is_dir($_POST['folder']) ){
if ($handle = opendir($_POST['folder'])) {
while (false !== ($entry = readdir($handle)))
array_push($files, $entry);
}
}
echo json_encode($files);
Also you need to add security check for input (directory check).
You can use for this realpath(), dirname() and other Filesystem functions.