I am trying to call a javascript function from php code, which it will receive a php variable from an input form. Once Javascript function received this variable or value it will call a php (search.php file) to make a query and other jobs.
PHP code:
<?
I need to call search function in php passing the $_POST Global variable value :
something like this: <script> search($_POST) ; </script>
?>
Javascript file name: call_search.js:
function search($_POST or variable) {
var search_query = $(this).val();
$.post('search.php', {search_query : search_query}, function(searchq) {
$('#search_query').html(searchq);
});
}
Nota: search.php is another php file doing mysql query and others jobs which it send back the result: MySQL query back to Javascript function.
Any help ..Please.!! Thank you very much.
6 Answers 6
Something like this should work:
<script type="text/javascript">
search(<?php echo $_POST; ?>);
</script>
However, note that it's probably a bad way to pass variables - try looking into Javascript frameworks and retrieving any information you need through a RESTful API on the backend.
Comments
For JS arguments you can send Object.. Use json_encode in PHP
echo '<script>';
echo 'search('.json_encode($_POST).')';
echo '</script>';
in JS:
function search(obj) {
console.log(obj);
}
Comments
You are doing it wrong or I did not understand what exactly you are doing.
Give the search field an id (searchInput) and get the value in jQuery and from there send it to php to recive an response.
function search() {
var search_query = $('#searchInput').val();
$.post('search.php', {search_query : search_query}, function(searchq) {
$('#search_query').html(searchq);
});
}
Hope this helps. Good luck young padawan and may the source be with you.
3 Comments
If you add the java script to your code
echo "<script src=\"call_search.js\"></script>";
and echo this as an event in your php it will work:
echo "<body onLoad=\"search($param)\">";
or
echo "<script> search($param) </script>";
it will load when the page is loaded.
Comments
If i have understand your question, the form must have a simple button rather than submit button, and juste use serialize() to get all form data by id
$.post('search.php', $('#IDform').serialize())
You Will find more details here
Comments
You could also take a look at SpiderMonkey. Its a javascript engine for PHP which has the facility to let you access PHP variables and classes from Javascript. I agree with Jeroen, though. Its probably not the best solution in the long run.