简体   繁体   中英

how do i send javascript variables to PHP and return the results

I have a form with inputs (each with ID param , param1 , param3 respectively) and an external php file with a function called getform() that takes three parameters from the form ( param , param1 , param3 respectively).

A text feild with id results to display the response from php file.
I have placed onclick function on param3 .

I need whenever a user types something in param3 it should be sent to php file and the results displayed in the text filed of id results .

here is my code

<script>
  function post(){
    var param = $('#param').val();
    var param2 = $('#param2').val();
    var param3 = $('#param3').val();
    $.post('curencyconvert.php', {
      postparam: param,
      postparam2: param2,
      postparam3:param3
    }, function(data){
      $('#results').html(data);
    });
  }
</script>

my php function in the php file

function Conv($param,$param2,$param3){
    //my code here
    return $output;
}
if(isset($_POST)){
//Calling the defined function here
Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}

Add these line below your function code.. and better echo the output in your function instead of returning it.

 jQuery(document).ready(function($) { $('#param3').change(function() { // put here the code // } ); }) 

What errors you get in Console(firbug)?

As stated by other answers $_POST should be used.

What your php code returns if it returns an array or returns an object It can not be put into the Input. Return value must be a string

PHP code must be :

      function Conv($param,$param2,$param3){
        //my code here
          // take particular field of the DB results or resultset that you want to show in the input.
            return $output['name'];

        }

I know answer is incomplete because your question is incomplete. Please let me know errors from the console so that i can help you further

echo instead of return.

if(isset($_POST)){
  echo Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}

Do something like this, it is more clean:

Conv($param, $param2, $param3){
   // your code here
   return $output;
}

As for the javascript part, jquery ajax is your friend

 function post(){

    var param = $('#param').val();
    var param2 = $('#param2').val();
    var param3 = $('#param3').val();

    $.ajax({
        url: '/path/to/file',
        type: 'POST',
        data : { postparam: param, postparam2: param2, postparam3: param3 },     
    }).done(function(data) {
          $('#results').html(data);
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM