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'] ?>">
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 use this to pass an argument (fullname).
<script type="text/javascript">
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
document.location.href="{$_SERVER["PHP_SELF"]}?fullname="+fullname;}
</script>
Is there a way to pass the argument such that it can NOT be seen in the http URL?
I know about POST.
$listboxselected = $_POST['listbox'];
I would use POST instead, so that the argument is not present in the URL, but I can't, because I'm using the javascript as an On Click event.
<select id="listboxid" name=listbox onChange="listbox_update()"></br>
The On Click event works perfectly. But I don't like seeing all my variables in the URL.
If you want to do that only by JS then you can go with Ajax.
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
$.ajax({
data: { fullname: fullname },
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
//some function here
}
});
}
Wrap the <select> in a <form> and then in onchange submit the form.
<form id="form" method="post" action="<?=$_SERVER["PHP_SELF"]?>">
<select id="listboxid" name="fullname" onChange="listbox_update()">
<option>here the options</option>
</select>
</form>
and the listbox_update
function listbox_update () {
document.getElementById('form').submit();
}
Another option would be to use Ajax, but since your original script reloads the page, then the first approach follows this way.
You have only 2 solutions for this:
1) Either you must implement AJAX like below:
function listbox_update()
{
var fullname = $("#listboxid").val();
$.ajax({
data: "fullname="+fullname,
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
console.log("Message :"+msg);
}
});
}
2) Or go with form submission.
function listbox_update()
{
$('#your_form_id').attr('action', <?php echo $_SERVER["PHP_SELF"]; ?>);
$('#your_form_id').submit();
}
Ok so im trying to start an ajax call after the first call has completed. I have a form with 3 drop down menus. The first menu onload runs the script to bring back values. I then want to feed the vale into the second script and run the script to populate the second 3rd menu.
the second dropdown is populated onChange of the first. This works great. I then want the result of that feed into to third drop down. I know my external queries are right I just think the ajax is wrong. Here is my Ajax calls....
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});
function get_cities(networks)
{
$.ajax({
type: "POST",
url: "select.php",
beforeSend: function () {
$("#folder").html("<option>Loading ...</option>");
},
data: "idnetworks="+networks +"&par="+ <?php echo $row_rs_doc['parentid']; ?>,
success: function(msg){
$("#folder").html(msg);
}
});
}
</script>
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function() {
jQuery('#folder').trigger('change');
});
function get_sub(folder)
{
$.ajax({
type: "POST",
url: "select2.php",
beforeSend: function () {
$("#subfolder").html("<option>Loading ...</option>");
},
data: "iddocs="+folder,
success: function(msg){
$("#subfolder").html(msg);
}
});
}
</script>
ok here are the form fields
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
<?php create(network, networkid, netname);?>
</select>
<select name="folder" id="folder" onChange='get_sub($(this).val())'>
</select>
<select name="subfolder" id="subfolder">
</select>
KISS it. Just put the second ajax call inside the success of the first one
You can use deferred objects, which will allow you to initiate additional actions without having to rewrite your existing event handler, and without nesting your code too much:
var req1 = $.ajax(...);
req1.done(function() { ... } ); // start your second request
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.
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.