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 },
})
}
});
Related
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 "connect" a select with a input text without refresh the page
This is my example
<select name="name_select" id="my_select">
<option value="1">first</option>
<option value="2">first</option>
<option value="3">first</option>
</select>
<?php ...query(SELECT name FROM table WHERE id = value) ?>
Then in var $name there is value from db
<input type="text" value="<?php echo $name; ?>" />
I think I must use jquery post/get but how to update only var that I need to check db?
Like Thamizhan say in comment, you need to use AJAX.
Here is a simple example :
HTML (index.html)
<select name="name_select" id="my_select">
<option value="1">first</option>
<option value="2">first</option>
<option value="3">first</option>
</select>
JS
$('#my_select').on('change', function () {
var selectData = $(this).val();
$.ajax({
type: "POST",
url: "custom.php",
data: {'selectData': selectData },
success: function (json) {
// do things
}
});
}
PHP (custom.php)
if (isset($_POST['selectData'])) {
var_dump($_POST['selectData']); // $_POST['selectData'] is the selected value
// query here
// and you can return the result if you want to do some things cool ;)
}
$("#my_select").on("change", function () {
$.ajax({
url: "phpfile.php",
method: 'POST',
data: {val: $(this).val()},
success: function (data) {
$("[type='text']").val(data);
}
});
});
In phpfile.php
include("db.php");
// ... your code ...
// execute sql(SELECT name FROM table WHERE id = value) and return value.
Please clear one thing why you need sql query here.
<option value="1">first</option>
first is name and 1 is option there. then we can put first or 1 into input box without using sql and ajax.
use only jquery for this
$(document).ready(function(){
$("#my_select").change(function(){
var thisval = $(this).val();
$("input").val(thisval);
});
});
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 am trying to implement ajax when the button is clicked, but the ajax is not wroking, can anyone tell me what's wrong, many thanks! what I want is that when click the "Move marked to set" button, in the "formstatus" div should display some message I defined in the addtoset.php, but currently it direct to to "#"page instead of remain on the same page
here is my ajax code
$('#movetoset').click(function() {
var fail="";
var hint="";
if ($('#selectsett').val() === 'General') {
fail += "Please chooose a set.\n";
}
for(j=0;j< array_str_idnum.length;j++)
{
if( document.getElementById('check' + array_str_idnum[j]).checked ==false){
hint='1';
}
}
if(hint=="1"){
fail += "Please check all the box.\n";
}
if(fail == ""){
var str = $("#complicated").serialize();
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg)
{
$("#formstatus").ajaxComplete(function(){
$(this).fadeIn("slow").html(msg)
});
}
});
return true;
}else{
alert(fail);
return false;
}
});
here is my html code
<form id ="complicated" method = 'post' action = '#'>
<div class="fancybuttonwrapper" style="margin-left:480px;"><span class="button"><span>
<input type="submit" class="form_button" id="movetoset" value=" Move Marked to Set"></span></span> </div>
<select name="sets" id ="selectsett">
<option value="General">Select Set</option>
<option value="Ceremony">Ceremony</option>
<option value="Lunch">Lunch</option>
<option value="Garden">Garden</option>
<option value="Longname">This is max length</option>
</select>
</div>
<div id="formstatus"></div>
</form>
your array array_str_idnum is not defined.
Further, you have to return false, else your form gets posted and so no ajax call at all.
Try this script. (always return false when you are in a form, else it gets send)
$('#movetoset').click(function() {
console.log("here")
var fail = "";
var hint = "";
if ($('#selectsett').val() === 'General') {
fail += "Please chooose a set.\n";
}
var str = $("#complicated").serialize();
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg) {
$("#formstatus").ajaxComplete(function() {
$(this).fadeIn("slow").html(msg)
});
}
});
return false;
});
check out: http://jsfiddle.net/wRNQv/5/ there is a running version.
Add fail handler to Ajax call and see what you get as error
error: function(xhr, textStatus, errorThrown){
}
The problem is you do not prevent the default action from executing. So the request may be started, but the page immediately redirects to different URL (defined in form's action).
Change the following part of the code:
$('#movetoset').click(function() {
var fail="";
into the following:
$('#movetoset').click(function(event) {
event.preventDefault(); // prevent form from submitting
var fail="";
It should help. Please let me know if it did.
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.