2017-10-17 107 views
1

我在做一個應用程序的網絡的一所學校,並試圖編輯一個學生,當我卡住了。我希望用戶點擊該行的具體學生,然後用他的數據打開一個表單。阿賈克斯parsererror用JSON在WordPress的

我必須做一個Ajax請求,所以我可以叫我的PHP函數(一個,這使得我的數據庫查詢)並在窗體加載數據。這是一個Ajax請求我的jQuery代碼:

//When you click in the table students, in some element whose class is edit ... 
    $("#tblAlumnos").on("click", ".editar", function(event) { 

    var rowID = $(this).parents('tr').attr('id'); 

    $.ajax({ 
     type: 'POST', 
     url: '../ajax/', 
     data: {'table': 'alumnos', 'action': 'carga', 'ids': rowID}, 
     dataType: 'json', 
     success: function(result) { 

      console.log(result.nombre); 

     }, 

     error: function (jqXHR, exception) { 
      if (jqXHR.status === 0) { 
       alert('Not connect.\n Verify Network.'); 
      } else if (jqXHR.status == 404) { 
       alert('Requested page not found. [404]'); 
      } else if (jqXHR.status == 500) { 
       alert('Internal Server Error [500].'); 
      } else if (exception === 'parsererror') { 
       alert('Requested JSON parse failed.'); 
       alert(jqXHR.status); 
       alert(jqXHR); 
      } else if (exception === 'timeout') { 
       alert('Time out error.'); 
      } else if (exception === 'abort') { 
       alert('Ajax request aborted.'); 
      } else { 
       alert('Uncaught Error.\n' + jqXHR.responseText); 
      } 
     } 
    }); 

}); 

Ajax請求調用從我的數據庫中的數據的方法:

function cargaAlumno($ids) { 

     require 'db.php'; 

     $sql = "SELECT * FROM Alumnos WHERE ID=$ids"; 
     $result = $conexion->query($sql); 


     if ($result->num_rows > 0) { 

      $row = $result -> fetch_assoc(); 

      $nombre = $row['Nombre']; 
      $apellidos = $row['Apellidos']; 
      $telefono = $row['Telefono']; 
      $usuario = $row['Usuario']; 
      $contrasena = $row['Contrasena']; 

      $result = array(); 
      $result["nombre"] = $nombre; 
      $result["apellidos"] = $apellidos; 
      $result["telefono"] = $telefono; 
      $result["usuario"] = $usuario; 
      $result["contrasena"] = $contrasena; 

      ChromePhp::warn($result); 
      ChromePhp::warn(json_encode($result)); 
      echo json_encode($result); 

     } 

    } 

這種方法有一個JSON返回Ajax請求,但由於錯誤:parsererror,永遠不會達到成功方法。

我試着數據類型:「JSON」(這是當我有錯誤),沒有它(它認爲它的HTML)。我也嘗試過使用和不使用contentType,在我的php:header('Content-type:application/json; charset = utf-8')。

我的JSON編碼看起來像這樣:

{"nombre":"Susana","telefono":"56765336","usuario":"susa"} 

我不知道如果我需要一些更多的方法,因爲我在WordPress的做或者我有什麼錯我的代碼。

任何幫助,將不勝感激。預先感謝您:)

+0

你有什麼錯誤? –

+0

parsererror當ajax請求獲取我的PHP函數的響應@SubhashShipu –

回答

0

如果您在WordPress的做,我會使用內置的wpdb來處理數據庫連接和結果。像這樣:

function cargaAlumno() { 

    global $wpdb; 
    $ids = $_POST['ids']; 

    $sql = $wpdb->get_results( 
     $wpdb->prepare(" 
     SELECT * 
     FROM Alumnos 
     WHERE id = '$ids' 
     ") 
    ); 

    echo json_encode($sql); 

    exit(); 

    } 

還記得這進入你的主題functions.php文件。

記住它掛接到wp_ajax鉤:

add_action('wp_ajax_nopriv_cargaAlumno', 'cargaAlumno'); 
add_action('wp_ajax_cargaAlumno', 'cargaAlumno'); 

然後在你的Ajax:需要

$("#tblAlumnos").on("click", ".editar", function(event) { 

    var rowID = $(this).parents('tr').attr('id'); 

    $.ajax({ 
     type: 'POST', 
     url: ajaxurl, //this is a wordpress ajaxurl hook 
     data: {'table': 'alumnos', 'action': 'cargaAlumno', 'ids': rowID}, // You didn't use the correct action name, it's your function name i.e. cargaAlumno 
     //dataType: 'json', dont need this 
     success: function(result) { 
      //Parse the data 
      var obj = jQuery.parseJSON(result); 
      console.log(obj[0].nombre); // I'm guessing nombre is your db column name 

     }, 

     error: function (jqXHR, exception) { 
      if (jqXHR.status === 0) { 
       alert('Not connect.\n Verify Network.'); 
      } else if (jqXHR.status == 404) { 
       alert('Requested page not found. [404]'); 
      } else if (jqXHR.status == 500) { 
       alert('Internal Server Error [500].'); 
      } else if (exception === 'parsererror') { 
       alert('Requested JSON parse failed.'); 
       alert(jqXHR.status); 
       alert(jqXHR); 
      } else if (exception === 'timeout') { 
       alert('Time out error.'); 
      } else if (exception === 'abort') { 
       alert('Ajax request aborted.'); 
      } else { 
       alert('Uncaught Error.\n' + jqXHR.responseText); 
      } 
     } 
    }); 

}); 

這個js文件添加到您的主題,結合工作與返工以上()函數

讓我知道你是否需要再幫助或有任何其他問題。

+0

非常感謝,我現在明白我的函數必須位於functions.php中,並且我必須將其名稱放在action中,但結果是同樣的: - 如果我有行dataType:'json'有一個狀態200的解析錯誤 - 如果我沒有它的結果它是html,我有以下錯誤:Uncaught SyntaxError:意外的標記<在JSON中位置0 我不知道問題出在哪裏,因爲我認爲由我的函數返回的json有一個有效的結構,但ajax不會將其識別爲json。你有什麼想法爲什麼這會繼續發生? –

+0

這很奇怪。您是否有適合該網站的重定向?例如,如果未登錄,則重定向到登錄頁面。或者如果用戶不允許他們在儀表板中? – designtocode

+0

如果用戶已經登錄,並且他沒有將他重定向到我的.php類的begginig中的錯誤頁面,但我沒有在functions.php或my.php中找到它,我有session_start()來cckck。 js –

0

不知道如果你只提供代碼的特定行或者這是整個事情,反正這肯定是不應該如何處理WordPress的AJAX請求:

  • 您應該使用wp_ajax_對於需要身份驗證或wp_ajax_nopriv_對於那些行爲是不
  • 您應該創建此功能的作用,並通過使用admin-ajax.phpadmin_url()
  • 你應該defin發送請求itely使用wp_create_nonce()安全通過創建隨機數您的要求和使用wp_verify_nonce()
  • 驗證您應該限制你的AJAX文件的直接訪問,同時檢查$_SERVER['HTTP_X_REQUESTED_WITH']

沒有必要要求db.php中,因爲你已經中工作functions.php和db連接已經建立。

使用下面的方法來代替:

global $wpdb; 
$query = "SELECT * FROM table_name"; 
$query_results = $wpdb->get_results($query); 

把它包起來,請按照下面的結構:

前端(PHP文件):

<?php 
$ajax_nonce = wp_create_nonce("change_to_action_name"); 
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce); 
?> 
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a> 
<input id="param" value="" /> 

腳本文件(js文件):

$('.do_ajax').click(function() { 
     var ajax_link = $(this).attr('data-ajax_link'); 
     var param = $(this).attr('data-ajax_param'); 

     if (ajax_link && param) { 
      $.ajax({ 
       type: "post", 
       dataType: "json", 
       url: ajax_link, 
       data: { 
        param: param, 
       }, 
       success: function (response) { 
        if (response.type == "success") { 

        /*Get/updated returned vals from ajax*/ 
        $('#param').val(response.new_param); 
         console.log('ajax was successful'); 

        } else if (response.type == "error") { 
         console.log('ajax request had errors'); 
        }else{ 
         console.log('ajax request had errors'); 
        } 
       } 
      }); 
     } else { 
      console.log('ajax not sent'); 
     } 
    }); 

功能文件(的functions.php文件):

add_action("wp_ajax_change_to_action_name", "change_to_action_name"); 
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name"); 
function change_to_action_name() 
{ 
    if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) { 
     exit("You think you are smart?"); 
    } 

    $param = $_REQUEST['param']; 

    /*php actions goes here*/ 
    $actions_success=0; 
    if($actions_success){ 

    /*Query db and update vals here*/ 

     $new_param = "new_val"; 
     $result['new_param'] = $new_param; 
     $result['type'] = "success"; 

    }else{ 
     $result['type'] = "error"; 
    } 

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 
     $result = json_encode($result); 
     echo $result; 
    } else { 
     header("Location: " . $_SERVER["HTTP_REFERER"]); 
    } 
    die(); 
} 

您當前的代碼包含了很多安全缺陷,所以它是非常建議您更新,並使用上述方法。

乾杯!

+0

據我所知,'$ wpdb-> prepare'處理安全性。什麼是'$ actions_success'? – designtocode

+0

$ actions_success是一個標誌,應該設置爲1,只要某個特定功能成功就能夠使用$ result ['type']發送相關響應,這只是一個演示。此外,'$ wpdb-> prepare'處理數據庫查詢的安全性(無論如何都是最佳實踐),並且與上面示例中解釋的AJAX安全性無關。 – Marounm