Q:
How to use variables as strings in jquery
In short:
Why does this string not find the right div?
var myURL = 'index2.php?pid=' + $(this).parent().find('.parentdiv').attr('id');
$(myURL).load(function(){
var somecontent = $(myURL);
$('.childdiv').html(somecontent);
});
I'm using jquery.
(this).parent().find('.parentdiv').attr('id'); will be always different for every single row in the table.
What's in index2.php?pid= is the same as parentdiv1, parentdiv2, parentdiv3 etc.
So how do I do this?
Please help me, I would be very grateful.
Thank you in advance!
EDIT:
I would like to be able to take myURL, place it into an object and then load it into a different div.
A:
You can use
$('#output').load('myurl/');
or
$('#output').load('/myurl/');
To load it to an specific id. And also, you should not use parent(this).parent().find('.parentdiv') in every row. That will cause a problem.
Try this:
HTML
JS
$('#output').load('/get.php?p=1'); //to just show 1st result (random value)
function loadURL(element) {
var p = element.parent().find('.parentdiv').attr('id');
//var newPath = 'get.php?p=' + p;
var newPath = '/get.php?p=' + p;
$(newPath).load(function () {
$('#output').load(newPath);
});
}
$(".parentdiv").on("click", function () {
var row = $(this).parent().index();
loadURL(row);
});
check working example in this fiddle.
Another way, I think this is also suitable to your situation:
JQuery
$(function () {
var base = '/get.php?pid=';
$('a.edit_link').click(function () {
var link = $(this).attr('href');
var pid = link.substring(link.indexOf('=') + 1, link.indexOf('&'));
//pid = link.substring(link.indexOf('=') + 1, link.indexOf('&') + 1);
$(base + pid).load(function () {
$(this).load('/page_action.php');
});
return false;
});
});
check this fiddle.
A:
Using PHP:
Edit this item';
// item 2
echo '
Edit this item';
?>
Then in jQuery you would simply look for the
tag and not worry about a specific ID in the li. For example, if you wanted to find the item with a pid of 1:
$(function () {
$("a.edit_link").live("click", function () {
var link = $(this);
var pid = link.attr("href").replace("pid=1", "");
var somecontent = $(pid);
$("#somewhere-else").html(somecontent);
});
});
Check out the jQuery Event Documentation
A:
jQuery is really for manipulating and inserting data, not simply displaying data.
Javascript has native ajax functionality, which would be my suggestion:
http://api.jquery.com/jQuery.ajax/
Example:
function data(pid) {
return '/get.php?pid=' + pid;
}
function loadData(target) {
target.load(data(pid));
}