I have many items, I want to post the specific item information after click using ajax. Usually I store its information by attribute data-name, data-date, etc. I use jquery to get it by .attr()
. I do not know how to do it if the text is too long or if each item has an array of text {"Text1", "Text2","Text3"...."Text20"}
. I can not store it as an attribute. I can not figure out where to put it or how & how to get by jQuery?
my Items look very simple like this
<div class="item">
<a data-name="item1" data-available="1" data-color="blue">Item1</a>
</div>
<div class="item">
<a data-name="item2" data-available="1" data-color="pink">Item2</a>
</div>
This is my jquery
jQuery(".item a").on('click', function () {
var url = "/test.php";
var item_name = jQuery(this).attr("data-name");
jQuery("#display").html("<img id='loading_gif' src='/loading.gif'>");
jQuery("#display").load(url,{item_name:item_name});
return false;
});
1 Answer 1
You can send json data to your php file using ajax,
jQuery(".item a").on('click', function () {
var available = $(this).attr("data-available"),
color = $(this).attr("data-color");
$.ajax({
url: 'url_to_your_phpfile.php',
type: 'post',
data: {
avail: available,
color: color
},
success: function (data){
console.log(data); // do something
}
});
}
And in your PHP file, you can fetch the variable by simply using $_POST['avail']
and $_POST['color']
EDIT
Since you want to access your data from php to your javascript, you can store that to a javascript variable, for example
<?php
$products = array(
array("id" => 1, "name" => "Item 1", "color" => "red", "desc" => "some large text..."),
array("id" => 2, "name" => "Item 2", "color" => "blue", "desc" => "some large text...")
);
echo '<script>var products = '.json_encode($products).'</script>';
// and then display
foreach($products as $product):
echo '<div class="item"><a data-id="'.$product->id.'" data-color="'.$product->color.'">'.$product->name.'</a></div>';
endforeach;
And I assume your javascript file will always be on the footer area of your page so, you can always call the products
variable on your javascript code.
In your JS, you can always add a custom function to find your product by its ID
function findProduct(id){
var product = products.filter(function (product){
if(product.id == id){
return product;
}
});
return products.length > 0 ? products[0] : product;
}
$('.item a').on('click', function () {
// get the id
var id = $(this).attr("data-id");
// now, make a function that finds other data for that product with that ID
var product = findProduct(id); // finds a product from variable products
// product variable will now contain id, name, color, desc and
// can be accessed directly with product.id, product.desc, etc.
});
2 Comments
a
tag besides the id
or any unique identifier you use.
<input type="hidden"/>
to store the value