I'm trying to have the background image of the body of my page change every (approximatly) N seconds. For this i have a PHP function that echoes random image src when i call it using AJAX. I then replace the current body background image src by this newly generated one, but i can't get it to work.
Here is the code, is there anything wrong in it ?
(function($) {
var $body = $('body');
window.setInterval(function() {
$.ajax({
url: 'http://localhost/some_path/index.php?exec=getNewBkgImgSrc',
}).done(function(data) {
var newImage = new Image();
newImage.onload = function() {
$body.css('background-image', newImage.src);
};
newImage.src = data;
});
}, 5000);
})(window.jQuery);
And the PHP function which does work :
public function getNewBkgImgSrc() {
echo CONTENT_URL_DIR.'/Wallpapers/wallpaper ('.rand(1, 20).').jpg';
}
Could this be because i'm using localhost ? I can mremeber having AJAX problems before when i was developping locally.
EDIT : A clue maybe is that the style property of the body element doesn't sseem to change / be set in Firebug. I also tried $('body').first() and $(document.body) and using url("") (in the value of background-image property) but it doesn't work either. The onload event does fire however.
Thanks for your help.
Why are you creating a new image object if you are getting a URL back from PHP? Just set the background-image property of body to:
$body.css('background-image', "url('" + data + "')");
If using vanilla JS:
document.body.style.backgroundImage="url('" + data + "')";
See proper format for that property here: http://www.w3schools.com/cssref/pr_background-image.asp
might need to cache bust the ajax call. Try changing the url property of the ajax call to
'/some_path/index.php?exec=getNewBkgImgSrc&cb='+((new Date).getTime()).
I have not good sense about var $body = $('body');
use $('body').css('background-image', newImage.src);
Related
So i got a youtube url... which im trying to get into my database in some way...
So what i got is an image
<img src = "cat">
And i also got a youtube url
https://www.youtube.com/watch?v=AFGWnqNf6t0
Then what i want is when i click on my image i want the youtube link to be inserted into a php varible so I later can insert it into my database
$("#img").click(function(){
$.ajax({
url: "php file",
});
return false;
});
How am i supposed to call the varible since Im not posting the url?
For example like $username = $_POST['username']; when i post something but to get the youtube url instead!
You can simply use the attr property like this
HTML Code
<img src = "bilder/lenny.gif" data-action = "//https://www.youtube.com/watch?v=5dsGWM5XGdg"
alt = "lenny" id = "add" width = "40" height = "40">
jquery Code :-
$("#add").click(function(){
var dataprop = $(this).attr('data-action');
//SEND IT TO AJAX NOW
});
You can add parameters to a GET request with & and ?.
test.php?bookid=15&page=435
You can add your value with jQuery:
$("#add").click(function(){
$.ajax({
url: "spelista.php?value"= $('#idofelementwithvalue').val(),
});
return false;
});
Sending the href:
$("#add").click(function(){
$.ajax({
url: "spelista.php?value"= $('#idofelementwithhref').attr('href'),
});
return false;
});
Note: You can get teh href with attr('href')
I hope that awnsers your question!
Make sure you know what value comes from your Database the "action/href/value". Then, you need to use:
$("#add").attr("href")
In this way, you get the value of the action/href/value from the html element. Replace "href" with whatever is the attribute's name. After getting the value, you need to post it to your url by jQuery post method. Please see the following example:
$("#add").click(function(){
var videoValue = $("#add").attr("href");
$.post("spelista.php", {video: videoValue}, function(data){
alert("Data: " + data);
});
}
Hope this helps!
Just an addition to Agam's Answer:
Here, the image is wrapped inside a link tag. This is just to provide a better user experience. i.e making the image look clickable(the little click hand)
<a id="link_tag" href="https://www.youtube.com/watch?v=5dsGWM5XGdg">
<img src = "bilder/lenny.gif" alt = "lenny" id = "add" width = "40" height = "40"></a>
<script>
$("#link_tag").click(function(){
var link = $(this).attr('href');
alert('This link is '+link);
});
</script>
Also your link is invalid. remove the //
Here is the answer, so you get what i was trying to achieve..
<img src = "cat" id = "https://www.youtube.com/watch?v=AFGWnqNf6t0"
onclick = "saveVideo(this)">
Then the script.... To make the id go to php
function saveVideo(x)
{
var film = x.id;
$.post('spelista.php', {film: film},function(data){
alert(data);
})
}
And then last the php varible
$url = $_POST['film'];
var_dump($url);
And then $url is the youtube url ...
Cheers!
I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.
I have a Javascript function I'm rendering on a page where the user can click on a list element and it will bring them to a new page showing more information about that list element. The original page is #index and the second page is #index2 which is coded using one multipage HTML page.
However I am hoping that I can move the index2 page to its own html file - index2.html but I'm not sure how I can reference the new index.html file within the function so that the elements can move to the new file.
My code is as follows:
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true)
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
If somebody could help me I'd really appreciate it.
You will need to separate pages into two php files, one called view.php and second one called offer.php.
Create 2 additional directories, one called amend and second one called del. Both of them will have a js file with logic related to the amend or delete functionality plus a php file which will server as a php/ajax proxy for a needed functionality.
Also take care that your 2 ajax calls must look at a correct location and that ajax response also must state witch action has beed done.
My guess is that you will need to make an Ajax request to your server for index2.html, since it no longer lives on the same page as index1.html. Here's an example
$.ajax({
url : '/pages/index2.html',
type: 'get',
success: function (html) {
// here , you can use jquery to manipulate
// the HTML in index2. Maybe pop up a lightbox, etc..
}
});
I'm not sure what you're trying to do, but Ajax is a fairly standard way of requesting new HTML / data behind the scenes. There is a lot you can do with JQuery ajax. Here are the docs
Jquery Ajax
I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.
EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..