Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery AJAX POST not passing anything to PHP

Tags:

jquery

ajax

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.

like image 948
aleXela Avatar asked Dec 20 '12 00:12

aleXela


2 Answers

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 />'); 
        };

    }
});
like image 60
Ricardo Alvaro Lohmann Avatar answered Oct 14 '22 10:10

Ricardo Alvaro Lohmann


The difference being that in the non-working example, you are sending a string, and in the working example you are sending an object. So, send that same object in your non-working example.

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

    }
})
like image 3
thescientist Avatar answered Oct 14 '22 10:10

thescientist