2011-01-27 98 views
0

我需要發佈一個變量並使用Ajax jQuery在Codeigniter中獲取結果。Codeigniter - 發佈表單變量並通過jQuery檢索AJAX

雖然我的db有內容,但代碼仍然返回空數組。 - array(0){}。 問題是該變量沒有從窗體中發佈。這裏是我的代碼:

表單代碼 - 景觀:

<form id = "myform1" onsubmit="return false"> 
<select name="field_country"> 
<option value="0">Argentina</option> 
<option value="1">Chile</option> 
</select> 
</form> 

使用Javascript - 內嵌鑑於

jQuery(document).ready(function($){ 
$("select[name='field_country']").change(function(){ 
    var country_name= $("select[name='field_country'] option:selected").text(); 
    $.post("<?= base_url(); ?>index.php/catalog/getCities/", {country:country_name}, function(data){ 
    alert(data); 
    }) 
}) 
}) 

catalog.php控制器 - 功能:

function getCities(){ 
$country_name = $this->input->post('country', 'Argentina'); 
$result = $this->catalog_model->getCitiesNames($country_name); 
var_dump($result); 
} 

catalog_model型號功能:

function getCitiesNames($country_name) { 
$cities=array(); 
$result = $this->db->query("SELECT title FROM cities WHERE country = '".$country_name."'"); 
foreach ($result->result() as $row) { 
    array_push($cities, $row->title); 
} 
return $cities; 
} 

回答

2

你需要做一個小的修改,以你的Javascript和控制器代碼。爲了Javascript和PHP彼此之間進行通信,您必須告訴這兩段代碼使用什麼格式來傳輸信息。最簡單和常見的格式是JSON。因此您需要修改您的代碼以發送和接收JSON。

表單視圖

<form id="myform1" onsubmit="return false"> 
    <select id='country' name="field_country"> 
     <option value="0">Argentina</option> 
     <option value="1">Chile</option> 
    </select> 
</form> 

我增加了一個id='country'select更容易達到。

JAVASCRIPT

$(document).ready(function(){ 
    // When the SELECT is changed 
    $("#myform1 #country").change(function(){ 

    var country_name= $(this).find("option:selected").text(); 
    $.post ("<?= base_url(); ?>index.php/catalog/getCities/", 
      { country:country_name }, 
      function(data){ 
       ...on success do something here 
      }, 
      'json' 
    ); 

}); 

});

你需要告訴Javascript你期待着一個JSON對象回來。

控制器

function getCities(){ 
    $country_name = $this->input->post('country'); 
    $result = $this->catalog_model->getCitiesNames($country_name); 

    echo json_encode($result); 
} 

你的PHP代碼,然後應返回一個JSON對象。

+0

非常感謝。我解決了這個問題,問題不在返回變量。問題在於變量用於在發佈時被破壞。我通過將post uri更改爲「getCities」而不是絕對路徑,找到了解決方案。我使用多語言的uri標識符,所以我懷疑它可能會干擾,因爲該應用程序看起來像自動生成2個數據請求(1個POST和1個GET)。但現在解決了它,謝謝。 – Cruising2hell 2011-01-27 21:07:16

0
jQuery(document).ready(function($){ 
$("select[name='field_country']").change(function(){ 
    var country_name= $("select[name='field_country'] option:selected").text(); 
    $.ajax({ 
    type: "POST", 
    url: "<?= base_url(); ?>index.php/catalog/getCities/", 
    data: "country="+country_name, 
    success: function(data){ 
      alert(data); 
     } 
    }); 
    }); 
});