Ajax - don't get Request - javascript

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

Related

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.

Why is PHP not receiving my AJAX request string?

I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];

Send $_GET vars on click link - PHP & Ajax

I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.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