Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKristian Terziev
28,449 PointsVariable From jQuery to PhP
Hello,
Here is a part of my jQuery code where i have a variable called id which is id from database.
jQuery("#result").on("click", "div", function(e){
var $name = $(this).find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
var id = $(this).data(\'id\');
});
I want to send this variable to a php document somehow called page.php
And then use it to change the src attribute of an image tag without refreshing the page. my pictures are saved with .jpg extension and are named with the number of the id. So i think the way to do this is like this:
<img src="images/<?php echo $id.'.jpg'; ?>"> But before that I have to take the id variable which is in the jQuery in the other file.
SO my question is how to send variable from Jquery to PhP and is this way of changing the image path without refreshing the page possible.
2 Answers
Gareth Borcherds
9,372 PointsYou're going to want to use some version of $.ajax http://api.jquery.com/jquery.ajax/ to get this done.
Personally when I'm trying to do something simple like this, I use $.get or $.post. I personally prefer $.post as I like to post my variables to php scripts, but that's just me, any of them will work.
So here's what it would look like using post.
$.post('http://example.com/page.php', {
id : id //We set the id to be passed to the page here
}, function(result) {
//Here is where we define what to do with the result from page.php this is where you would also change out the src of the image.
});
Gareth Borcherds
9,372 PointsYou would need to simply change the src attribute for your image. So something like
$('#image_ID').attr('src', 'put url of new source here as string or variable');
Kristian Terziev
28,449 PointsKristian Terziev
28,449 PointsHello
Thanks for the reply . I understood the code but I am not really sure how to change the scr inside this function.