Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  178] [ 4]  / answers: 1 / hits: 21046  / 11 Years ago, mon, april 1, 2013, 12:00:00

I created a script to read a hash (www.website.com/#hash) and pass the hash in to php.
The alert(hash) pops up with the hash value, but the hash is not being echoed out in the post variable. Any idea why?



jQuery page



<script>
var hash = location.hash;
$.post(community.php, {
hash: hash
});
alert(hash);
</script>


Community.php page



<?php echo $_POST['hash']; ?>







Edits - $_GET below was originally $_POST above.




I have a foreach that is looping through postings (posting IDs) in a function. I need to pass the HASH into the function and compare it to the posting IDs everytime. Only problem is, the $_GET['hash'] will not show up inside the function.



function something() {
echo $_GET['hash'];
}

More From » php

 Answers
5

$.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



<?php
if($isset($_POST[hash]) && strlen(trim($_POST[hash])) > 0){
echo Hash found :: . $_POST[hash];
}else
echo 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.


[#79197] Saturday, March 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxh

Total Points: 137
Total Questions: 100
Total Answers: 103

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
maxh questions
Tue, May 18, 21, 00:00, 3 Years ago
Mon, Jan 4, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;