Reputation: 1301
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.
Upvotes: 9
Views: 3586
Reputation: 12574
the url field has a trailing slash that can made it not working so:
url:'mypath/'
had to be:
url:'mypath'
Upvotes: 0
Reputation: 26320
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 />');
};
}
});
Upvotes: 8
Reputation: 2948
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 />');
};
}
})
Upvotes: 3