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';
}
?> 
6
  • 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. Commented Aug 24, 2015 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 ? Commented Aug 24, 2015 at 19:48
  • While it's probably not causing the problem, you should move the output from PHP from the <head> element into a <body> element. Commented Aug 24, 2015 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. Commented Aug 25, 2015 at 2: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? Commented Aug 25, 2015 at 12:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

10 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.