2012-06-18 34 views
0

我有以下JS代碼是不能工作:笨2.1和JQuery AJAX如預期

var forma = $('form#mali_oglas'), 
    pomoc = $('div[role=pomoc]'), 
    div = $('.mali_oglas_pomoc'), 
    input = forma.find('input, textarea'), 
    code = forma.find('#code'); 

    input.on('click', function(){ 
     var name = $(':input:focus').attr("name"); 
     pomoc.fadeOut('slow').promise().done(function(){ div.find("[data-pomoc='" + name + "']").fadeIn('slow'); });    
    }); 

    code.on('focusout', function(){ 
     console.log(code.val()); 
     $.ajax({ 
      type: 'POST', 
      url: '<?php echo base_url() ?>global_info/gi_get_ad_payment_code', 
      data: 'code=' + code.val(), 
      success: function(){ 
      for(i = 1; i<=4; i++) 
      { 
       code.after('<label for="image' + i +'">Slika</label><input type="file" name="userfile" id="image' + i +'" />'); 
      } 
      code.after('<input type="hidden" name="time" value="' + time + '"'); 
      }, 
      error: function(){ 
       alert('nije uspeh'); 
      } 
     }); /* KRAJ NA AJAX */ 
     }); 

和笨功能:

function gi_get_ad_payment_code() 
     { 
      $q = $this->db->get_where('code_payment', array('code' => $_POST['code'])); 
      if ($q->num_rows() == 0){ 
       return FALSE; 
      } else 
      { 
       return TRUE; 
      } 
     } 

問題是以下幾點:它始終是成功的,即使笨函數返回false。另外,我需要這個函數在成功時追加輸入字段一次(此時它正在追加每個焦點)。 問題在哪裏,我做錯了什麼?

+0

什麼是成功?你的意思是ajax回調'成功'?錯誤只會在HTTP錯誤(例如, 404 –

+0

是的,回調'成功'總是被激活,即使查詢中沒有結果。 – Sasha

+0

這是設計。成功意味着沒有服務器錯誤。你需要在你的回調中測試查詢成功的輸出 –

回答

1

從CodeIgniter控制器方法返回truefalse不影響返回給客戶端的內容。

相反,使用show_eror()註冊錯誤,並輸出一些別的(使用echo或更優選CodeIgniters View system)在成功的情況下;

$q = $this->db->get_where('code_payment', array('code' => $_POST['code'])); 

    if ($q->num_rows() == 0){ 
     show_error('Whoops, no results :('); 
    } else 
    { 
     echo 'Success'; 
    } 
+0

這是工作:)。但是,現在我需要解決問題的第二部分。我怎樣才能從成功回調中追加輸入字段一次? (目前它正在追加每個焦點) – Sasha

+0

我設置了標題狀態代碼400,403等。'$ this-> output-> set_status_header(code,'text');' – gorelative

0

您可以從服務器到客戶端返回多個值,和你在事件的「成功」阿賈克斯想要什麼(添加參數「數據」):

$.ajax({ 
      type: 'POST', 
      url: '<?php echo base_url() ?>global_info/gi_get_ad_payment_code', 
      data: 'code=' + code.val(), 
      success: function(data){ 
       switch(data) 
       { 
        case 'success': 
         code.after('<label for="image' + i +'">Slika</label><input type="file" name="userfile" id="image' + i +'" />'); 
         break; 

        case 'whoops': 
         // .... 
         break; 

        default: 
         code.after('<input type="hidden" name="time" value="' + time + '"'); 
         break; 
       } 
      }, 
      error: function(){ 
       alert('nije uspeh'); 
      } 
     });