aleXela aleXela - 2 months ago 7
Ajax Question

Jquery AJAX POST not passing anything to PHP

I'm having a problem passing variable using POST method with AJAX.Jquery

Here is my code:

ajaxtest.php

<?php
$dir = $_POST['dir'];
$scaned = glob($dir."*",GLOB_ONLYDIR);
echo json_encode($scaned);
?>


ajaxtest.html

<html>
<head>

<script type="text/javascript" src="js/jquery.js"></script>

</head>
<script>

$(document).ready(function(){
$('button[type="button"]').click(function(){
var dir = 'gals/';
$.ajax({
url: "ajaxtest.php",
type: "POST",
data: dir,
success: function(results){
data = jQuery.parseJSON(results);
for (var i = 0; i < data.length ; i++) {
$('#buttonA').after('<br />'+data[i]+'<br />');
};

}
})
})

})
</script>
<body>
<br />
<button id="buttonA" type="button">Test button</button>

</body>
</html>


This code not working.

But this one do: (but not with json)

$.post("ajaxtest.php", {dir:dir}, function(results){
var data = $.parseJSON(results);
for (var i = 0; i < data.length ; i++) {
$('#buttonA').after('<br />'+data[i]+'<br />');
}
})


why so?!
What is wrong in my code? please advice!
Thanks a lot.

Answer

data should have the following format:

data: {
    'dir': dir
}

It doesnt work with json because the success parameter name is wrong. It's not according to the code inside the callback.
Change it from results to data.

var dir = 'gals/';
$.ajax({
    url: "ajaxtest.php",
    type: "POST",
    data: {'dir': dir},
    success: function(data){
        data = jQuery.parseJSON(data);
        for (var i = 0; i < data.length ; i++) {
            $('#buttonA').after('<br />'+data[i]+'<br />'); 
        };

    }
});