post selextbox values to php page in jquery
I am using jquery button click to post all the values in a selectbox to a PHP page, but this code does not seem to work. Can anyone please help?
<script type="text/javascript">
$(function() {
$("#btn1").click(function () {
var arr= new Array;
$("#target_select option").each (function () {
// You can push the array on an array
arr.push( $(this).val() );
//alert( $(this).val() ); not getting the alert to display too
});
$.post("test.php", { name: arr } );
});
});开发者_如何学C
</script>
Generate
You have to make sure that the page you are $.post()
-ing to is on the same domain. Also, $.post()
is not a way to submit a form, it's an Ajax call that does not load the new page over the current page. So this works for me, loading the results of the POST into the body of the page.
<html>
<head>
<title>Test Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn1").bind('click', function () {
var arr= [];
$("#target_select option").each (function () {
arr.push( $(this).val() );
});
$.post("post.php", { 'name': arr }, function(data){
$('body').append(data);
} );
});
});
</script>
</head>
<body>
<form method="POST" action=".">
<select name="target_select" id="target_select">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option2</option>
</select>
<input type="button" value="btn1" id="btn1" />
</form>
</body>
</html>
Here's what I have in post.php
:
<?php
print "<pre>";
print_r($_POST);
print "</pre>";
?>
When I do this, I get this appended to my page:
Array
(
[name] => Array
(
[0] => option1
[1] => option2
[2] => option3
)
)
Try
arr.push( $(this).attr('value') );
instead
Try using the .attr("value")
instead of .val()
. I can't remember if .val()
works on <option>
tags, but I'm thinking not.
<script type="text/javascript">
$(function() {
$("#btn1").click(function () {
var arr= new Array;
$("#target_select option").each (function () {
// You can push the array on an array
arr.push( $(this).attr("value") );
//alert( $(this).attr("value") ); not getting the alert to display too
});
$.post("test.php", { name: arr } );
});
});
</script>
- EDIT -
I found the same as Art (comment below) when I was putting together that jsFiddle.
.attr("value")
and .val()
are the same on <option>
tags.
I would delete this answer, but I think people may benefit from the clarification posted in the comments and whatnot (since there is another answer stating the same).
精彩评论