Search code examples
phpajaxonbeforeunload

how to call update file in ajax on index.php page


update.php page

if (isset($_POST['bags']))
{
    $bagS=$_POST['bags'];
        $id=$_POST["id"];
        $_SESSION['id']=$id;
        $cats = explode(" ", $bagS);
        $cats = preg_split('/,/', $bagS, -1, PREG_SPLIT_NO_EMPTY);
        foreach($cats as $key => $cat )
        {
        $cat  = mysqli_real_escape_string($con,$cats[$key]);
        $cat = trim($cat);
 if($cat !=NULL)
             {
                 $stmt = $con->prepare('UPDATE wallet SET `Status`="Hold" where `Id`=? AND `bags`="'.$cat.'" ');
                 $stmt->bind_param("s", $_POST["id"]);
                 $stmt->execute();

  }
  }
}

want to use update.php file on index.php page on window.onbeforeunload

using ajax here

function myfoo(){

    $.ajax({
                url: "update.php",
                dataType: 'json',
                data: {id: 1},
                success: function (r) {}
    });
        }

        window.onbeforeunload = function(){
      myfoo();
      return 'Are you sure you want to leave?';
    };

Solution

  • 1) your not sending any data like bags

    2) ajax not defined type:'post' but your accessing value by post . if you not define the type means ajax will use default get method .

    $.ajax({
                url: "update.php",
                type:'post',
                dataType: 'json',
                data: {id: 1,bags:bags}, // bags collection value what your goging to send to server 
                success: function (r) {}
    });