1

I've got this simple script where I want to post data using AJAX to the server and then spit it out (echo), but it won't work...

This is my output:

Your viewport width is 1338x684

Ajax wasn't initialized!

And in this case, the Width and Height are only set to 880px * 495px when the PHP script doesn't get any data.

The web page head of testajax.php:

<head>
<script type='text/javascript' src='js/jquery-1.7.2.min.js'></script>       <!-- Main Java library script-->
<!-- The following 3 scripts are utilized by the Accordion Menu in the aside side bar -->
<script type='text/javascript' src='js/jquery.cookie.js'></script>          <!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.hoverIntent.minified.js'></script><!-- Acco. Menu script-->
<script type='text/javascript' src='js/jquery.dcjqaccordion.2.7.min.js'></script> <!-- Acco. Menu script-->
<!--The following 2 scripts are utilized by the Pan and Zoom Slide Show -->
<script type="text/javascript" src="js/jquery.carouFredSel-6.2.1.js"></script>
<script type="text/javascript" src="js/panzoomslideshow.js"></script>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Testing Ajax</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/normalize.min.css">        <!-- used to normalize-->
        <link rel="stylesheet" href="css/main.css">                 <!-- Main CSS styling-->

<script type="text/javascript">
document.write('<p>Your viewport width is '+ window.innerWidth+'x'+window.innerHeight+'</p>');

$(document).ready(function() {
    $.ajax({
            url: "ajaxresponse.php",
            type: "POST",
            dataType: "json",   
            data: {
                width        : window.innerWidth,
                height       : window.innerHeight
            },    
            success: function( data, textStatus, jQxhr ){
                $("#response pre").html( JSON.stringify( data ) );
            },
            error: function( jqXhr, textStatus, errorThrown ){
            console.log( errorThrown );
            }
        });
});
</script>


<!-- ********** panzooom.php prints the java script to make a pan and zoom transition slide show, depending on the width and heigth of the viewport *********** -->

             <!--[if lt IE 9]>
                <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
                <script>window.html5 || document.write('<script src="js/vendor/html5shiv.js"><\/script>')</script>
            <!--<![endif]--> 
    <?php include 'ajaxresponse.php';?>                 
</head>

And here is the ajaxresponse.php file:

<?php  
if (is_ajax()) {
    if (isset($_POST["data"]) && !empty($_POST["data"])) { //Checks if data value exists
        $data = $_POST["data"];
        echo "Ajax was initialized :)<br>";
        echo '<p>var_dump($_POST):<br>'; 
        var_dump( $_POST );    
    }else{
        "Ajax was initialized, but the value isn't set or it's empty (same same)!<br>";
    }
}else{
echo "Ajax wasn't initialized!<br>";    
}


//Function to check if the request is an AJAX request
function is_ajax() {
    echo "\$_SERVER['HTTP_X_REQUESTED_WITH']  ->   " . $_SERVER['HTTP_X_REQUESTED_WITH'] . "<br>";
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?> 
Jimmi Lee
  • 73
  • 1
  • 11
  • 2
    Have you looked into the browser's developer tools (-> networks sources) and actually seen the AJAX request going off? Also what does `I want to post data using AJAX to the server and then spit it out (echo), but it won't work...` exactly mean? I mean `it won't work` isn't an error description. It's as if a patient would go to a doctor and say `I'm hurt`. – Charlotte Dunois Aug 24 '15 at 19:46
  • 1
    The question is, why did you turn of processing and set the contentType to JSON, and then you're trying to get the data as `$_POST['width']` as if it was `www-encoded`, which it isn't, it's now JSON ? – adeneo Aug 24 '15 at 19:48
  • While it's _probably_ not causing the problem, you should move the output from PHP from the `` element into a `` element. – HPierce Aug 24 '15 at 19:50
  • Got all three comments and will try out moving the code and looking into how to change it from JSON to simple string text. Under developer tools I got both the console and network and I'll try to give you this information as well. – Jimmi Lee Aug 25 '15 at 02:32
  • adeneo - I took a screenshot of the Network section in my Comodo browser (basically Chrome) and under XHR there's a list of various files, mostly .js with status, type, initiator, size and time, along with a timeline. IN THIS list I find testajax.php and it's size is 7.0KB and it's time 1.65s Doesn't this indicate that something gets fired off? – Jimmi Lee Aug 25 '15 at 12:46
  • Charlotte Dunois - I changed the PHP script part to give me a minimum of feedback and print the $_POST array, so that one day I can see it... Right now though, it just tells me that "Ajax wasn't initialized!" and so I will go read up more on this magic thing called AJAX... adeneo - I guess that means nothing was fired off after all . . . – Jimmi Lee Aug 25 '15 at 12:48

1 Answers1

2

Problem 1

Here you tell jQuery that when it makes the request it:

  • Should say that it is sending JSON
  • Should not convert the data you pass it into a different format
contentType: 'application/json',            
processData: false,

Here you don't pass it JSON:

data: {
    width        : window.innerWidth,
    height       : window.innerHeight
},

and in the PHP:

You try to read from $_POST which won't be initilised if the request is formatted a JSON.

isset($_POST["data"]

Remove the contentType and processData configuration from your JavaScript. Let jQuery do its default of encoding the data using form encoding.


Problem 2

You are trying to read a piece of data called data:

$data = $_POST["data"];

but the only pieces of data you are sending are called width and height:

data: {
    width        : window.innerWidth,
    height       : window.innerHeight
},

You need to test for data you are actually sending.

Problem 3

You say (dataType: 'json',) you expect JSON in the response but testajax.php returns an HTML document.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hi Quentin - you're making a lot of sense. I removed **contentType** and **processData**, while keeping the **dataType** as _json_ I'm testing for whether there is data, before I try to dump the content. The plan was to get to that point and then start figuring out how to use it. I'm still getting the output _Ajax wasn't initialized!_ though - so something else is missing in the puzzle (as well)... – Jimmi Lee Aug 25 '15 at 14:00
  • What is the value of `$_SERVER['HTTP_X_REQUESTED_WITH']`? (When you request the URL with Ajax, not when you load it straight into the browser). – Quentin Aug 25 '15 at 14:08
  • Hi Quentin - I'm not entirely sure how to check the value of `$_SERVER['HTTP_X_REQUESTED_WITH']` at the time when I request the URL with Ajax. Since all I need is a couple of numbers or strings (the width and height), I'd rather stay away from JSON, but I'm not having any luck with setting the **dataType** to _text_ either - I continually get a false when checking `is_ajax()` I'm very new to JQuery BTW ... – Jimmi Lee Aug 25 '15 at 14:15
  • Just `echo` it (and look in the Net tab of your developer tools to see what the response looks like … which assume you're already doing as otherwise you couldn't see what it was outputting in response to your Ajax request) – Quentin Aug 25 '15 at 14:22
  • It looks like `testajax.php` is both the script for loading the HTML document when the browser requests it directly and also the script for loading some specific data when requested by Ajax. While there are often perfectly good reasons for putting both those things on the same URL, you'll have a much easier time debugging things if you break them into two separate files and test them independently. – Quentin Aug 25 '15 at 14:24
  • Heh - I actually had them split up, but put them together to better show it here... I'll put it back and test with separate files. – Jimmi Lee Aug 25 '15 at 14:30
  • I've split them up and made the question reflect this with the new output as well. – Jimmi Lee Aug 25 '15 at 14:39
  • I put another line into `is_ajax()` to check for the content of `$_SERVER['HTTP_X_REQUESTED_WITH']` This is the line: `echo "\$_SERVER['HTTP_X_REQUESTED_WITH'] -> " . $_SERVER['HTTP_X_REQUESTED_WITH'] . "
    ";` This gives me this output: `Notice: Undefined index: HTTP_X_REQUESTED_WITH in D:\xampp\htdocs\NewTopInterieur\ajaxresponse.php on line 18`
    – Jimmi Lee Aug 25 '15 at 14:47
  • I can't reproduce that: https://www.evernote.com/l/AAMR0YFUMzpJJ7tZHGxOdhl0NeFFyS62_WQ – Quentin Aug 25 '15 at 15:15
  • That's interesting - in my browser under network, when choosing ajaxresponse.php there's nothing under response! I tried in a different browser as well (IE) and at least now I know where to check if there's a response, but I'm still very much at a loss with regards to why AJAX isn't sending... I tried using _JSON.stringify()_ as well... – Jimmi Lee Aug 25 '15 at 15:58