i have a problem when it comes to retrieving value from jQuery to php.i was able to get the value of my select and pass it to my php but i can't pass it back to php. here is the code...
<script>
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
$.ajax({
type: 'POST',
url: "monthly_CRD.php",
data: {m: m},
success: function(){alert("updated")}
});
});
});
</script>
<div>
<select id="months">
<option value='00'>Month...</option>
<option value='01'>Jan</option>
<option value='02'>Feb</option>
<option value='03'>Mar</option>
<option value='04'>Apr</option>
</select>
<select id="years">
<?php
for($yr=10; $yr<=$year; $yr++)
{
echo "<option value='".$yr."'>".$years[$yr]."</option>";
}
?>
</select>
</div>
<?php
if (isset($_POST['m']))
{
$m = $_POST['m'];
echo $m;
} else {echo "fail";}
?>
it keeps on returning fail which means that isset is not working.
Change data: {m: m} to data: {"m":m}
Since you are looking at $_POST['m'] you need to define that key in your JSON. Currently you'd need to look inside $_POST['03'] if you selected Mar
If you mean that on page load, it returns fail, that is because on page load your $_POST array is probably empty.
If you want to know what was returned from your AJAX post, you need your success function to accept a parameter (like data) that jQuery will fill with the response to your post.
Then in the function body, you can write it to the DOM or your error console.
If you have an id to an element then just id is enough to select. Try this
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: { m: $(this).val()},
success: function(){
alert("updated")
}
});
});
});
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: '{ "m": "' + $(this).val() + '"}',
success: function(msg){
alert(msg)
},
error: function(msg) {
alert("An error happened: " +msg);
}
});
});
});
User fiddler of chrome tools to break on either success or error and check the value of the meesage property.
Related
I have tied for hours now to get the values value="oneyearanalysis" and value="oneyearanalysis", of each button when i press them, i tried with ajax. I think i am close but i get no output GetData but i do in my console.log(clikYear);. Hope you can help me
Best regards
Index.php
<div class="container" style="margin-top: 50px;">
<select name="button" id="button">
<option value="">Select...</option>
<option value="oneyearanalysis">1 year analyse</option>
<option value="fiveyearanalysis">5 year analyse</option>
</select>
</div>
$(document).ready(function(){
$("#button").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
}
});
getTableCall2.done(function(data){
console.log(data);
console.log(getTableCall2);
console.log(clikYear);
})
GetData.php
if(isset($_POST['clikYear']))
{
$year= $_POST['clikYear'];
}
$yearOfChoice = $year;
You were quite close to make it work. If you apply the simple recommandations below, you should save yourself that kind of trouble in the future.
First recommandation is to indent your code correctly.
You would have noticed the getTableCall2 variable is declared on select change. But "used" before that when trying to apply the .done() promise handler.
Below, I made no change to you code except the indentation.
The order of execution on document ready is:
Register the change handler (not executed)
Throw an error.
$(document).ready(function(){
$("#button").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
}
});
getTableCall2.done(function(data){
console.log(data);
console.log(getTableCall2);
console.log(clikYear);
})
Second recommandation is to use the console where you would have seen this error:
ReferenceError: getTableCall2 is not defined.
Third recommandation is to be a bit more creative with you class and id naming. .button used on a <select> just can lead to confusion. You can use the name you want. Make it meaningful! I'm sure you do not use the word door when you talk about a window in the real life...
So here is something that should work:
$(document).ready(function(){
$("#analysis_term").on("change",function() {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
var getTableCall2 = $.ajax({
url : "GetData.php",
type:"POST",
cache:false,
data:{clikYear:clikYear},
})
getTableCall2.done(function(data){
console.log(data);
})
}
});
});
And to test it, make sure the GetData.php outputs something in both cases:
$year = "No POST value!";
if(isset($_POST['clikYear'])){
$year= $_POST['clikYear'];
}
echo "The POST value is:" . $year;
The ID for your Select is "button" but you are using Class Selector instead. Try replacing . with # in front of button
HTML
<select id="button">
<option value="">Select...</option>
<option value="oneyearanalysis">1 year analyse</option>
<option value="fiveyearanalysis">5 year analyse</option>
</select>
JQuery
$("#button").on("change", function () {
var clikYear = $(this).val();
console.log(clikYear);
if (clikYear !== "") {
$.ajax({
url: "GetData.php",
type: "POST",
cache: false,
data: { clikYear: clikYear },
})
}
});
I want to get a jquery (a selectmenu) variable to php. I try it with Ajax "POST". For testing purpose i just want to echo out the selected number of the selectmenu without any page refresh. So the Change should appear dynamically.
Here is my html_file.php
<script> $( function() {
$( "#number" )
.selectmenu()
.selectmenu( "menuWidget" )
.addClass( "overflow" );
$.ajax({
method: "POST",
url: "php_file.php",
data: { number }
})
/* Here we receive the data back */
.done(function(data) {
/* Here you can do whatever you want with the data */
$("#response").html(data);
});
} );
</script>
<select name="number" id="number">
<option>1</option>
<option selected="selected">2</option>
<option>3</option>
</select>
<div id='response'></div>
And here the php_file.php
<?php
$test = $_POST['number'];
// Output of the selcetmenu for testing
echo '<div class="profile-font2">', $test, '</div>';
?>
I think there is some mistake in the Ajax function.
Pass key as number and assign value to number key as
$.ajax({
method: "POST",
url: "php_file.php",
data: { number : yournumber }
})
You have to give your data property a value.
Try:
$.ajax({
method: "POST",
url: "php_file.php",
data: {
number: $("#number").val()
}
})
I want to retrieve the value of my dropdown on change, and post it to my PHP (at the moment, the PHP is just var_dump, for debugging purposes)
I'm stuck at posting the selected value to my AJAX, seemingly there no change.
I Using WP framework to load scripts and run them through admin-ajax.php -- I've been
using this approach for others AJAX functions, and it is working.
I have a dropdown list, like this:
HTML
<form action="" method="post">
<select name="count" class="count">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<input class="koordinator_id" type="hidden" name="koordinator_id" value="<?php echo $_SESSION['coordinator_id'] ?>">
</form>
AJAX
$(document).ready(function () {
$('select.count').change(function () {
alert("Whyunoalert?");
$.ajax({
type: "POST",
url: (my_ajax_script.ajaxurl),
data: ({
action: 'generate',
koordinator_id: $('input[name=$"koordinator_id"]').val(),
id: $('select.count').val()
}),
success: function (msg) {
alert("Data changed:" + msg);
}
});
});
});
PHP
function generate() {
$count = $_POST['id'];
var_dump($count);
$koordinator_id = $_POST['koordinator_id'];
var_dump($koordinator_id);
}
EDIT
I've changed the code accordingly to the first three comments. Now my code executes the AJAX but still no var_dump are made in the php file. Thanks for the help so far, hope you can do a bit more. Also i've added the functions.php code , where the php function is bound and the redirect to ajax-admin.php is setup.
functions.php
function load_scripts() {
wp_enqueue_script('local_jquery', '/wp-content/themes/tutorial_theme/scripts/scripts.js');
wp_enqueue_script('ajax_func', get_template_directory_uri() . '/scripts/ajax_implementation.js');
}
if (!is_admin())
add_action('wp_enqueue_scripts', 'load_scripts');
add_action('template_redirect', 'load_scripts');
$dirName = dirname(__FILE__);
$baseName = basename(realpath($dirName));
require_once ("$dirName/ajax_functions.php");
add_action("wp_ajax_nopriv_approve", "generate");
add_action("wp_ajax_approve", "generate");
2nd EDIT
removed this from the ajax: (was from old copy-paste)
dataType: 'html',
The selector $('input[name=$"koordinator_id"]') is wrong in your data line. The syntax for input name ending with some string is $('input[name$=somestring]'].
Use this instead:
$('input[name$="koordinator_id"]') // '$' needs to be before '='
^
First of all if you are firing ajax onchange event why did you wrap them in the form tag? remove it if no use other than onchange event.
Second is you're using action: 'generate' in your ajax function but you're not hooking the right action in your functions file of php
add_action("wp_ajax_nopriv_YOUR_ACTION", "METHOD");
add_action("wp_ajax_YOUR_ACTION", "METHOD");
So it would be
add_action("wp_ajax_nopriv_generate", "generate");
add_action("wp_ajax_generate", "generate");
Last but not least always exit your ajax method call, so make sure it won't fall below.
function generate() {
$count = $_POST['id'];
var_dump($count);
$koordinator_id = $_POST['koordinator_id'];
var_dump($koordinator_id);
exit;
}
Also as #Krishna answer remove the $ sign unexpected expression
koordinator_id: jQuery('input[name=$"koordinator_id"]').val(),
Need to be:
koordinator_id: jQuery('input[name="koordinator_id"]').val(),
You're missing the { after the .ready(function(). Fix it like this:
$(document).ready(function () {
$('select.count').change(function () {
alert("Whyunoalert?");
$.ajax({
type: "POST",
url: 'my_ajax_script.ajaxurl',
data: ({
action: 'generate',
koordinator_id: $('input[name=$"koordinator_id"]').val(),
id: $('select.count').val()
}),
dataType: 'html',
success: function (msg) {
alert("Data changed:" + msg);
}
});
});
});
Try like this
$(document).ready(function()
$('.count').change(function() {
$.ajax({
type: "POST",
url: 'my_ajax_script.ajaxurl',
data: {'action': 'generate', 'koordinator_id': $('input[name=koordinator_id]').val(), 'id': $('.count').val()}),
dataType: 'html',
success: function(msg) {
alert("Data changed:" + msg);
}
});
});
});
Also avoid using of php short tags.Sometimes it cause problems if your php version doesnt support short tags.So change this
<input class="koordinator_id" type="hidden" name="koordinator_id" value="<?php echo $_SESSION['coordinator_id'] ?>">
I have a simple combo box whose value I can get in JavaScript.
I am doing that so I don't need to refresh the page.
Also I want to use the selected value to do some conditional branching after combo box so how do I get the value of combo box from JavaScript to my variable $change.
echo '<select id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '</select>';
Below is my JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
});
});
</script>
Here I want to do $change = $(this).val(), but obviously I cant do it like this.
Any suggestions?
i want to do it on the same page without refreshing or without submitting
my url kinda look like this
http://localhost/lms/grade/report/userdef/index.php
and i want it to be on click action
cuz depending on the choice of combobox 2 very different procedures will be called
You're gonna want to use AJAX and submit the form, then you can access the returned data without ever refreshing the page.
Basically:
HTML
<select name="combo" id="combo_1">
<option value="2">Submative</option>
<option value="1">formative</option>
</select>
JavaScript
$('#combo_1').change(function() {
$.post('calcScript.php', $(this).serialize(), function(data) {
alert(data);
});
});
in PHP, you can access your combo data via $_POST['combo'].
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
var combo_1 = $(this).val();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {'combo_1':combo_1},
success: function(data){
alert(data)
}
});
});
});
</script>
ajax.php
if( isset($_GET['combo_1]) ) {
echo $change = $_GET['combo_1'];
}
JS:
$.ajax({
type: "POST",
url: './filename.php',
beforeSend: function(){
//If you want to do something
},
data: 'data='$('#combo_1').val(), //Optional '&data2='+value+'&datan='+value,
success: function(msg){
alert(msg);
}
});
PHP:
$val = $_POST['data'];
return 'received successfully';
This will alert 'received successfully'
this is my Jquery:
$('#Save').click(function () {
var realvalues = new Array(); //storing the selected values inside an array
$('#Privilege :selected').each(function (i, selected) {
realvalues[i] = $(selected).val();
});
$.ajax({
type: "POST",
traditional: true,
url: "http://localhost:8081/crownregency/UpdateOrCreateOrDeleteUser.php",
data: {
Privilege: realvalues,
ID: '1'
},
success: function (data) {
alert(data, 'Status');
location.reload();
}
});
});
this is my php.
I have read quiet a lot about serializing but doesnt seem to work, what i am trying to achieve is sending the selected items of a dropdown into an array and sending it to a php through ajax. but sending the array to the php doesnt seem to work. help anyone?
Your code is okay just remove the traditional: true and your code seems to work
$('#Save').click(function(){
var realvalues = new Array();//storing the selected values inside an array
$('#Privilege :selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
});
$.ajax({
type: "POST",
url: "http://localhost:8081/crownregency/UpdateOrCreateOrDeleteUser.php",
data: {Privilege: realvalues, ID: '1'},
success:function(data){
$("#subscrres").html(data)
}
});
});
HTML
<form method="post">
<select id="Privilege" multiple="multiple">
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save"/>
</form>
UpdateOrCreateOrDeleteUser.php
<?php
if(isset($_POST['Privilege'])){
$myvar =$_POST['Privilege'];
foreach($_POST['Privilege'] as $one)
echo $one."<br/>";
}
?>