我的AJAX函数正常工作,但有时我得到一个未定义的JSON对象

时间:2014-07-03 08:52:39

标签: javascript php jquery ajax json

我正在构建下一个界面:

enter image description here

如您所见,此界面有两个显示为按钮的链接,一个用于添加产品,另一个用于休息产品。

当我点击“addProduct”链接时,它会计算出以下界面中显示的新总数:

enter image description here

此操作涉及的代码涉及2个文件:

JQuery Ajax文件:

$.ajax({
        async:true,
        type:"POST",
        url: "masProducto.php",
        datatype:"JSON",
        data: {
            tecantidad: tecantidad.val(), 
            valorId:id
        },
        success:function (jsonStr) {
            var cantidad=jsonStr.cantidad;
            var fila=$("#ticket_"+jsonStr.id);
            var tetotal=fila.find(".precioTotal");
            var teprecio=parseFloat(fila.find("input[type=hidden]").val());
            var teCosteTotal=$("#importeTotal");
            teCosteTotal.text(jsonStr.total+"€");
            tetotal.text(teprecio*cantidad+"€");
            var resumenTotal=$("#resumenTicket td:nth-child(3)");
            resumenTotal.text(jsonStr.total+"€");
            var resumenNumProductos=$("#resumenTicket td:nth-child(1)");
                resumenNumProductos.text(jsonStr.numTotalProductos+" Items en la cesta");
        },
        error:function(err){
            alert(err);
        },
        timeout:4000
    });

构建JSON对象的文件masProducto.php:

<?php 
include 'functions.php';
include('./ShoppingCart.php');
include('./Item.php');
sec_session_start(); //Nuestra manera personalizada segura de iniciar sesión php.

if (!isset($_SESSION['cesta'])){
      header('Location: ./login.php?error=1');
}
else {
    $cesta=new ShoppingCart();
    $cesta=unserialize($_SESSION['cesta']);
}


header('Content-Type: application/json');

$listaItems=$cesta->getItems();
$numEltos=$cesta->count();
$tecantidad=$_POST['tecantidad'];
$id=$_POST['valorId'];

foreach ($listaItems as $celda){
    if($id===$celda['item']->getId()){
        $cesta->updateItem($celda['item'],$tecantidad);
    }
}
    $_SESSION['cesta']=serialize($cesta);


if(isset($id)){
        $data = array(
            "cantidad"   => $tecantidad,
            "id"  => $id,
            "total" => $cesta->calcularTotal(),
            "numTotalProductos" => $numEltos

        );
        echo json_encode($data);
    }

?>

我正在使用PHP OOP,我使用的是购物篮的对象,即“Soppingcart”和“Item”。

我的问题是这个代码工作正常,但是当我快速点击加号(或休息按钮)时,它会给我一个未定义的对象。

如果有人可以帮助我,我会赞成,因为我甚至不知道如何寻找这个问题的解决方案。

有关详细信息,请访问此网站www.galeonweb.es/Index.php,如果您使用“test@example.com”和密码“123456”登录,您可以更好地了解我的问题。

提前谢谢

2 个答案:

答案 0 :(得分:0)

首先关闭这条线是非常糟糕的做法

if (!isset($_SESSION['cesta'])){
      header('Location: ./login.php?error=1');
}

你应该喜欢

if (!isset($_SESSION['cesta'])){
      echo json_encode(array(code => 2, message => 'Session invalid'));
}

将用户重定向到jQuery的登录页面。 然后,您需要相应地修改其余部分

if(isset($id)){
        $data = array(
            "code" => 0,
            "message" => "Success",
            "data" => array(
                "cantidad"   => $tecantidad,
                "id"  => $id,
                "total" => $cesta->calcularTotal(),
                "numTotalProductos" => $numEltos
             )

        );
        echo json_encode($data);
    }

我还要将以下内容添加到

else {

    echo json_encode(array('code' => 1, 'message' => 'Item not found' ));
}

此外,我不会测试是否在最后传递了一个id

if(isset($id)){
    $found = false;

    foreach ($listaItems as $celda){
        if($id===$celda['item']->getId()){
            $cesta->updateItem($celda['item'],$tecantidad);
            $found = true;
        }
    }
}
else
{
    echo json_encode(array(code => 1, message => 'Fatal error, id not set'));
}

并替换

if(isset($id)){
        $data = array(

使用

if($found === true){
        $data = array(

你当然必须相应调整你的javascript来解析响应。 这些变化可以让您更好地了解出了什么问题。但是,正如我在评论中所说,使用像Firebug这样的调试工具也会有很长的路要走。

答案 1 :(得分:-2)

您是否尝试过非异步?

$.ajax({
    async:false,
    type:"POST",
    url: "masProducto.php",
    datatype:"JSON",
...