Pass Variable From Jquery To Php
Solution 1:
use ajax like this, send the value in hash
function send_hash(hash) {
$.ajax({
url : "community.php",
type : "POST",
cache : false,
data : {
hash : hash
}
});
}
now u will get
<?phpecho$_POST['hash']; ?>
Solution 2:
<script>var hash = location.hash;
$.post("community.php", {
hash: hash
}, function(responde){ alert(responde); });
</script>
To check what your PHP response :)
Solution 3:
$.post is an ajax event. You are posting data by ajax so by that the page doesn't go to the communitypage.php. For the behaviour you want you have to do normal form post and not ajax post. $.post will retrive anything you echo on communitypage.php using this code.
//Note the 3rd argument is a callback.var hash = location.hash;
$.post('communitypage.php',{hash:hash},function(data){
alert(data);
});
Process hash on that page and alert something if u find the hash. You'd find the echo in the data
You could mod the communitypage.php
to return html as below
<?phpif($isset($_POST["hash"]) && strlen(trim($_POST["hash"])) > 0){
echo"Hash found :: " . $_POST["hash"];
}elseecho"No hash found";
?>
Note this will return html you can modify the response to return xml, json as per your needs.
Refer jQuery post() documentation for more info.
For the updated question
It works outside because it is called when the ajax call is made inside a function it won't because the function is not called. If you want to do that (and i don't know why) u can do like this.
function myfunction(){
//your code goes here
}
myfunction(); //call the function so that the code in the function is called upon
Though that's an overkill unless u want to call the function over and over in the same script. If it works without a function you should do it that way.
Solution 4:
<script>var hash = location.hash;
//Try this.window.location.href = 'community.php?val='+hash;
</script>
OR
<script>
$.post("community.php","val="+hash);
</script>
In community.php
$res=isset($_REQUEST['val'])?$_REQUEST['val']:'';
hope it will give you some solution.
Solution 5:
but the hash is not being echoed out in the post variable
This is because if you want to send it when page loads then you have to use this in doc ready
handler:
<script>
$(function(){
var hash = location.hash;
$.post("community.php", { hash: hash });
alert(hash);
});
</script>
Post a Comment for "Pass Variable From Jquery To Php"