Apologies for the ambiguous title, it just goes to show how confused I am with this one.
<a href"page.php?article_id=123&&img_id=img1">change image</a>
The link above is inside a form and is supposed to allow a user to change the image on an article. The functional php side of things is sorted - uploading the image, changing the image etc, but this will require the main form being submitted which is fine for the initial upload - not so much for the edit.
When the user clicks the "change image" link, I would ideally like to process that particular request alone in a different form, then update the parent page. I thought of doing it with a javascript new window popup which would have been ideal, except that I can't figure out how to pass the article_id as well as the img_id to the new popup page but above all... is this the most efficient way of doing this nowadays?
If not, How do I carry out this task? I have thought of ajax, jquery... but the same issue of passing the article_id and img_id still limits me.
I hope all of this makes sense and thanks in advance
ps: An article can have multiple images and article id is dynamic.
ajax sounds good to me.
may be you try something like this (jquery)?!
$.ajax({
type: "POST",
url: "page.php",
data: { article_id: 123, images: { i1: "img1", i2: "img2" } }
}).done(function( msg ) {
alert( "done: " + msg );
});
for further information and examples: http://api.jquery.com/jQuery.ajax/
why cant u receive article_id and img_id?
if you use:
<a href"#" onclick="window.open('page.php?article_id=123&&img_id=img1', 'window1');">edit</a>
u can get article_id and img_id in $_GET
however, this is a oldfashioned way getting this done.
Check this up: http://www.malsup.com/jquery/form/ - jQuery is a prerequisite but plugin allows you to send form elements via ajax, including file fields using simple API and does all heavy lifting for you.
Related
Hello, I am making a jQuery YouTube search and display web application and I need to send the link of a specific video to the database using PHP.
In the application, the user searches for a video and the unique code for that video gets inserted into a set YouTube link using an "id" variable. I want to capture the full link (including the unique id) and put it into the database without having to open a new page (which is how AJAX does it, I think).
Here are links to some similar problems, but they haven't worked for me. (getting youtube video id the PHP, How do I find all YouTube video ids in a string using a regex?, https://stackoverflow.com/questions/19977278/how-to-get-php-data-in-javascript, Data transfer from JavaScript to PHP, http://www.webdeveloper.com/forum/showthread.php?249863-pass-jquery-value-to-php-variable (sorry for the massive amount of links, Stack told me to include them if they were similar and didn't work))
Here is the code that makes it work so far.
<script type="text/javascript">
//on thumbnail click
$videoDiv.click(function(e) {
displayVideo(entry.media$group.yt$videoid.$t, entry.title.$t);
});
//Display the video
function displayVideo(id, title) {
//embed player
swfobject.embedSWF('http://www.youtube.com/e/' + id + '?enablejsapi=1&playerapiid=ytplayer&autoplay=1',
'video-placeholder', '544', '408', '9.0.0', null, null, { allowScriptAccess: "always" },
{ id: "youtubevideo" } );
}
</script>
Obviously, this isn't the whole function, but hopefully it should be enough.
Please help me, I've run out of places to look.
Hi Niklas,
Thank you for answering me, I’ve tried that out and it turns out that my code is a bit more complicated to allow for that.
My project for university also needs to have information sent to the page that the video is on, currently I have the form for the user on one page and the code to search YouTube and display the user’s information as well as the video on the next (external) page.
Unfortunately AJAX is still one of the languages I haven’t yet learnt, so the documentation you linked me to didn’t make much sense.
My code is very complicated as it uses the YouTube API as well as JavaScript, jQuery and PHP. The main js file for this searches YouTube and once the user clicks on the thumbnail, it fires up a displayVideo function, which also features the information from the previous page.
I can’t redirect the user to a new page after they select the video, just to get the id into PHP, because that would wipe the data from the first form when the user gets redirected back to the YouTube form.
I’m hoping you could please assist me.
Answer
Okey, know I understand what you're asking. That you would do something like this:
<script type="text/javascript">
$(function() {
//on thumbnail click
$videoDiv.click(function(e) {
var videoURL = displayVideo(entry.media$group.yt$videoid.$t, entry.title.$t);
$.post('url-to-your-php-file', {videoURL: videoURL}, function(response) {
// Do stuff with the response given/echoed by the PHP file
});
});
//Display the video
function displayVideo(id, title) {
//embed player
var videoURL = 'http://www.youtube.com/e/' + id + '?enablejsapi=1&playerapiid=ytplayer&autoplay=1';
swfobject.embedSWF(videoURL,
'video-placeholder', '544', '408', '9.0.0', null, null, { allowScriptAccess: "always" },
{ id: "youtubevideo" } );
return videoURL;
}
});
</script>
Hope this helps and good luck!
Answer before revised question
I won't write the code for you, but you're right in your thinking and I will give you some links that may help. You need to make an AJAX call to a PHP file which saves the link to the database.
AJAX Call
You're using jQuery, which makes AJAX calls real easy. Have a look at the jQuery .ajax() documentation. Though in this case it being a really small and "unadvanced" call you need to make, the shorthand wrapper function .post() will do nicely for you.
Retrieve the link in PHP
After that you can retrieve the link in the PHP using the global $_POST variable.
Adding the link to the database
For adding it to the database, I would recommend the PHP PDO library for making the connection and queries.
Hope this helps and don't hesitate to ask if there's anything you wonder!
I'm going to do my best explaining this, as I'm fumbling around a bit as it's my first time doing anything like this.
At the beginning of my page I call a function that returns 3 recipe's, I then create variables and assign each with a recipe id:
$meal = builder::buildMealPlan(1200,0,0,0,3);
$id1 = $meal[0][id];
$id2 = $meal[1][id];
$id3 = $meal[2][id];
So I now know the id's of the 3 recipe's that have been chosen by the function, I then display these 3 recipe's in 3 div's:
<div id="meal1"><h2><? print_r($meal[0]); ?></h2></div>
<div id="meal2"><h2><? print_r($meal[1]); ?></h2></div>
<div id="meal3"><h2><? print_r($meal[2]); ?></h2></div>
When any of these div's are clicked it means you don't like that recipe and want a different one, it calls a page with 4 parameters (id1,id2,id3,clicked), basically telling it the 3 recipe's that are currently displayed as well as which one was clicked, so I can find another combination of recipes with 2 of the same id's, as well as the new one:
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1", function(result){
$("#meal1").html(result);
});
});
This works great, a proper recipe is selected and the div is refreshed with the new recipe, however my problem is now, if you click any of the div's again, it refreshes with the same recipe over and over again, because my php variables ($id1, $id2, $id3) are always the same value, since the page is never reloaded.
My question: How can I set a javascript variable with the result of my onclick event? Right now the on click event replaces the div with data from:
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1
However I need to somehow update the variables that I'm sending in the above statement with new values each time a div is clicked.
If you've read this far, thanks, if I've left important/obvious things out please just let me know and I'll add it in.
EDIT: Ok, I've got it outputting JSON now:
{"mealnumber":1,"id":"69","title":"Protein Packed Meatloaf","description":"This meatloaf is packed with protein to help your muscles grow.","cookingtime":"00:25 ","preptime":"00:10 ","servings":"4.00","rating":"0.000","calories_ps":"205.00","carbohydrate_ps":"7.70","protein_ps":"20.55","fat_ps":"9.64"}
My JS code to try and show that I'm at least reading it correctly:
$(document).ready(function(){
$("#meal1").click(function(){
$.getJSON("testing-01.php?id1="+id1+"&id2="+id2+"&id3="+id3+"&clicked=1", function(data) {
$.each(data.items, function(i, item) {
console.log(item.id);
alert(item.id);
});
});
});
});
However nothing is logged or alerted when I click the div... am I missing something obvious here? I can see in the console that it's calling to the correct page, if I copy and paste the URL I get the json code I pasted above.
Im not sure i understand all you need, but i guess you need to change this 3 ID's in get method.
You could make some simple javascript object that store 3 id's, and rewrite it on success ajax... Buy you need better repsonse then just html... Try json...
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1="+SomeJavascriptObject.id1"&id2="+SomeJavascriptObject.id2"&id3="+SomeJavascriptObject.id3"&clicked=1", function(result){
SomeJavascriptObject.id1 =result.returnedID1;
SomeJavascriptObject.id2 = result.returnedID2;
SomeJavascriptObject.id3 = result.returnedID3;
$("#meal1").html(result.html);
});
Maybe this can help you.
I have a thumbnail gallery populated from a database using php. Each thumbnail is also a link. What I would like is to be able to load an external php page in each case, with the large version of each thumbnail on it, flanked with related images.
The database tables are all set up properly in a relational sense, but I'm not sure about the functionality of being able to send data, in this case imgId, from the thumbnail gallery page, to the external page, and load the external page at the same time.
I thought it would be possible to do with a form submit, but since I need this functionality on every single thumbnail link, I thought that Ajax would work using jQuery. But alas it doesn't seem to be sending the data when I click on the link.
Hopefully someone can give me some advice. Thanks in advance.
The HTML:
<a target="_blank" href="secondary_imgs.php" class="gallery" value="16">
<img src="new_arrivals_img/thumbnails/boss-skaz1_black_front.jpg">
</a>
The jQuery:
$('.gallery').click(function(){
$.get("secondary_imgs.php", { imgId: $('.gallery').attr('value') });
});
Use $(this) inside the function to reference the clicked gallery
$('.gallery').click(function(){
$.get("secondary_imgs.php", { imgId: $(this).attr('value') });
});
Try this:
$('.gallery').click(function(){
$.get("secondary_imgs.php", { imgId: $(this).attr('value') }, function(data) {
$('body').append(data);
});
});
If that does nothing when you click on it, browse to "/secondary_imgs.php?imgID=xxx" and see if it is returning the data correctly at all.
Ok, I feel kinda stupid, but I figured out that all I needed to do was pass the data through the URL. The PHP code below shows what I mean, and I do thank those who helped me with this problem. My fault for making it faaaar more complicated than needed.
My question is however, is it safe to place data in the href as I'm showing below? I remember someone mentioning a potent ion problem concerning google spiders and the like.
The PHP:
while($row = mysql_fetch_assoc($result_pag_data)) {
echo "<a target='_blank' href='secondary_imgs.php?imgId=".$row['imgId']."'></a>";
}
I haven't started on this yet because I'm still pretty new, and I want to be sure there are not any issues with what I'm wanting to accomplish.
In it's simplest form, I want to have a div that will display a text quote that is pulled from a mySQL database. Every 5 seconds, the quote will fade out and the next will fade in.
Is ajax appropriate for this? In more detail, I would have a few functions that would:
pull the first and last name of the
user from the database
Convert that to initials: IE: Joe
Smith would become -J.S.
Pull the place from the database: IE:
Dallas, TX
Pull the quote from the database:
IE: Great Job!
Then it'd populate the div (using a fade in) with
Dallas, TX:
"Great Job!"
-J.S.
My main question is is this a good way to do this? I don't want to use flash for this task. Is there a jQuery plugin that will accomplish this?
Thanks!
This should do the trick.
nb: '#comments' is a span INSIDE your comments div.
nb: 'comments.php' should return the content laid out as you wish it to be shown.
nb: the start param would be used in the limit statement on your db query.
function comments(ccount) {
var ccount = (ccount == 'undefined' ? 1 : ccount);
$.ajax({
url: 'comments.php',
data : {'start': ccount},
success: function(data) {
$('#comments').fadeOut('slow').html(data).fadeIn('slow');
}
});
setTimeout(function(){comments(ccount+1)},5000);
}
then in your docment ready just have
comments();
I have a list of names (1-15 rows) I display from an array. I want the administrator to select the correct name from the list by clicking on the hypertext called "link." The record id is in the array and I want that passed to the called script.
I found this javascript that works except that I want the linkur.php page to print (with its information messages). I know it doesn't print because of the void(0) but can not figure the correct method needed.
<a href="javascript:void(0);" onclick='$.get("linkur.php",{ rid: "<?php echo $k['id']; ?>", uid: "<?php echo $uid; ?>", } ,function(data){ $("#link<?php echo $k['id']; ?>").html(data); });'>Link</a>
Also, is it possible to do the hyperlink with pure HTML? The hyperlink is straight forward except for passing the array values.
Thanks for any ideas.
Carl
I'm a bit confused by your request. You don't mention needing an asynchronous request, yet that is what your code is doing using the jQuery library. If you don't need an asynchronous request, and want to see the end-page, you just build a regular link:
Link
This would be rendered on the page with solid values rather than variables:
Link
Once you clicked the link, you would pass rid=123 and uid=281 to the end-script, seeing its output on the screen.
Properly Adding some Asynch'ness
If you need to load this data asynchronously, there is only a small addition to the code. Keep the original link that we just referenced above, but add a class to it:
Link
Now with jQuery we can incercept these requests and load up their HTML elsewhere:
$(function(){
// Intercept the click event of our links
$(".loadme").click(function(e){
// Prevent them from leaving the page
e.preventDefault();
// Fire off a request for their content
$.get($(this).attr("href"), function(data) {
// Load their content into a container on our page
$("#content-viewer").html(data);
}, "html");
});
});
Note that I referenced a #content-viewer. You would need to have this on your page someplace:
<div id="content-viewer">I will show the content .loadme links!</div>
Your approach is a bit hacky, to say the least. Now you need to have the javascript stuff on every link, whereas the correct way to do it would be to bind the functions separately. You could do something like this instead:
Link
Which would output to the browser as:
Link
And in a separate Javascript file:
$('a.some_links').click(function() {
$("#link"+$(this).attr('rel')).load($(this).attr('href'));
return false;
});
If I understood your code correctly, this will do the exactly same thing – loading the content from linkur.php with passed variables to #link+rid element.