I'm attempting to send a piece of data through jQuery .ajax() to a PHP script which will then be loaded into a div container. The PHP script will then run with this piece of data and its contents will be returned into the aforementioned div container.
Initially, I wrote this piece of code (shown below) which successfully added the correct elements upon a click but wasn't able to name them correctly because it didn't doesn't pass the count_bucket variable to the PHP.
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP));
return false;
});
I then altered the code to this (shown below) in attempt to pass the count_bucket variable to the PHP script.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.ajax ({
type: "GET",
url: "create_new_bucket.php",
data: var count_bucket,
dataType: "json",
async: false,
}).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
The PHP file create_new_bucket.php looks like this:
<?php
include_once "test_functions.php"; // include functions page
$i = $_GET["count_bucket"];
drawBunchNew($i);
?>
I'm unclear which aspect of the .ajax() is incorrect. I suspect I'm not collecting the variable correctly in the PHP or I'm using the incorrect syntax to pass it to the PHP file. If anyone could help me identify the error, I would greatly appreciate it.
*UPDATE******
Thanks Tejs & Tandu. I'm clear on how to structure the data now but I still am having trouble getting the whole bit of jQuery to work. I took Tandu's suggestion to use .load() instead and have changed my PHP to use POST to pull the data but it's still not working correctly.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.load ("create_new_bucket.php", {count_bucket: count_bucket}, }).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
And the PHP is:
<?php
include_once "test_functions.php"; // include functions page
$i = $_POST["count_bucket"];
drawBunchNew($i);
?>
Final working jquery I used (final PHP is same as above):
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP, {count_bucket: count_bucket}));
return false;
});