jquery - Ajax not working on select tag, PHP, AJAX -
i'm trying use ajax on select tag 2 options, it's not getting $_post reason. prints out "---", not print out $_post value, either 1 or 2. i'm not sure did wrong. please take @ code:
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type = "text/javascript"> function ajax(url,type,thename,id) { $.ajax({ type: "post", url: url, data: { select: $(type+'[name='+thename+']').val()}, error: function(xhr,status,error){alert(error);}, success:function(data) { document.getelementbyid( id ).innerhtml = data; } }); } </script> <?php echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>"; echo "<option value = '1'> 1 </option>"; echo "<option value = '2'> 2 </option>"; echo "</select>"; echo "<div id = 'output'></div>"; ?>
newtestx.php
<?php $name = $_post['name']; echo $name."---"; ?>
you sending post parameter key "select" server in ajax call:
data: { select: $(type+'[name='+thename+']').val()},
in newtestx.php trying retrieve value post parameter key "name" - doesn't exist:
$name = $_post['name'];
you fix giving parameter keys same name. if $name = $_post['select']
parameter found.
inline javascript considered bad practice , there's no need echo out html markup, makes mark harder work with.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="[link javascript file here]"></script> <select name='numbers' class="postvalueonchange" data-id-to-update="output" data-post-url="newtestx.php"> <option value='1'>1</option> <option value='2'>2</option> </select> <div id='output'></div>
javascript file
$(document).ready(function () { $('.postvalueonchange').change(postselectedvalue); function postselectedvalue(e) { var $self = $(this); var url = $self.data('post-url'); var $elementtoupdate = $('#' + $self.data('id-to-update')); var jqxhr = $.ajax({ type: "post", url: url, data: { selected: $self.val() } }); jqxhr.done(function (data) { $elementtoupdate.html(data); }); jqxhr.fail(function (jqxhr, textstatus, errorthrown) { alert(errorthrown); }); } });
newtestx.php
<?php $name = $_post['selected']; echo $name."---"; ?>
Comments
Post a Comment