Ajax xmlhttprequest with POST to php file - javascript

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("Y-m-d", strtotime($date)) and the var $date instead of - has / or w/e it wont change the date to the format you expect.

Related

Posting js variables to PHP not running in any method

In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}

Passing variables from javascript to php file

I have worked on API (zomato) that gives me restaurant details. I want to insert them into my local database, but I have a problem with passing the variable to PHP because it's too much big for $_GET to handle it. I tried to use $_POST but The output of the post was empty.
// JS code
function showCafes(str){
var xhttp;
xhttp = new XMLHttpRequest();
console.log(str);
xhttp.open("GET","https://developers.zomato.com/api/v2.1/search?entity_type=city&q=t&start="+str+"&count=20" , true);
xhttp.send();
var restaurants="";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var r=JSON.parse(this.responseText);
var rest ={
name : r.restaurant[1].restaurant.name
};
$.post("addFromApi.php", rest);
window.location.href="addFromApi.php";
// PHP code
<?php
print_r($_POST);
?>
I expected from the PHP code to print the name of the first element in it.
// Sample output From API
{"results_found":1,
"results_start":0,
"results_shown":1,
"restaurants":
[{"restaurant":{
"R":{"res_id":18692654},
"id":"18692654",
"name":"East Village"}
I have solved it with making a form from js like this
document.getElementById("cafes").innerHTML += '<form id="rests" action="addFromApi.php" method="post"><input type="hidden" name="q" value="'+restaurants+'"></form>';
document.getElementById("rests").submit();
//resturants is the variable that I wanted to pass to php.

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Data not getting passed via Ajax to PHP script

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

PHP not receiving JSON send by Ajax

I am trying to send some JSON data to a PHP file using Ajax. Here is my JavaScript code:
function updateJSON(){
var xmlhttpa;
if (window.XMLHttpRequest){
xmlhttpa = new XMLHttpRequest();
} else {
xmlhttpa = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttpa.onreadystatechange = function(){
if (xmlhttpa.readyState==4 && xmlhttpa.status==200){
console.log("Sent")
}
};
xmlhttpa.open("POST", "update.php", true);
xmlhttpa.send("json=" + JSON.stringify(json));
};
And here is the PHP file that processes the request:
<?php
$json = $_POST["json"];
file_put_contents('data.json', $json);
Unfortunately this isn't working. How can I repair my code?
Please, no jQuery.
Thanks!
Also, if you vote down, please tell me why so I can improve this question.
You should add line with setting Content-type when you POST your data.Try this:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Also :
xmlhttp.send("json=" + encodeURIComponent(JSON.stringify(json)));

Categories

Resources