2014-02-27 132 views
0

我是ajax中的一個完整的新手,但我讀到Ajax是從jQuery存儲變量並將其發回PHP以使用它的唯一方法。發送jQuery變量返回到PHP並在mySQL中使用

正如你可以看到在這個例子,我有一個下拉列表從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,所以請儘可能詳細和耐​​心! :)

+0

你有什麼需要把它送回來到PHP的,到底是什麼? –

+0

添加了'selected =「selected''屬性的'option value ='。 – Mark

+0

[__learn jQuery ajax on here https://api.jquery.com/jQuery.ajax/__](https://api.jquery.com/jQuery.ajax/) –

回答

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

如果你想在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"; 

?> 
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'];