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 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line