简体   繁体   中英

HTML form data is not passed to the php file by ajax GET request

I am getting errors in creating a GET request to send the form data to the PHP file. What should I do?

function addDetails(str1,str2,str3,str4){

    var xmlhttp=new XMLHttpRequest();
    xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {
        document.getElementById("viewblock").innerHTML = this.responseText;
       }
    };
    xmlhttp.open("GET","addDetails.php?a="+str1+"&b="+str2+"&c="+str3+"&d="+str4,true);
    xmlhttp.send();
}

str1 to str4 are the input field values(HTML) I send when calling addDetails().

My PHP code looks like this

$a = $_REQUEST["a"];
$b = $_REQUEST["b"];
$c = $_REQUEST["c"];
$d = $_REQUEST["d"];

$con=new mysqli_connect('localhost','root','');
if(!$con){
    die('Connection Error : '.mysqli_error($con));
}

mysqli_select_db($con,"ajax_app");
$sql="INSERT INTO images(title,description,capturedate,image) VALUES ($a,$b,$c,$d)";
if(mysqli_query($con,$sql)){
    alert("data added successfully");
}
else{
    alert("failed to add");
}
?>

No change occurs when I'm executing this. And there is no error too.

Your probably getting errors on the php script. You can not call the alert() functions in PHP. Use echo instead. Then you will see the responses in your browsers console.

Your PHP code should look like this:

$a = $_REQUEST["a"];
$b = $_REQUEST["b"];
$c = $_REQUEST["c"];
$d = $_REQUEST["d"];

$con=new mysqli_connect('localhost','root','');
if(!$con){
    die('Connection Error : '.mysqli_error($con));
}

mysqli_select_db($con,"ajax_app");
$sql="INSERT INTO images(title,description,capturedate,image) VALUES ($a,$b,$c,$d)";
if(mysqli_query($con,$sql)){
    echo "data added successfully";
}
else{
    echo "failed to add";
}
?>

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