populate dependent select box through ajax call in wordpress - javascript

I want to poulate cities on behalf of selected state in select box. I am able to get the id of the selected state but unable to pass that state id to php function to get array of dependent cities. All this is in wordpress.
<script type="text/javascript">
$(document).ready(function()
{
function ajaxSubmit(){
var stateId = $(this).val();
// alert("SID"+stateId);
jQuery.ajax({
type:"POST",
action:'getDist',
data: stateId,
url: "<?php echo $adminUrl; ?>"
});
}
$('#billing_state').on("change", ajaxSubmit);
});
</script>
Above ismy ajax call and below is my php function to which i want to pass state id..
<?php
function getDist($id){
global $wpdb;
$dists = $wpdb->get_results("select name from cities where state_id = ".$id);
if($dists === FALSE):
echo $wpdb->error;
else:
foreach($dists as $dist){
echo"<option value=".$dist->name.">".$dist->name."</option>";
}
endif;
}
add_action('wp_ajax_getDist', 'getDist');
?>
after this i get nothing in cities select box..

Not totally wrong approach...I was just missing the acction function in ajax..
here's update..
$.ajax({
type:"POST",
url:"<?= admin_url('admin-ajax.php') ?>",
data:({
action:'get_city',
state_id:stateID
}),
success:function(response){
$("#billing_city").html(response);
}
});

Related

Setting a session variable in PHP using AJAX

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

Passing JavaScript variable to PHP on dropdown change

I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.
//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Making my combo boxes independent in PHP and JQuery

I'm having some trouble with populating combo boxes with database content depending on what the user chooses in another combobox.
It works fine when I use one 'pair' of boxes. COUNTRY -> PLAYER. But when I add several COUNTRY->PLAYER on the same page, all my players get chosen by the first COUNTRY BOX.
Here is a snap of my code, it is created from this webpage example:
<script type="text/javascript">
$(document).ready(function(){
$(".country").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-search.php",
data: dataString,
cache: false,
success: function(html){
$(".player").html(html);
console.log(id);
}
});
});
});
</script>
while ($row = mysql_fetch_array($result)) {
$counter++;
echo '<select class = "country" name="singleBetTeam[' . $counter . ']">';
echo "<option selected = 'selected'> COUNRTY</option>";
while ($row = mysql_fetch_array($result2)) {
$data = $row['team_name'];
echo '<option value="'.$data.'">'.$data.'</option>';
}
echo '</select><select name="singleBetStar[' . $counter . ']" class="player">';
echo '<option selected="selected"> PLAYER </option></select>';
}
The problem is that when I choose Germany in the first Combobox, then I get the German players all of the other combo boxes for player. This is depending on the fact that I check for class="player" in the javascript but I don't know how to create this connection?
You should only update the combobox following the one that the user changed, rather than all elements matching the player class. You can use the context: option to $.ajax to pass the changed element to the callback.
$(document).ready(function() {
$(".country").change(function() {
var id=$(this).val();
$.ajax ({
type: "POST",
url: "ajax-search.php",
data: {id: id},
cache: false,
context: this;
success: function(html) {
$(this).next(".player").html(html);
console.log(id);
}
});
});
});

Data from all the dynamically generated input fields doesn't go to database

I regenerate the input fields by calling an external PHP function which generates those fields with the help an ajax function, but the save function doesn't save data from all the fields but only the data from last row is saved to database..
Code for ajax function to regenerate these fields looks like this:
var counter = 0;
function loadfields_addmore(checked)
{
$jd.ajax({
url: "<?php echo JURI::root(); ?>",
type: "POST",
data: {'option':'com_joomd', 'view':'itempanel', 'task':'loadfields', 'typeid':<?php echo $this->cparams->typeid; ?>, 'catid[]':checked, 'id':<?php echo (int)$this->item->id; ?>, "<?php echo jutility::getToken(); ?>":1, 'abase':1}
});
}
For save button that triggers the save process:
function save(task) {
var data = $jd("form[name='<?php echo $array['editform']; ?>']").serializeArray();
$jd.ajax({
url: "<?php echo $url; ?>",
type: "POST",
dataType:"json",
data: data
});
}
The actual save function is like this:
function store()
{
foreach($post['cats'] as $cat) {
$query = 'insert into #__joomd_item_cat values('.$cat.', '.$row->id.')';
$this->_db->setQuery( $query );
}
}
The image shows the form..
The data from all the fields is not going to the database..
If I understand correctly, it seems like some form elements are created on the fly through jQuery. These will not be posted as they are not part of the original source code but were added later.
Use on() to get fields that were created on the fly.
Your parameters will be 'click',buttonid,next static parent of button.

Categories