dongren4099 2014-02-27 17:05
浏览 33
已采纳

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

I am a complete newbie in ajax, but I read that Ajax is the only way to store a variable from jQuery and send it back to PHP to use it.

As you can see in this example, I have a drop down list populate from a MySQL database:

$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>';
}

With jQuery I add the selected attribute:

$('#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

How can I store the selected option in a variable and send it back to PHP? Never used ajax, so please be as much detailed as possible and patience! :)

  • 写回答

3条回答 默认 最新

  • dongzhi5587 2014-02-27 17:15
    关注

    I updated your jsfiddle

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

    basically you would need to add this to your code:

    $.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
          }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改