1

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?

2
  • @hRaval Yes the the url should be bh.php?id=value Commented Jun 18, 2012 at 6:49
  • If you will use keyup event after every keypress for letter ajax will be called. You can also use blur event. Commented Jun 18, 2012 at 6:50

2 Answers 2

4

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
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for reply ... is there a way i can use it in hidden field of form ... where value comes from variable<input type="hidden" id="get_value_id" name="get_value" value="<?$echo $id?>"></input>
@Harinder yes you can , simple don't use id , use "name"$(input[name=textboxname])" so you can use in any textbox , and there is no need"</input>" tag
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.