XmlHttpRequest sends blank data to php using POST method - javascript

I have attached the two files, I am trying to verify recaptcha from server side and trying to pass grecaptcha.repsonse() to php using XMLHttpRequest but it sends blank data using POST.I am able to get the solution for the same.
Following code has the XMLHttpRequest
<script type="text/javascript">
function sendAjaxRequest() {
if (grecaptcha === undefined) {
alert('Recaptcha not defined');
return;
}
var response = grecaptcha.getResponse();
if (!response) {
alert('Coud not get recaptcha response');
return;
}
var http = new XMLHttpRequest();
var url = 'validate-recaptcha.php';
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
temp = JSON.stringify(response);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.open('POST', url, true);
http.send(response);
}
</script>
Following is the php code:
<?php
if (empty($_POST['response'])) {
exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(array (
'response' => $response,
'secret' => 'mysecretkey',
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' => array (
'method' => 'POST',
'header' => 'application/x-www-form-urlencoded',
'content' => $post
)
);
$context = stream_context_create($opts);
$serverResponse =
#file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');
?>

Related

Ajax request handled by php returns NULL

I'm trying to send data from the browser's local storage to php using AJAX, when I test the API using postman by inserting this data(POST)
[
{
"product-id": "32",
"product-name": "Reese Stevenson",
"product-description": "Ea tempore temporib",
"product-image": "Screenshot_3.png",
"product-price": "778 "
}
]
which is the same data in local storage I get back this object as a response(POST & GET METHODS) which is the thing I want for the moment (starting small before scaling the API and integrating it with the whole application )
so when I tried to make the request using AJAX:
const storedProduct = localStorage.getItem("product-id");
const products = JSON.parse(storedProduct);
(function products_to_backend() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "localhost:9000/frontEndProductsHandler.php",true);
xhr.setRequestHeader("Content-type" , "application/json");
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.addEventListener("load",function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(`server status : 200 OK : ${xhr.responseText}`);
}else if(xhr.status === 404){
console.log("NOT FOUND");
}
});
xhr.addEventListener("error", function(){
console.log(`request faild : ${xhr.statusText}`);
});
console.log(typeof(JSON.parse(storedProduct)))
xhr.send(JSON.parse(storedProduct));
})();
the PHP script :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === "application/json"){
$requestBody = file_get_contents("php://input");
$data = json_decode($requestBody);
if($data){
http_response_code(201);
echo json_encode($data);
}else{
http_response_code(400);
}
}else{
http_response_code(404);
die();
};
Thanks in advance, and I hope that I described the issue well.
So the first problem was that i forgot about HTTP protocol in the end point , thanks to Markus Zeller to notice it.
And the second this was that i'm actually encoding the data into json even tho its already a json.
So that the new version of the script :
js :
(function products_to_backend() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:9000/controller/handlers/frontEndProductsHandler.php",true);
xhr.setRequestHeader("Content-type" , "application/json");
xhr.addEventListener("load",function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(`server status : 200 OK : ${xhr.responseText}`);
}else if(xhr.status === 404){
console.log("NOT FOUND");
}
});
xhr.addEventListener("error", function(){
console.log(`request faild : ${xhr.statusText}`);
});
xhr.send(JSON.stringify(storedProduct));
})();
php :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_CONTENT_TYPE']) && $_SERVER['HTTP_CONTENT_TYPE'] === "application/json"){
$requestBody = file_get_contents("php://input");
$data = $requestBody;
if($data){
http_response_code(200);
echo json_decode($data);
}else{
http_response_code(400);
}
}else{
http_response_code(404);
die();
};

I want to make a cart with php and js with the js sending a post request

<script>
function cart(func,id){
let url = "<?= SITEURL ?>Home/cart/" + func;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"value": id
}));
}
</script>
case 'cart':
require_once "modelProduct.php";
$model = new Product();
$idItem = $_POST['value'];
if($aParam[2] == 'add'){
if(isset($_SESSION['cart'])){
array_push($_SESSION['cart'],$idItem);
} else {
$_SESSION['cart'] = array();
array_push($_SESSION['cart'],$idItem);
}
} else if($aParam[2] == 'remove'){
if (($key = array_search($idItem, $_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
$category= $model->getById($idItem);
$aData['data'] = $products->getListaWhere("product_id = {$idItem}");
require_once "site/productsView.php";
break;
From what I saw this should send post request to site/Home/cart/func and there what would happened would be the ID would be added to the session['cart'] and the page would refresh but instead nothing seams to be happening

my ajax send post is not working in JS

I have a wordrpess site and I am trying to do an ajax call to send a variable but I cant make it work when I try to retrieve the variable I dont get anything back this is my code:
<script type="text/javascript">
window.onload = function(){
var boton = document.getElementsByClassName("teatro-buy");
const xhr = new XMLHttpRequest();
xhr.onload = function ()
{
console.log(this.responseText);
}
for (let qq = 0; qq < boton.length; qq++)
{
boton[qq].onclick = function()
{
botonid = this.id ;
xhr.open("POST", "ajaxcallnew.php")
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("lol=" + botonid);
console.log(botonid);
}
}
};
</script>
and this is my php
<?php
if(isset($_POST['lol'])){ //check if $_POST['examplePHP'] exists
echo $_POST['lol']; // echo the data
die(); // stop execution of the script.
}
?>
you can var_dump($_POST) or var_dump($_SERVER) or echo 1 ... if it's empty, your request is not arrive php
you can read the server log (such as nginx log, apache log ... almost they exist in runtime folder)
check your format:
examples:
(1) get:
var ajax = new XMLHttpRequest();
ajax.open('get','getStar.php?starName='+name);
ajax.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
(2) post:
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', '02.post.php' );
xhr.send('name=fox&age=18');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
you must add to your request action property.
For example:
jQuery.ajax({
url: ajaxurl, // ('admin-ajax.php')
method: 'POST',
dataType: 'json',
data: {action: 'yourvalue', fields: info},
success: function (json) {
console.log(json)
});
and on functions.php add the following:
add_action('wp_ajax_nopriv_actionValue', 'FunkName');
add_action("wp_ajax_actionValue", 'FunkName');
function FunkName()
{
//buisness logic
}
Why not use jQuery for this. It would become very simple.
$.ajax({
url:'path_to_php_file.php',
type:'post',
data:{'lol':'value_for_lol'},
onsuccess:function(response){
alert(response);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
https://www.w3schools.com/jquery/default.asp

why i am getting empty response text in ajax?

below is my code fo ajax which sends a string data via post method, the request is successful but I get an empty response. I had checked the readystate and status both are proper and the php file is in the same directory.
function getData(str)
{
if (str == "")
{
} else
{
if (window.XMLHttpRequest)
{
var dat = new XMLHttpRequest();
} else
{
dat = new ActiveXObject("Microsoft.XMLHTTP");
}
dat.open("POST","userdat.php",true);
dat.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dat.onreadystatechange = function ()
{
if (dat.readyState == 4 && dat.status == 200)
{
alert(dat.responseText);
$('#dataReT').text(dat.responseText);
}
}
dat.send("userid=" + str);
}
}
content of my php file:
<?php
$id=$_REQUEST['userid'];
echo $id;
?>
there is no userid in $_REQUEST. Try to add this to your php file:
if(array_key_exists('userid',$_REQUEST)) {
echo $_REQUEST['userid'];
} else {
echo 'no userid.';
}
You may send userid value from your javascript file

my php can't receive the 'post' variabe I am sending via ajax

Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax

Categories