简体   繁体   中英

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable. I POST two variables, which the PHP page collects and sets the relevant Session variable.

Occasionally though it doesn't work, even though the correct values are being Posted across. So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax. But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.

Am I missing something here. Do I need to create a response or should that be automatic?

My Javascript is:

GBD.updateFunction = function(p,x)
{
    $.ajax(
        {
            type: "POST",
            url: "SetSession.php",
            dataType:'text',
            data: 
                {
                    item:p,
                    section:x
                },
            success: function()
                {
                    alert('success');
                },
            error: function()
                {
                    alert('failure');
                }
            });

         console.log(p + " " + x + " selected");

    return false;
}

The setSession . php is:

$section = (isset($_POST['section']) ? $_POST['section'] : 0 );

if($section == 1)
{
    if(isset($_POST['item']))
        {
            $pageVar = $_POST['item'];
            $_SESSION['pagevar'] = $pageVar;    
        }
    else
        {
            $_SESSION['pagevar'] = $_SESSION['pagevar'];
        };
}
?>  

Try this way

//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
 {
  if(isset($_POST['item']))
    {
        $pageVar = $_POST['item'];
        $_SESSION['pagevar'] = $pageVar;    
    }
  else
    {
        $_SESSION['pagevar'] = $_SESSION['pagevar'];

    };
  echo "success";
 }
 ?> 

 //ajax call
 GBD.updateFunction = function(p,x)
{
 $.ajax(
    {
        type: "POST",
        url: "SetSession.php",
        dataType:'text',
        data: 
            {
                item:p,
                section:x
            },
        success: function(data)
            {
                console.log(data);
            },
        error: function(jqxhr)
            {
                //it  will be errors: 324, 500, 404 or anythings else
                console.lgo(jqxhr.responseText); 

            }
        });


    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM