简体   繁体   中英

Ajax xmlhttprequest with POST to php file

Hello guys I am kina new in ajax and I have an issue, I want to call a php file to do some db queries from the javascript file. JS code

$(document).ready(function(){
$(".delete").click(function(){
var xhttp;
    if(window.XMLHttpRequest)
       xhttp = new XMLHttpRequest();
    else
       xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
    if(xhttp.readyState==4 && xhttp.status==200){
        $(".delete").css("color", "pink");
    }
};
    xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("date="+date+ "&hour="+time);
});
});

And php file.

<?php
session_start();
require_once("../connection.php");
if($_SESSION["password"]!=null) 
{   
if(!empty($_POST["date"]) && !empty($_POST["hour"])){
    $_SESSION["msg"]= "<script type='text/javascript'> alert('The appointment has been removed!');</script>";
    $date=$_POST["date"];
    $hour=$_POST["hour"];
...

I would like to point that the request is going properly, the php file is running if I sent data through html form with post,the problem is when I try it through the js file. The status is 200 and the readyState is going to 4 eventually. Is this below right when I call it from js??

$_POST["date"] 
$_POST["hour"]

Did you try to add some brackets ?

if(xhttp.readyState==4 && xhttp.status==200) {
    $(".delete").css("color", "pink");
    xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("date="+date+ "&hour="+time);
}

The code is completely right, I found the mistake on method date. If I give date("Ymd", strtotime($date)) and the var $date instead of - has / or w/e it wont change the date to the format you expect.

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