Can't send XMLHttpRequest - javascript

I am trying to delete data with vanilla javascript ajax. After sending POST request with an id value to php file. Every time it prints "error" in the console.
HTML
<div class="deleteButton" onclick="showAllert(this)" id="1">
<i class="fa-solid fa-trash-can fa-2x" style="color:#A81E22" title="delete"></i>
</div>
JAVASCRIPT
<script>
function showAllert(a) {
// sent delete request
var dataId = a.getAttribute("id");
var dataId = parseInt(dataId);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/vehicles/del-veh.php', true);
// xhr.responseType = 'json';
xhr.onload = () => {
if(xhr.status === 200) {
console.log(xhr.response);
location.reload();
}else {
console.log("There was a problem");
}
}
var data = JSON.stringify({id: dataId});
xhr.send(data);
}
</script>
PHP
<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$data = json_decode(file_get_contents('php://input'), true);
if(!empty($data["id"])) {
// Required variables
$vehid = $data['id'];
echo "success";
}else {
echo "error";
}
//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);

Send POST data in urlencoded format:
<script>
function showAllert(a) {
// sent delete request
var dataId = a.getAttribute("id");
var dataId = parseInt(dataId);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/vehicles/del-veh.php', true);
// xhr.responseType = 'json';
xhr.onload = () => {
if(xhr.status === 200) {
console.log(xhr.response);
location.reload();
}else {
console.log("There was a problem");
}
}
// var data = JSON.stringify({id: dataId});
xhr.send(`id=${dataId}`);
}
</script>
And in your PHP script:
<?php
//Connection statement
require_once('../../Connections/ukcd.php');
$id= $_POST['id'];
if(!empty($id)) {
// Required variables
$vehid = $id;
echo "success";
}else {
echo "error";
}
//AUTOEXECUTE METHOD
$delveh = $ukcd->prepare('DELETE FROM a_ukcd_client_vehicles WHERE clientveh_id = ?');
$result = $ukcd->execute($delveh, $vehid);

Related

POST data in JavaScript is not being sent

Here's my JavaScript code to post to my API:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
pageRequest.send("firstname=John&lastname=Doe");
And here is my PHP backend code:
<?php
if (isset($_POST["firstname"]) && isset($_POST["lastname"])) {
$first_name = $_POST["firstname"];
$last_name = $_POST["lastname"];
echo "Hello, " . htmlspecialchars($first_name) . " " . htmlspecialchars($last_name);
} else {
echo "Please include all fields.";
}
?>
However, my PHP code just echos "Please include all fields.", and when I try doing
var_dump($_POST);
It returns an empty array. Am I doing something wrong here?
Thanks.
You are likely missing setup of request header:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
*** pageRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
pageRequest.send("firstname=John&lastname=Doe");

echo is adding a new line to what i output in PHP

I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.

How to pass data into form and response onkeyup or keydown using json, ajax

How to fetch data and pass. into form and response customername onkeyup or keydown json and php.
<?php
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
while ($result2=mysqli_fetch_assoc($query)) {
$data[] = $result2['customername'];
}
echo json_encode($data);
?>
Here is HTML code with javascript ajax:-
<div id="demo">
CustomerName: <input type="search" name="customername">
</div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "connection.php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
document.getElementById("demo").innerHTML = arr;
}
</script>
How pass into form and response on keyup or keydown and related suggestions customername should display down. I am new to JSON and javascript and examples sites. Thanks in advance. All suggestions are welcome.
From your code sample
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
$dataForJSON = array()
while($result2=mysqli_fetch_assoc($query)) {
$dataForJSON[] = $result2['customerName'];
}
echo json_encode($dataForJSON);
Use this code to return data from json and this will work fine with JSON.parse(response)

Audio File Not Getting Uploaded with ajax

I tried The following code to upload files without pressing submit button. It works for images not for audio or video. When Audio File is uploaded it says undefined index 'file' in the log.
<script>
$('#headerimage').on('change', function() {
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
console.log(xhr.responseText);
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
});
</script>
<form id="fileupload" method="post" enctype="multipart/form-data" action="upload2.php">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
<?php
if(!empty($_FILES))
{
$file = $_FILES;
if($file['file']['error'] == 0)
{
$name = explode('.', $file['file']['name']);
$newName = $name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "uploads/".$newName))
{
echo $newName;
exit;
}
} else {
echo "err";
exit;
}
} else {
echo "errrror";
exit;
}
?>

ajax. Retrieve information from query

I am really confused at the moment, I am very new to all this just being learning java script and php . I am trying to use ajax to check the db to see if the email exist and then if it is cancel the submit of the form. I cant seem to retrieve the information from the XML. I am probably doing it completely wrong, but that why I am asking here , to lean
So if you could help would be great
JAVA SCRIPT
//validate the sign up/regiser form
function validateForm() {
//Get password varibles
var pass = document.forms["signup"]["sign-up-password"].value;
var confPass = document.forms["signup"]["password-confirm"].value;
//Check if they match
if (pass != confPass) {
alert("Password does not match");
return false;
}
//Ajax functions
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
alert("im here");
email = document.getElementById('email2').value;
xmlHttp.open("GET", "php/ajaxCom.php?email=" + email, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
var check=xmlHttp.status;
if(xmlHttp.status==200){
alert("also here 2");
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
return message;
}
}
}
php/xml
<?php
$status;
if (isset($_GET['email'])) {
$email_in_use = $_GET['email'];
$query = mysqli_query($link, "SELECT * FROM users WHERE email='".$email_in_use."'");
if(mysqli_num_rows($query) > 0){
$status = false;
}else{
if( !mysqli_query( $link, $query ) )
{ $status = mysqli_error( $link ); }
else
{ $status = true; }
}
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" standalone="yes" ?><response><status/></response>');
$xml->response->status = $status;
echo $xml->asXML();
echo $status;
}
?>
You are building and handling ajax XMLHttpRequest in an incorrect way.
Also, to be able to receive an XML response - set additional request header(will be shown further).
Change you ajax request as shown below:
var xmlHttp = null; // this variable should be global to access from different functions
...
//Ajax functions
email = document.getElementById('email2').value;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "php/ajaxCom.php?email=" + email, true);
xmlHttp.setRequestHeader("Accept", "text/xml");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
...
function handleServerResponse(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var check=xmlHttp.status;
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
return message;
} else{
setTimeout('process()',1000);
}
}

Categories

Resources