I have a php script in which i have the following function :
<?php
function readXML() {
$url = $_REQUEST['schemaPath'];
$xml = simplexml_load_file($url);
$fields = $xml -> fields -> field;
GLOBAL $array;
GLOBAL $c;
$array = new stdClass;
foreach($fields as $field->attributes){
foreach($field->attributes->attributes() as $a => $b){
if($a == "name") {
$c = $b;
}
if($a == "type") {
$array -> $c = $b;
}
}
}
return json_encode($array);
}
echo readXML();
?>
I am making ajax call in the following way :
$.ajax({
cache: false,
url: "readXML.php",
type: "POST",
dataType: 'jsonp',
jsonp: 'jsonp_callback',
data: { schemaPath: "http://localhost:8983/solr/admin/file/?file=schema.xml" },
crossDomain: true,
success:function(data) {
if (!data) {
alert("Error in processing xml file");
return null;
} else {
console.log(data);
}
},
error:function(data) {
alert("Error while reading schema file.");
$("#loadingStatus").hide();
}
});
I am not getting the desired json response format. I get the alert Error while reading schema file in the response. I actually want it be as a key:value pattern like as $c:$b but it is coming like $c:{"0":$b}. How to return the array from the php script such that i can have a valid json response.
I got the solution why on completion of ajax call it was always going to the error function. Here i am doing
jsonpin the ajax call but was not handling the same in the php script. To solve this problem and to return a proper response need to add the following in the php script :And to make the response as
key:valueneed to change the$array[$c] = $b;to$array[$c] = (string)$b;along with the change pointed by @EmmanuelG in his answer.