Receive paramter with cURL PHP using XMLHTTP JavaScript - javascript

My program is using a JS XMLHTTP request to a PHP file with cURL code to retrieve the contents of another page. I'm calling a PHP file in order to avoid a cross-origin-request error by the browser. I need to send my PHP file a JS variable, psswd, so it can use it when executing a cURL request.
I'm using the following JavaScript code to get the contents of another page:
var psswd = "test";
var xmlhttp;
if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }
else{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("POST", "parsefeed.php?psswd=" + psswd, false);
xmlhttp.send();
My cURL PHP script where i need to use this variable is:
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url ,
CURLOPT_SSLCERT => $cert_file ,
CURLOPT_SSLCERTPASSWD => $< * VARIABLE GOES HERE * >,
);
curl_setopt_array($ch , $options);
$output = curl_exec($ch);
echo $output;
I've tried using $_POST['psswd'] and checking if anything is even posted, but it doesn't seem to work. Any ideas how I can verify the variable is being passed?

For a valid POST request which is accessable through PHP you have to specify a header and pass your data in the .send() method:
xmlhttp.open("POST", "parsefeed.php", false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("psswd=" + psswd);
But it would be a lot more secure and easier to use jQuerys ajax abilities instead.

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';
}

Ajax xmlhttprequest with POST to php file

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.

Ajax - don't get Request

I have a JavaScript function that I use to start a request. I need the GET parameter of this request, but trying to access it through PHP does not return anything. Any idea why?
I call the JS function in the same PHP file through which I try to access it (index.php)
JavaScript:
function aufloesung() {
var request = new XMLHttpRequest();
request.open("GET", "index.php?screen=1", true);
request.send();
}
PHP File:
<script> aufloesung(); </script>
...
echo $_GET["screen"]
But I don't get the parameter.
Its easy by using jQuery and slicing your index.php & ajaxphp files.
include jquery.js in your index.php:
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
aufloesung();
</script>
app.js:
function aufloesung() {
$.ajax({
type: "get",
url: "ajax.php?screen=1",
success: function( data ) {
alert( data );
}
});
}
ajax.php:
<?PHP
echo $_GET[ 'screen' ];
?>
You are making two separate HTTP requests.
The first one made by typing a URL into the address bar of the browser doesn't include the query string parameter but is rendered in the page.
The second one, made by using the XMLHttpRequest object, does include the query string parameter, but you don't do anything with the response so you can't see it.
You could, for example:
function aufloesung() {
var request = new XMLHttpRequest();
request.open("GET", "index.php?screen=1", true);
request.addEventListener("load", function (event) {
document.body.appendChild(
document.createTextNode(this.responseText)
);
});
request.send();
}

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

Call Perl function in HTML using AJAX

im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:
function getOption(){
var selectmenu=document.getElementById("Select1")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
var s = chosenoption.text;
openFile("C:\PerlTest\test.txt");
}
}
}
EX. not working trying to pass parameter:
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Im attempting to pass the paremeter in that way because of this example:
http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201
Can anyone help??
Thanks a lot.
After the sugestion of Kinopiko, that makes sense, i have the following:
HTML-
function openFile(name){
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
var container = XMLHttp.responseText.split("\n");
if (container.length>0){
for ( i=0; i< container.length-1;i++){
document.getElementById("TxtArea").innerHTML += container[i] + " ";
}
}
}
else{
document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
Perl script:
#!c:/Perl/bin/perl
use strict;
use CGI qw/param/;
use URI::Escape;
print "Content-type: text/html\n\n";
my $file = param ('file');
$file = uri_unescape ($file);
open (MYFILE, $file);
while (<MYFILE>) {
chomp;
print "$_\n";
}
close (MYFILE);
Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.
Maybe im using the encodeURI wrong??
Thanks.
First of all you need to add a question mark:
XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true);
Also you need to percent-encode "name" using encodeURI.
On the Perl end, you can use a module like CGI to get the value of the file:
use CGI qw/param/;
my $file = param ('file');
Then
use URI::Escape;
$file = uri_unescape ($file);
open (MYFILE, $file);
should be
open (MYFILE, $file) or die "Cannot open file $file: $!\n";

Categories

Resources