简体   繁体   中英

How to pass value to JS function and, then, to PHP script

I want to show the result of PHP script on div tag without page refresh. I have a list of .c files (the users can compile them on server)...

<option value="" selected="selected">Choose file </option>';

                    $dirPath = dir('directoryExample');
                    while (($file = $dirPath->read()) !== false)
                        {
                            if ($file == '.' || $file == '..') continue;
                            echo "<option value=\"" . trim($file) . "\">" . $file . "\n";
                        }
                    $dirPath->close();
                    echo '</select>

...and two div and button like this:

<div id="2" style="display:none;">  </div>
<div id="1" style="display:visible;"> Compile...</div>
<button type="button" onclick="codiad.ccomp.compile(this.value);">Compile</button>

First question: How can I pass selected file to JQuery function? this.value works fine?

This is the Jquery function:

compile: function(value) {

            if(($('#1').css('display')!='none')){
                    $('#2').load(this.path+'\compile.php').show().siblings('div').hide();
            }else if($('#2').css('display')!='none'){
                    $('#1').show().siblings('div').hide();
                }

    }

The code works fine but this is second question: how can I pass now the value to php page?

Thanks in advance!

You can pass a data argument to .load() .

$('#2').load(this.path+'/compile.php', { file: $("#selectID").val() })
    .show().siblings('div').hide();

In the PHP script, use $_GET['file'] to get the selected filename.

I don't think that in your first question this.value will work fine as this refers to the button, not the select element.

Instead you would need something like:

$('#your_select_element').val();

And you can remove the inline javascript and use something like:

$('button').on('click', function() {
  // do something with `$('#your_select_element').val();`
  ...
}

Assuming there is one button, you might need to add a class or ID to address it specifically.

And as mentioned in the other answer, you can add a data parameter to your .load() function.

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