将jquery变量发送回PHP并在mySQL中使用

时间:2014-02-27 17:05:07

标签: javascript php jquery mysql ajax

我是ajax中的新手,但我读到Ajax是从jQuery存储变量并将其发送回PHP以使用它的唯一方法。

正如您在本示例中所看到的,我有一个从MySQL数据库填充的下拉列表:

$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query); 

$results = mysqli_num_rows($execute);

if ($results!=0) {
    echo '<label>The galleries are: ';
    echo '<select id="galleries" name="galleries">';
    echo '<option value=""></option>';

    for ($i=0; $i<$results; $i++) {
        $row = mysqli_fetch_array($execute);
        $name = htmlspecialchars($row['galleryName']);

        echo '<option value="' .$name. '">' .$name. '</option>';
    }
   echo '</select>';
   echo '</label>';
}

使用jQuery我添加了所选属性:

$('#page').change(function(e) {
    e.preventDefault();
    var selectedOption = $(this).find('option:selected');
    $('#page option').removeAttr('selected');
    $(selectedOption).attr('selected','selected');
    var selectedOptionValue = $(selectedOption).val();
    var selectedOptionText = $(selectedOption).text();


    alert("You selected " + selectedOptionText + " Value: " + selectedOptionValue);
});

jsFiddle to see it in action

如何将所选选项存储在变量中并将其发送回PHP?从未使用过ajax,所以请尽可能详细和耐​​心! :)

3 个答案:

答案 0 :(得分:2)

我更新了你的jsfiddle

http://jsfiddle.net/sQ7Y9/2/

基本上你需要将它添加到你的代码中:

$.ajax({
      url: 'your url', //the url that you are sending data to
      type: 'POST', //the method you want to use can change to 'GET'
      data: {data : selectedOptionText}, //the data you want to send as an object , to receive in on the PHP end you would use $_POST['data']
      dataType: 'text', //your PHP can send back data using 'echo' can be HTML, JSON, or TEXT
      success: function(data){
       //do something with the returned data, either put it in html or you don't need to do anything with it
      }
});

答案 1 :(得分:2)

使用一些jquery

$.ajax({
  type: "GET",
  url: "some.php",
  data: "a="+$('#galleries option').filter(':selected').text()+"&b=someval",
  beforeSend: function() {  },
  success: function(html){ 
    $('#content').html(html);
  }
});

..和php

echo "a = ". $_GET['a'];

答案 2 :(得分:1)

如果您想在change事件上发送ajax请求,请尝试

$('#galleries').change(function() {
    var selected = $(this).val(); // getting selected value
    $.ajax({
        url: "upload.php", // url to send ajax request
        type: "POST", // request method
        data: {selected: selected}, // passing selected data
        success: function(data) { // success callback function
            alert(data); // the response data
        }
    });
});

upload.php

<?php

$selected=$_POST['selected']; //getting the selected value
//other code    
echo "your result";

?>