I want to get some data via ajax from a php file: this my code:
jQuery("#load").click(function(){
$.ajax({
type: 'POST',
url: 'setting/php/get_pic.php'
}).done(function (data) {
// Bei Erfolg
console.log("done:" + data);
});
});
PHP code:
$images = glob("BILDER/{*.jpg,*.JPG}", GLOB_BRACE);
print_r($images);
Now I want to write the array, bit I get the whole PHP script code
In AJAX
add dataType: 'json'
jQuery("#load").click(function(){
$.ajax(
{
type: 'POST',
url: 'setting/php/get_pic.php',
dataType: 'json' //Add this line
})
.done(function (data) {
console.log("done:" + data);
});
});
And in PHP
end use die()
or echo
instead of print_r()
$images = glob("BILDER/{*.jpg,*.JPG}", GLOB_BRACE);
die(json_encode($images)); //or echo json_encode($images);
Try. (Eg.)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Example</title>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
$.ajax(
{
type: 'POST',
url: 'setting/php/get_pic.php'
}).done(function (data) {
// Bei Erfolg
jsonObj = JSON.parse(data);
var img = "";
for(i in jsonObj)
{
img += jsonObj[i]+"<br/>";
}
$("#jsonParsedResult").html(img);
});
});
</script>
</head>
<body>
<div id="jsonParsedResult"></div>
</body>
</html>
PHP Code:
<?php
$images = glob("BILDER/{*.php,*.PHP}", GLOB_BRACE);
echo json_encode($images);
?>