roemel
roemel

Reputation: 3297

AJAX request to .php file returns empty string

First: I am new to AJAX and just know some basics about PHP.

I want to do an AJAX post to a .php file. To do that I got this code:

var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();

$.ajax({
    url: 'http://api.geonames.org/findNearbyPostalCodes',
    type: 'GET',
    data: {lat: lat, lng: lng, radius: 20, maxRows: 100, country: 'CH', username: 'bbag8274'},
    success: function(scriptData, textStatus, jqXHR){
        $.ajax({
            url: 'privatkunden_data.php',
            type: 'POST',
            data: {xmldata: jqXHR.responseText, address: $('#address').val()},
            success: function(secondScriptData, textStatus, jqXHR){
                alert('suc');
            },

            error: function(jqXHR, textStatus, errorThrown){
                alert(jqXHR.responseText);
            }
        });                         
    },

    error: function(jqXHR, textStatus, errorThrown){
        alert('fail');
    }
});

If the first post is successful it executes the second one. But the second one executes the error: function. Here is my .php file:

$xmlroot = $_POST['xmldata'];

$doc = new DOMDocument;
$doc->loadXML($xmlroot);

foreach($doc->getElementsByTagName('postalcode') as $postalcode){
    $zipcodes = $postalcode->nodeValue . " ";
}

The problem is: The AJAX post returns an empty alert box (alert(jqXHR.responseText);) and the .php file returns an error:

 **PHP Warning:  DOMDocument::loadXML(): Empty string supplied as input**

So the error says my $xmlroot variable is empty, am I right? If yes, why is it empty? It should be filled in with informations from xmldata.

Suggestions are appreciated

Thanks in advance

Upvotes: 2

Views: 4842

Answers (2)

Thiago C. S Ventura
Thiago C. S Ventura

Reputation: 2602

The data in the first ajax call is coming right. Try to put the dataType as text and convert this text to xml on your PHP.

dataType: 'text'

Example:

$.ajax({
    url: 'http://api.geonames.org/findNearbyPostalCodes',
    type: 'get',
    dataType: 'text',
    data: {lat: '47.644200', lng: '9.180260', radius: 20, maxRows: 100, country: 'CH', username: 'bbag8274'},
    success: function(result){
      alert(result)
    }
});

Live example: http://jsfiddle.net/t5jA5/

Upvotes: 1

theking2
theking2

Reputation: 2838

Could it be that you specify POST parameters although you do a GET request?

change the URL in something like

http://api.geonames.org/findNearbyPostalCodes?lat=47&lng=9&username=demo

...and read : http://www.geonames.org/export/web-services.html

Upvotes: 1

Related Questions