I have a form which has a select tag that contains the numbers from 1-31. What I'm trying to do is update the database with the value in the select tag if the user changes it (the default value is the value in the database i.e $drop_d) WITHOUT reloading the page at all.
The following code doesn't seem to work, I think there is a problem in the way I am sending my data to ajax.
This variable contains the default value:
$drop_d = $e_r[drop_d];
The form:
<form> Number of days: <select name="dropD" id="dropID"> <?php for($i=1; $i<=31; $i++){ ?> <option value="<?php echo $i;?>" <?php if($i==$drop_d){ ?> selected="selected" <?php } ?> > <?php echo $i; } ?> </select> </form> <br />
Ajax:
<script>
$('#dropID').change(function(){
alert(1);
var url = document.URL;
var blah = $('#dropID').val()
alert(blah);
alert(url);
$.ajax({
type: 'POST',
url: url,
data: {newFieldValue: blah},
dataType: 'html'
}).done( function(){
alert(1);
blah.hide();
});
});
</script>
Update on database:
<?php
$newFieldValue = $_POST['newFieldValue'];
$updateD = 'UPDATE en SET drop_d = $newFieldValue WHERE name=$name;
mysql_query($updateD);
?>
$('select#dropID').on('change' , function(){
var url = document.URL;
var blah = $('select#dropID').val();
$.ajax({
type: 'POST',
url: url,
data: {newFieldValue:blah},
dataType: 'html'
});
});
You have defined an id value id="dropID, so your jQuery should be:
$('#dropID').val()
Related
I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my 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 are sending a POST parameter with the key "select" to the server in your AJAX call:
data: { select: $(type+'[name='+theName+']').val()},
In newtestx.php you are trying to retrieve the value from a POST parameter with the key "name" - which doesn't exist:
$name = $_POST['name'];
You could fix this easily by giving the parameter keys the same name. If you would look for $name = $_POST['select'] the parameter would be found.
Inline Javascript is considered bad practice and there's no need to echo out the HTML markup, it makes the mark up harder to work with.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="[link to your 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."---";
?>
You are sending post param select and trying to receive as $_POST['name'].
Make sure they match...either both as name or as select
First, Since you are using jQuery, why are you still using inline javascript?
Well I suggest you first to restrucure your code around the jQuery change event:
$(document).ready(function() {
$('select').change(function(e) {
e.preventDefault();
var selected = $('.select option:selected').val();
var id, theName, url= ...// get it from the DOM
$.ajax({
type: "GET",
url: url,
data: { select: selected},
error: function(xhr,status,error){alert(error);},
success:function(data) {
$('#'+id).html(data);
}
});
});
});
Second, why are you coding HTML with PHP, you are making yourself struggle and lose time only with quotes and double quotes, and no-needed spaces.
<form action="">
<select name="name">
<option value="1">1</option>
<option value="1">1</option>
</select>
</form>
<div id="output"></div>
This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>
How can I run a PHP query which only runs when an option is chosen from a select dropdown but also which refreshes each time a different option is chosen?
For example, here is the HTML:
<html>
<head>
<script type="text/javascript" src="/hr/includes/jui/js/jquery-ui-1.8.20.min.js"</script>
<script>
$(document).ready(function() {
$('#select_box_1').change(function() {
if($(this).val() != '')
$.ajax({
type: 'get',
url: 'balance1.php',
data: 'value' + $(this).val() ,
success: function(data) {
$("#result-div").html(data);
}
});
}
});
});
</script>
</head>
<body>
<form name="form" id="form" method="post" action="validate.php">
<div id="select_box_1">
<select name="drop_down">
<option value="">Please choose</option>
<option value="1">John</option>
<option value="2">Bob</option>
<option value="3">Mike</option>
</select>
</div>
<div id="result-div">
</div>
<input type="submit">
</form>
</body>
</html>
balance1.php
<?php
print "GET Value:".$_GET['value'];
?>
I would like to run a query below the select box depending on the value chosen - for example, when nothing is chosen there is no query ran. If the user chooses John from the list then the query runs where the id=1 and displays results for John. If the user then chooses Bob, the query should run again where the id=2 and so on?
This is working:
[...]
<select name="drop_down" id="sel_something">
[...]
$('#sel_something').change(function() {
if($(this).val() != '') {
$.ajax({
type: 'get',
url: 'someurl',
data: { 'value' : $(this).val() } ,
success: function(data) {
// do your stuff
}
});
}
});
I gave an id to the select and modified the data line (and added a few syntax corrections).
i suggest you to use jquery.ajax, which is way more powerful than you think mate ! below is the example code to make it working
$('#select_box_1').change(function() {
if($(this).val() != '')
$.ajax({
type: 'get',
url: 'URL To Your PHP Script',
data: 'value' + $(this).val() ,
success: function(data) {
$("#result-div").html(data);
}
});
}
});
EDIT : $_GET['value'] will hold the value in your php script, you can query database using that value and return your result or output to ajax call and then you can simply populate the data in your html view
If you are reloading the page everytime the value is changes in the dropdown, then you can use onchange attribute in your SELECT tag.
Reload the page when value is changed and set a GET variable in the URL. If this GET variable is NULL then do not process the PHP code ... else process accordingly.
Try something like this:
$("#select_box_1").change(function(){
if ($(this).val() != "") {
$.ajax({
type: "POST",
url: "foo.php",
data: "id=" + $("#select_box_1").val(),
success: function(msg){
$("#result").text(msg);
}
});
}
});
I have two pages in php and I need that the value of radioButton selection pass to another page, but it not work.
The jquery code of the page that send the data is:
$(document).ready(function(){
$("#continue").click(function(){
var val = $("input[#name='opt']:checked").val();
$.ajax({
type: 'GET',
url:'editor.php',
data:'radio=' + val,
dataTyoe:'html',
succes: alert(val)
});
});
});
The html code into the php page is:
<input type="radio" id="opt" name="opt" value="opt1" checked="checked">Opt 1<br/>
<input type="radio" id="opt" name="opt" value="opt2"/>opt2<br />
<input type="radio" id="opt" name="opt" value="opt3"/>opt3<br />
Guardar continuar<br/>
And the code of the page that recive data is the follow.
<?php
$valor = $_REQUEST['radio'];
echo $valor
?>
Thanks
There were some spelling mistakes and need some correction. Try the following code;
$(document).ready(function(){
$("#continue").click(function(){
var val1 = $("input[name='opt']:checked").val();
$.ajax({
type: 'GET',
url:'editor.php',
data:'radio=' + val1,
success: function(){
alert(val1);
}
});
});
});
you misspelled succes: it should be success:
You may have some errors : try replacing dataTyoe:'html' for dataType:'html', Also $("input[#name='opt']:checked") by $("input[#name=opt]:checked")... and the success callback too...
It would look like :
var val = $("input[#name=opt]:checked").val();
$.ajax({
type: "GET",
url: "editor.php",
data:'radio='+val,
dataType: "html",
async:false,
success: function(){
alert(val);
}
}
);
Also you could remove the link from the html :
Guardar continuar<br/>
Actually i want to send the value of checkbox when it is checked through jquery...means when i click on checkbox it has to send automatically...i tried with following code..
$(document).ready(function () {
$(".checkBox").change(function () {
var s = $(this).val();
var dataString = 's=' + s;
$.ajax({
type: "GET",
url: "xyz.php",
data: dataString,
cache: false,
success: function (html) {}
});
});
});
and html code is
<div class = "checkBox">
<input type = "checkbox" name = "select[]" value = <?php $friendUid?> />
</div>
I was unable to send to other page
Change your html: Put the class = "checkBox" onto the checkbox element
<div>
<input type = "checkbox" name = "select[]" value = <?php $friendUid?> class = "checkBox"/>
</div>
The selector $(".checkBox") will attach that function to any items with the class of checkBox, and since your checkbox does not have that as its class, you are actually attaching your function to the div that contains the checkbox instead, which of course will never trigger your function.
<?php $friendUid?> should be <?php echo $friendUid ?>
with $(".checkbox") you're referencing something of class 'checkbox' (i.e., your div, not the actual checkbox).
Add the class to the <input type='checkbox'> instead
try this in your code and let us know what happens.
<script type="text/javascript">
alert('check0');
$(document).ready(function () {
alert('check1');
$(".checkBox").change(function () {
alert('check2');
var s = $(this).val();
var dataString = 's=' + s;
$.ajax({
type: "GET",
url: "test.php",
data: dataString,
cache: false,
success: function (html) {
alert('check3');
}
});
});
});
</script>
<input type="checkbox" class="checkBox" />