I have a requirement to pass the JavaScript object to a PHP file and load that PHP file in browser when a button is clicked.
index.html has the following code:
<button id="1a" type="button">Click here</button>
custom.js has the following code:
var testobject={'element1':1, 'element2':2}
$(document).ready(function() {
$("#123456").click(function(event){
$.post(
"test.php",
testobject
);
});
But I don't know to write a php file to receive this data. Also I am not able to understand how to load this PHP file.
You need to make sure your click event is actually tied to the button using the correct ID, so
$("#1a").click(...);
in this case. Once you have that, clicking the button will cause a POST to happen to the PHP file, this is where it will load. You can then access those variables in the most simple way like:
<?php
$element1 = $_POST["element1"];
$element2 = $_POST["element2"];
?>
as the other answer implies.
In test.php you can access those variables like so:
<?php
$element1 = $_POST["element1"];
$element2 = $_POST["element2"];
echo "data loaded with ajax: " . $element1 . " and " . $element2;
?>
you can then manipulate the data and get the info back to the page with the success callback:
<div class="ajaxtarget"></div>
$("#1a").click(function(event){
$.post( "test.php", testobject,function(data){
//here, data is the data returned by test.php
// if you want to show that content you need a target div to choose where to load it
$(".ajaxtarget").html(data);
});
});
The same without ajax would be:
<form method="POST" action="test.php">
<input type="hidden" name="element1" value="valueyouwant">
<input type="hidden" name="element2" value="valueyouwantforel2">
<button id="submit" name="submit">Send</button>
</form>