doushuo1080 2015-01-07 21:28
浏览 56
已采纳

Ajax上的分析器错误

I'm trying to confirm the insert to a DB and return a Json if success, and if it fails catch the error and send the exception message.

The PHP inserts the info in to the data base but for some reason the javascript is returning an error even when the data is inserted correctly.

In the response text when the info is inserted I receive a NULL value = "" but when it fails ib the insertion it works fine and catch the error. and always receive this error: "Error. Parsing JSON Request failed."

Here is the PHP:

<?php
//Cargar coneccion a BD:
  require_once '../db/db_config.php';
//Validacion de Datos:
if (is_ajax()) {
  if (isset($_POST["param1"]) && !empty($_POST["param1"])) { //verificar si param1 existe y tiene valor
    $tipo = $_POST["param1"];    
          if (isset($_POST["param2"]) && !empty($_POST["param2"])) { //verificar si param2 existe y tiene valor
        $lista = $_POST["param2"];

        insertarUsr($tipo,$handler,$lista);
    }
  }
}
//Funcion para verifica si el request  en un tipo Ajax rquest
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function insertarUsr($tipo, $h, $lista){
    $nomre      =$lista[0];
    $apellido   =$lista[1];
    $email      =$lista[2]; 
    $password   =$lista[3];
 try {
    $sql = "CALL proc_create_user(:tipo, :nomre, :apellido, :email, :password)";
        $handler = $h;
         $stm = $handler->prepare($sql); // preparar statments
         $stm->bindParam(':tipo', $tipo, PDO::PARAM_INT);
         $stm->bindParam(':nomre', $nomre, PDO::PARAM_STR, 4000);
         $stm->bindParam(':apellido', $apellido, PDO::PARAM_STR, 4000);
         $stm->bindParam(':email', $email, PDO::PARAM_STR, 4000);
         $stm->bindParam(':password', $password, PDO::PARAM_STR, 4000);
         if($stm -> execute()){     
                    header('Content-type: application/json');
                     echo json_encode(array(
                        'Status' => 'Success'
                        ));}

    } catch (Exception $e) {
        //echo "Error occurred:" . $pe->getMessage();
       die( "Ocurrio un Error:" . "'".(string)$e->getMessage()."'");
    }
}

?>

This is the JS

function addNewUsr(tipo, arreglo){
 var datos = {param1: tipo, param2: arreglo};

 $.ajax({
      url: "resources/includes/control/create_user.php",
      type: "POST",
      data: datos,
      contentType: "application/x-www-form-urlencoded; charset=UTF-8",
      dataType: "json",
      error:function(x,e){
            if(x.status==0){
                alert('You are offline!!
 Please Check Your Network.');
            }else if(x.status==404){
                alert('Requested URL not found.');
            }else if(x.status==500){
                alert('Internel Server Error.');
            }else if(e=='parsererror'){
                alert('Error.
Parsing JSON Request failed.');
                console.log(e);
                console.log(x);
            }else if(e=='timeout'){
                alert('Request Time out.');
            }else {
                alert('Unknow Error.
'+x.responseText);
            }
        }
      }).done(function(data, textStatus, jqXHR) {
           alert('Yey it worked!!')
          clearChildren(document.getElementById('frmUser'));
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            jqXHR.errorThrown = errorThrown;
            var message = jqXHR.responseText
            message = message.replace("Error occurred:'SQLSTATE[45000]: <<Unknown error>>", 'Error')
            alert('Ocurrio un Error

'+message);
        })
        .always(function() {
        }); 

  return 1;

}

Edit: this is the Headers I see from google Crhome Dev Tools:

Remote Address:XXX.XXX.XXX.XXX
Request URL:http://someserver/vek/resources/includes/control/create_user.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:102
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://someserver
Pragma:no-cache
Referer:http://someserver/vek/keyuser.php
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
param1:2
param2[]:asd
param2[]:f
param2[]:sdfsdfeagv@somemail.com
param2[]:sdfvdzfv_sfd
Response Headersview source
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Fri, 09 Jan 2015 23:09:41 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12
  • 写回答

1条回答 默认 最新

  • doujiao4705 2015-02-18 15:57
    关注

    I was able to resolve this by placing the header at the top of the PHP file:

    <?php
    header('Content-type: application/json');
    //
    // rest of the code...
    

    This returned the query result and echoed a correctly formatted Json

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题