Reputation: 87
Ok so I have a link created with JS:
var content = document.getElementById("Profile");
var entry = document.createElement('li');
entry.innerHTML= ' <a href="eventList2.html" onclick ="post()"> Click Me </a>';
content.appendChild(entry);
function post(){
$.post( "random.php", { variable: "hello"} );
}
And in my PHP:
random.php
<?php
Header("content-type: application/x-javascript");
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$variable = $_POST['variable'];
echo"alert($variable);";
?>
"undefined" gets echoed instead of "hello". Could anybody tell me what I'm doing wrong? I'm not too familiar with AJAX and Jquery, I'm just going by whatever I see in tutorials and examples. Thanks
Upvotes: 0
Views: 92
Reputation: 737
Why have PHP return an alert? This is a bad approach. Let PHP return the json encoded result and have jquery handle the alert. This is one possible way to achieve this:
$.post( "random.php", { variable: "hello"}, function(data) {
alert(data);
});
PHP:
<?php
Header("content-type: application/x-javascript");
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$variable = $_POST['variable'];
echo json_encode($variable);
?>
Upvotes: 1
Reputation: 780724
Change:
echo"alert($variable);";
to:
$js = json_encode($variable);
echo "alert($js);";
This will put the contents of $variable
into the proper format for a Javscript literal.
Upvotes: 0