Reputation: 1257
I am using JavaScript to pass a variable to another php file. I have a value in javascript, and I want to pass it as a post variable to another php file.
Javascript code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" >
//Important code here to post a variable to bh.php:
$(document).ready(function(){
$('#op_comp_id').load('bh.php').show();
$('#get_value_id').keyup(function() {
$.post('bh.php', { id: form.get_value.value },
function(result){
$('#op_comp_id').html(result).show();
});
});
});
</script>
</head>
<body>
<?$id = $_GET['id'];?>
<form name="form">
<input type="text" id="get_value_id" name="get_value" value="<?php echo $id ?>">
</input>
</form>
<div id="op_comp_id"></div>
</body>
</html>
This was my attempt to pass a variable value from javascript to bh.php
in post mode.
bh.php?id=value
Is there an alternative way or better way to do this?
Upvotes: 1
Views: 3915
Reputation: 13
You can also use hidden Inputfields with javascript. The javascript gets the value via getElementbyId and replace it with the value of a hidden input (also with getElementbyId). Then javascript automaticly submit the form with the hidden input in it (document.forms["formID"].submit();). Thats it. The Value will be send via the form method. So you can send it via post very easy.
Upvotes: 0
Reputation: 1940
Use following method to pass a JavaScript variable to php with a post:
$(input[name=get_value]).bind('keyup click blur focus change paste',function(){
var id = $(this).val();
$.ajax({
type: "POST",
url: "bh.php",
async: false,
data: "clientId="+id ,
success:function(response){
$('#op_comp_id').html(response).show();
}
});
}
bh.php use following code
<?php
$id = $_REQUEST['clientId'];
// your code
?>
Upvotes: 4