Ajax call failing; xhr.responseXML is undefined

421 Views Asked by At

I'm trying to make a simple ajax call:

When the user selects and option, some info about that option will be echoed into a div (this is dynamic)

Here's my code for the ajax call

ajax.js

$(document).ready(function()
{ 
//Add Event 
    //Currently Broadcasting @Zone 
    $('#beacon0').on('change', function () 
    {
        var Selected = $(this).find("option:selected");
        var SelectedText   = Selected.text();
        var SelectedEncoded = encodeURIComponent(SelectedText);

        $.ajax
        ({
        url:        'ajax-addevent.php',
        data:       'n_beacon='+ SelectedEncoded,
        dataType:   'JSON',
        success: function(returnClass)
            {
                var resultajax = jQuery.parseJSON(returnClass)
                console.log(resultajax);
            },
        error: function(xhr, status, error) 
            {
                var errors = JSON.parse(xhr.responseText);
                console.log("failed");
                console.log (errors);
            }
        });
    });

});

SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.

ajax-addevent.php

<?php
include("classes/event.class.php");

$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
        $EventTitle = $row["n_title"];
        $EventLink = $row["n_link"];
        $EventDate = $row["n_date"];
}
        $arr = array( "EventTitle" => $EventTitle,
                           "EventLink" => $EventLink, 
                           "EventDate" => $EventDate );

        header("content-type:application/json");

        $json_arr = json_encode($arr);

        return $json_arr;
?>

My problem is that the ajax call fails and gives me this as result:

Error

What's wrong why my ajax call? Can you help?

EDIT Update Code:

1

There are 1 best solutions below

12
On

You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.

Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.

Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).