Converting jquery function from form submit to php array result - php

I'm attempting to take the ImageResolver plugin and adapt it to work with a php array.
Stripping the code to this returns the image without a form:
$(function(){
var url = $('#url').val();
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').html('<img src="' + image + '" alt="">');
} else {
$('#result').html('<h2>No image found</h2>');
}
});
});
I want to adapt it to work within a php foreach loop. results would be replaced on the next class='result' div. IE: after the page has loaded the urls from the query, the function will parse the url and return image link if one is found. I'm guessing I need to use (each) or this(), but I can't figure it out.
can someone point me in the right direction?

<script src="ImageResolver/URI.min.js"></script>
<script src="ImageResolver/ImageResolver.js"></script>
<?
$javascriptarray = 'var urls = [';
$counter=0;
foreach (array('http://www.apple.com/','http://github.com/','http://www.test.com/') as $url)
{
if ($counter++ > 0) $javascriptarray .= ',';
$javascriptarray .= '"'.$url.'"';
}
$javascriptarray .= '];';
?>
<script>
<?=$javascriptarray?>
//The ImageResolver will try all the resolvers one after the other
//in the order of their registration
//Resolvers that guess the image URL
ImageResolver.register(new FileExtensionResolver());
ImageResolver.register(new ImgurPageResolver());
ImageResolver.register(new NineGagResolver());
ImageResolver.register(new InstagramResolver());
//Resolvers that need extra ajax requests
ImageResolver.register(new ImgurAlbumResolver());
ImageResolver.register(new OpengraphResolver());
ImageResolver.register(new WebpageResolver());
//Some jQuery code to make the demo work
//Use a crossdomain proxy (required by some plugins)
$.ajaxPrefilter('text', function(options) {
options.url = "http://furious-stream-4406.herokuapp.com?src=" + encodeURIComponent(options.url);
});
$(function(){
var length = urls.length,
url = null;
for (var i = 0; i < length; i++) {
url = urls[i];
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').append('<img src="' + image + '" alt=""><br>');
} else {
$('#result').append('<h2>No image</h2>');
//$('#result').append('<h2>No image found for ' + url + '</h2>');
}
});
}
});
</script>
Watch out cause ImageResolver.resolve() works asynchrone you can get unexpected results. Call ImageResolver.resolve() again before the previous call has finished will change url in $('#result').append('<h2>No image found for ' + url + '</h2>'); to the url of your last call by example. To prevent this you need to initialize a new Resolver in the for-loop. see: Javascript prototypes and instance creation

Related

Ajax infinite scrolling not loading

So in my index.php file i have this:
<script src="jquery-1.12.3.js"></script>
<script>
$(window).scroll(function() {
var load = 0;
if($(window).scrollTop() + $(window).height() == $(document).height()) {
load++;
$.POST("scripts/myload.php",{load:load},function(data){
$.('photoclass').append(data);
})
}
});
</script>
and in my "myload.php" file i have this
$query = $handler->query("SELECT * FROM photo LIMIT ".$load.",5");
while($photo = $query->fetch()){
echo '<center><h1 class="ptitle">'.$photo['PhotoTitle'].'</h1></center>';
echo '<center><img src="UserPhotos/'.$photo['Photo'].'"></center>';
}
The problem is that it won't load in my index file the rest... Thanks in advance.
change your jquery code.
$.('photoclass').append(data); to
$('.photoclass').append(data); or $('#photoclass').append(data);
putting "." or "#" depends on class or id.
for example :
<div class="photoclass"> </div>then use $('.photoclass').append(data); otherwise $('#photoclass').append(data);
and in your php file make sure you are saving post value to variable.
like this $load=$_POST['load']

Creating dynamic div content with jquery

I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON.
My problem is that I can't get the JSON data to display when clicking the links.
Here's the script I'm using:
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
for(var i=0; i<data.length;i++) {
$("#changetext"+data[i].id).click(function() {
$("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
});
}
}
});
This is the div element that has to change:
<div class='rightside' id='rightside'>Test</div>
The links are constructed this way:
echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";
I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.
Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
$.each(data, function(i, d) {
$("#changetext" + d.id).on('click', function() {
var h1 = $('<h1 />', {text : d.title}),
p = $('<p />', {text : d.content});
$("#rightside").html(h1.add(p));
});
});
}
});
The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.

javascript variable value to php variable and loading tab content by default

var Result;
$(document).ready(function(){
location.href="index.php?Result=" +1;
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
});
<div id="tabs">
<ul>
<?php include "config.php";
$query = "select * from tabs";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$name = $row['name']; $tabid = $row['tabid'];
echo '<li><a id="' . $tabid . '" href="#' . $name . '"> ' . $name . '</a></li>';
} ?>
</ul>
</div>
Hie,
I have seven tabs,which are fetched from database using mysql query,Onclick on each tab am passing the tab value from javascript to php variable and by using that tabvalue am running the required querys to load the data into tabs,My issue is am unable to load the first tab content by default,on click the first tab content is loading properly,i want that first tab content to load by default here am using jquery ui tabs,when i followed the above code by calling first tab before onclick it is loading multiple times....and even focus is moving to first tab by default...suggest any solution......thanks....
The reason is, you are redirecting to index.php from the same file. So during the first execution of document ready function, it redirects you to the same file with a different query string parameter. But since the document ready function will execute again now, it keeps on reloading.
The simplest approach will be to handle this in PHP, when the "Result" parameter is not set, make it as 1.
In a javascript way, you can grab the query string value and check if "Result" parameter is set. If its not set then redirect the page to index.php?Result=1.
A javascript way of getting query string parameter is below.
function param(name)
{
var url = window.location.search.substring(1);
var query = url.split('?')[0];
var data = query.split('&');
for(var i in data)
{
if(data[i].split('=')[0] == name)
{
return data[i].split('=')[1];
}
}
}
You can call it by using
var page_num = param('Result');
if(page_num == null)
{
location.href = 'index.php?Result=1';
}
try this
var Result = 1;
$(document).ready(function(){
location.href="index.php?Result=" + Result;
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
})
This will trigger automatically first tab click.
<script type="text/javascript">
$('.parent > a').trigger('click');
</script>
var Result;
$(document).ready(function(){
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
}
And Body tag
<body onload="location.href='index.php?Result=1'">

Pass value from jQuery into PHP script in ONE file

The following is one file index.php GetWidth and GetHeight functions work. (They are not final functions so not important.) The important part is marked by /* IMPORTANT HERE */ What I am trying to accomplish is pass the variable I get using jQuery Window Portal Height / Width and pass it to a PHP script here In other words when I get value from GetWidth() it should go to w=120 or replace 120 value with whatever the width is at the moment and the same with height. If there is any syntax errors please ignore.
I only want to figure out how to pass value from jQuery to PHP scrip. Also in the future I want add on resize method so values will be dynamic when window is resized.
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(window).resize(function () {
$('#msg').text('Browser (Width : '
+ $(window).width()
+ ' , Height :' + $(window).height() + ' )');
});
$(document).ready(function() {
// DOCUMENT READY
function GetWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement &&
document.documentElement.clientHeight) {
return document.documentElement.clientWidth;
}
else if (document.body) {
return 0;
}
return x;
}
function GetHeight() {
if (self.innerHeight) {
y = self.innerHeight;
}
else if (document.documentElement &&
document.documentElement.clientHeight) {
return
document.documentElement.clientHeight;
}
else if (document.body) {
return 0;
}
return y;
}
// This is for when it first loads.
$('#TEXT').text('W: ' + $(window).width() + ' , H:' + $(window).height() + y);
// This is for when window gets resized.
$(window).resize(function () {
$('#TEXT').text('W: ' + $(window).width() + ' , H:' + $(window).height());
});
// DOCUMENT READY
});
</script>
</head>
<body>
Info Area:<br>
<div id="TEXT"></div>
/* IMPORTANT HERE */
<!-- img src="timthumb.php?src=URL...image.jpg&h=180&w=120" -->
/* IMPORTANT HERE */
</body>
</html>
wellcome to stackoverflow!
the problem is that the php is compiling in server and browser receive a html and javascript file from server
then your browser compiling your javascript and html code
so javascript unable to change phpcode
you can make your html whit javascript like this:
image = new Image();
image.src = "timthumb.php?src=URL...image.jpg&h="+ hgt + "&w=" + wth;
image.onLoad=function(){ $("img").attr({src: image.src}); }
You can not pass the jQuery or JS variables to the PHP script.
Basically the PHP scripts get executed at server level and only HTML, JS and CSS will be returned to the browser. Then browser will render it. So when browser executing your JS method, the PHP scripts are already executed.
you can use Ajax.
You can not pass values from jQuery to PHP becuase PHP is a server-side language and jQuery is a client-side language. But there is a way to pass data from client-side to server-side which is AJAX
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming
Why PHP script is not workig in a web browser?
http://www.scriptingok.com/tutorial/Server-side-vs-Client-side

include path and ajax not working?

I couldn't get "castMyVote" function to execute. It worked when I cast a vote in poll.php but not in index.php. I have ensure all php and js are in correct path. I tried another function "displayvotewithoutvote" in Index.php, I could display statistic without vote.
index.php:
include('poll.php');
poll.php:
<img src="images/vote_button.gif">
ajax.js:
function castMyVote(pollId,formObj)
{
var elements = formObj.elements['vote[' + pollId + ']'];
var optionId = false;
**for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}**
Poller_Set_Cookie('dhtmlgoodies_poller_' + pollId,'1',6000000);
if(optionId){
var ajaxIndex = ajaxObjects.length;
ajaxObjects[ajaxIndex] = new sack(); //an api from simple ajax code kit
ajaxObjects[ajaxIndex].requestFile = serverSideFile + '?pollId=' + pollId + '&optionId=' + optionId;
prepareForPollResults(pollId);
ajaxObjects[ajaxIndex].onCompletion = function(){ showVoteResults(pollId,ajaxIndex); }; // Specify function that will be executed after file has been found
ajaxObjects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
Update: in ajax.js as showing above, it doesn't response after I include alert after, I afraid something wrong here:
for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionId = elements[no].value;
}
Please try this code in your poll.php
<img src="images/vote_button.gif" onclick="castMyVote(<?php echo $pollerId;?>,document.forms[0])">
This may help you.
Thanks,
Kanji
are you getting the pollid in the js?
var pollid="";
onclick="castMyVotepollid,....
try this

Categories