using POST in ajax in vanilla js - javascript

I am trying to send the post request to my PHP file but it is saying undefined index.
my js code -
document.getElementById("btn1").addEventListener('click', xh );
function xh(){
xhr = new XMLHttpRequest();
//xhr.open('GET', 'req.php?msg=hello bro', true);
xhr.open('POST', 'req.php');
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
xhr.onprogress = function () {
// document.getElementById("loading").classList.remove("dis");
}
xhr.onload = function () {
console.log(this.responseText);
}
xhr.send("msg=hello");
}
my PHP code -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
I also tried the server request method but it didn't work
it is showing not set, and if I try to echo the $_POST['msg']; it says undefined index 'msg'

Instead of
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
you want to set the request header
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Read more about XHR. The present approach it to use fetch() though.
fetch("req.php", {
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: "msg=hello"
}).then(response => response.text())
.then(console.log)

Related

XmlHttpRequest sends blank data to php using POST method

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');
?>

download excel file using post request

I've an API endpoint that takes in a JSON and returns a excel file. The endpoint directly sends the file, not the link to the file. How do I download the file using JQuery AJAX.
Backend Code:
public function postExcel() {
// Parse request body
$reqBody = json_decode(file_get_contents('php://input'));
// On Valid Request
if(isset($reqBody, $reqBody->regno, $reqBody->offset) && $reqBody->offset < 100 && $reqBody->offset >= 0) {
// Create and add metadata to the workbook
$workbook = new \PHPExcel();
$workbook->getProperties()
->setCreator('AUScraper')
->setTitle('AU Results')
->setLastModifiedBy('AUScraper')
->setDescription('generated by AUScraper')
->setSubject('generated by AUScraper')
->setKeywords('anna university unofficial semester result API')
->setCategory('semester results');
$worksheet = $workbook->getSheet(0);
$worksheet->setTitle('results');
// Get the results
$results = $this->requestAU($reqBody->regno, $reqBody->offset);
// Update worksheet
//Output the file
ob_clean();
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
header("Expires: 0");
$workbookWriter = new \PHPExcel_Writer_Excel2007($workbook);
$workbookWriter->save("php://output");
}
// On Invalid Request
header('Content-Type: application/json');
http_response_code(400);
return json_encode(['error' => 'invalid request']);
}
Frontend Code:
import $ from 'jquery';
import 'materialize';
$(() => {
$('#reg_form').submit(() => {
// format data to send
let form_data = {};
form_data.regno = $('#reg_no').val();
form_data.offset = $('#offset').val();
// Send the request
$.ajax({
url: 'http://localhost/git_repo/AUScraper/app/public/api/excel',
data: JSON.stringify(form_data),
type: 'POST',
contentType: 'application/json',
success: function(data) {
var blob=new Blob([data], {type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="result_"+new Date()+".xlsx";
link.click();
},
error: (xhr,status,error) => {
let errorMessage = JSON.parse(xhr.responseText);
Materialize.toast(errorMessage.error, 2000);
}
});
return false;
});
});
I don't want to save the file in server beforehand, but just download it. Thanks in advance.
The problem in the above question was, I was able to download the file but it was corrupted. I fixed it by setting responseType of xhr to blob.
New AJAX code for reference:
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/git_repo/AUScraper/app/public/api/excel');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
let link=document.createElement('a');
link.href=window.URL.createObjectURL(this.response);
link.download="results.xlsx";
link.click();
}
else {
Materialize.toast('Invalid data!', 2000);
}
}
xhr.send(form_data);

How can I get binary data from PHP passthru in JavaScript ajax call?

I want to get an audio file from a server in JavaScript and play it. But the ajax call in my code never seems to callback, and I am also unsure whether I handle the audio in JavaScript correctly.
The following PHP file returns the audio file on the server:
<?php
header('Access-Control-Allow-Origin: *');
$name = './audiofiles/audio.wav';
$fp = fopen($name, 'rb');
header("Content-Type: binary");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
?>
The script is called from JavaScript using ajax and the returned audio data is replayed in the browser (at least thats what should happen):
function playSample(e,q) {
console.log("requesting audio from server")
$.ajax({
url: "https://audioserver.com/getaudio.php",
type: "GET",
dataType: "arraybuffer",
processData: false,
success: function(result){
console.log("received audio, starting to play now")
var buffers = result;
var newSource = audioContext.createBufferSource();
var newBuffer = audioContext.createBuffer( 2, buffers[0].length, 16000 );
newBuffer.getChannelData(0).set(buffers[0]);
newSource.buffer = newBuffer;
newSource.connect( audioContext.destination );
newSource.start(0);
}
});
}
What am I doing wrong here?
jQuery ajax does not support typed responses, so you're going to get text as result in your success callback.
You can use bare XMLHTTPRequest to get a binary response
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is the array buffer for you to manipulate
}
}
xhr.open('GET', 'https://audioserver.com/getaudio.php');
xhr.responseType = 'arraybuffer';
xhr.send();
There is also a plugin that patches jquery to support it https://github.com/acigna/jquery-ajax-native
Also your your audio processing code looks incorrect. buffers[0] doesn't make sense since an arraybuffer doesn't have numeric properties

Why WP AJAX always return 0?

Tried to get answer, but returns 0.
JS in the head:
q = new XMLHttpRequest();
q.open('POST', ajaxUrl);
q.onreadystatechange = function () {
if (q.readyState === 4) {
console.log(q.response);
}
};
var data = {
'action': 'check_email'
};
q.send(JSON.stringify(data));
ajaxUrl links to admin_url('admin-ajax.php');
Code in the function.php:
function check_email() {
echo 'true or false';
die();
}
add_action('wp_ajax_check_email', 'check_email');
add_action('wp_ajax_nopriv_check_email', 'check_email');
Assuming a json request is valid, set the content-type to json
q.setRequestHeader('Content-Type', 'application/json');
if it isn't send application/x-www-form-urlencoded instead
q.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...
q.send('action=check_email');
q.responseText is what you're looking for.

Send the POST variable in ajax request

I have the following ajax ,on which im trying to post the dataString as a parameter to the php file.
I have tried putting dataString inside xhr.send(dataString);.But it didnt work out.Is there any way around?
dataString = txCryptData;
var xhr = new XMLHttpRequest();
var params="data="+dataString;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
xhr.open('POST', 'tokenize.php', true);
xhr.send();
In the php I tried $_POST['params']; to fetch the value posted by the ajax req
In PHP use this to get the string sent with ajax :
$data = file_get_contents("php://input");
And in JS :
dataString = txCryptData;
var xhr = new XMLHttpRequest();
var params="data="+dataString;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
alert(xhr.responseText);
}
}
xhr.open('POST', 'tokenize.php', true);
xhr.send(params);
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'youUrl',
data: {
'Joo': 'bar',
'ca$libri': 'no$libri' // $ sign in the parameter name seems unusual, I would avoid it
},
success: function(msg){
alert('Value' + msg);
}
});
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(params);
You may have to add these lines to your js snippet

Categories