Jamie McAllister
Jamie McAllister

Reputation: 729

Setect AJAX Request in PHP

OK, this has taken me 3 days and i am no further on than when i started.

i am building a web app at the request of my employer. the APP requires communication with a server which uses PHP Code.

I am currently trying to get my PHP code to detect whether a request is AJAX or not. the response i am getting suggests to me that i have done something wrong.

I used the code that was marked as an answer to another question so i'm not sure what's wrong :/

This is the PHP code: - the response from the server is No GET or PUT request found

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: Content-Type');
include_once("xmlHandler.php");

function s($message){
echo $message. "<br>";
}

if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
    echo "GET has been received";
}else{
    s("No GET or PUT request found");
}

?>

the AJAX request looks like this:

var data = {
  "data" : "test"
};
$.ajax({
  type: "GET",
  dataType: "json",
  url: "http://www.qsl.org.uk/apps/main.php", //Relative or absolute path to response.php file
  data: data,
  contentType: "application/json",
  success: function(response) {
    console.log(response);

    alert("Form submitted successfully.\nReturned json: " + data["json"]);
  }
});

any help here would be greatly appreciated as i am quite inexperienced with PHP and have no idea what i've done wrong

Upvotes: 0

Views: 842

Answers (1)

Novocaine
Novocaine

Reputation: 4786

Why not just pass an additional variable along with the ajax request that indicates that it was an ajax request;

var data = {
  "data": "test",
  "ajax": true
};
$.ajax({
  type: "GET",
  dataType: "json",
  url: "http://www.qsl.org.uk/apps/main.php", //Relative or absolute path to response.php file
  data: data,
  contentType: "application/json",
  success: function(response) {
    console.log(response);

    alert("Form submitted successfully.\nReturned json: " + data["json"]);
  }
});

Then you can retrieve that in PHP;

$_GET['ajax']

Upvotes: 2

Related Questions