1

I'm having problem with my code below:

jquery

var data = $('thisForm').serialize();
var msg = <?php echo computeAverage(data)?>;
alert(msg);

php

function computeAverage($data){
    return $data;
}

I'm getting " data"(string) as the output and not the actual value of data. By the way, I only use one php file that contains the jquery and php function above.

Your help will be appreciated. I really need to figure this out. I'm new to jquery.

thank you for your replies. given that i need to place my php function to a separate file

jquery

var url = "myPhpFunction.php";
var data = $('thisForm').serialize();
$post(url,data, function(response)); // how can i get the reponse from my url?

php

function computeAverage($data){ // how to convert $data to an array?
     return average; // how can i return the average back to my jquery?
} 

can anyone help me? thanks

iamhealed
  • 35
  • 6

3 Answers3

1

You cann't pass the value from the javascript to PHP function as PHP execute on SERVER side and Javascript execute Clint side.

You should use the Ajax for doing such thing.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
  • thank you for the info. do i need to put my php function in a separate file? can you give me a better way on how to implement this? – iamhealed Jul 11 '13 at 13:59
  • @iamhealed in the given link in answer you can see the full code and yes, you need to put the php function in another file. – Code Lღver Jul 11 '13 at 14:00
1

PHP code is executed on the server before the client starts executing Javascript. All the code within <?php ?> are executed first.

After the PHP code has been executed, it will send output to the client which will look like:-

var data = $('thisForm').serialize();
var msg = data; // echo executed
alert(msg);

Now javascript will start executing.

The PHP will not consider javascript variable data as it is a part of client-side scripting.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
0

use $.post for sending data to your php script!

<script type="text/javascript">
     $(document).ready(function () {

        $("#autocomplete").keyup(function(e){
            var form = $("#autocomplete");
            var data = form.serialize();
            $.post("ajax_form.php", data, function(response) {
                $( "#autocomplete" ).autocomplete({
                    source: response
                })
            })   
        })
     })             

</script>

html part:

 <input class="formfeld" id="autocomplete" name="suchfeld" title="type &quot;a&quot;">
arnisz
  • 175
  • 3
  • 8
  • why d o i need the input? – iamhealed Jul 11 '13 at 14:32
  • well, you can serialize anything you want - you did not specify where your data comes from. In my example the input field contains the entries by the user. They are seralized and send by post to the php-script and the response from php script comes back as json... – arnisz Jul 12 '13 at 09:10