Making my combo boxes independent in PHP and JQuery - javascript

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);
}
});
});
});

Related

populate dependent select box through ajax call in wordpress

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);
}
});

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.

Using AJAX and PHP to change combobox choices

I've been trying and struggling all morning to get my combobox to update properly. Once a user selects and option in the first box I want to then populate a second box with options applicable to the first option chosen. I have written a separate php script to take in the option chosen and pull from the sql database the applicable return. This script works fine when run by itself but I cannot get it working within the javascript using AJAX
PHP:
<?php
$name=$_GET['name'];
// select box option tag
$selectBoxOption1 = '';
// connect mysql server
$con=mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mysql',$con);
$sql1 = "SELECT DISTINCT bike_type FROM bc_fit WHERE name='$name'";
$result1 = mysql_query($sql1);
// play with return result array
while($row = mysql_fetch_array($result1)){
$selectBoxOption1 .="<option value = '".$row['bike_type']."'>".$row['bike_type']."</option>";
}
// return options
echo $selectBoxOption1;
?>
Javascript (#nap2 is the current box and #nap 4 the next):
$("#nap2").change(function(event){
var selected = $(this).find('option:selected').text()
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
//need to get options based upon nap 2 choice by calling php script with selected and returning all unqiue bike under that name
var options4;
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: "name"=selected,
success: function(data) {
options4 = data;
}
});
$('#nap4').append($(options4));
});
You have a few issues in your jQuery:
<select id="nap2" class="napkeeComponent napkeeCombobox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="2">Three</option>
</select>
<select id="nap4" class="napkeeComponent napkeeCombobox" disabled>
</select>
<script>
$(document).ready(function() {
$("#nap2").change(function(event){
// You just get the value of selected input
// You don't need to find anything because you've already selected it
var selected = $(this).val();
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$.ajax({
type: "GET",
url: 'getbiketype.php',
// Your creation of the data object is incorrect
data: { name: selected },
success: function(data) {
console.log(data);
// Here just append the straight data
$('#nap4').append(data);
}
});
});
});
</script>

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>

submitting form with ajax and php

Hi I have a page that lets a user view results for a certain tournament and round
User will select sport then tournament is populated based on sport selection then user will select round which is populated based on tournament selection
When all is done user press Submit button which will look up the results for the result based on tournament and round selected
My code is working great:
mainPage.php
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
get_sport.php
<label>Sport :</label>
<form method="post">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
get_round.php
if($_POST['id'])
{
$id=$_POST['id'];
$sql="SELECT DISTINCT round FROM events WHERE tournament='$id'";
$result=mysql_query($sql);
?>
<option selected="selected">Select Round</option><?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['round'] ?>"><?php echo $row['round'] ?></option>
<?php
}
}
?>
EXAMPLE
Sport=>Football; Tournament=>EPL; Round=>5;
Assuming the above is selected when the user clicks submit the code will query select results from someTable Where sport='Football' AND...
My Problem
I get the data from the selectboxes by using a simple php isset() function
if(isset($_POST['submit'])){
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
:
:
Now my problem is when submit is clicked everything works BUT the form gets reloaded, which is what I don't want
Im looking for an AJAX equivalent of isset() or a way for the data to be submitted without the form reloading
Any ideas/help will greatly be appreciated
There is a different ways to avoid the reload of a submit form.
A solution would be to handle the submit action of the form and return 'false' ( Example here and here) or preventing the default action ( Example here )
You can also replace the input type submit for an input type button (or button), and handle the click button action instead of handling the form submit action. This would be an easy workaround to most of your 'form submit' problems, but is a worst solution in the semantic and valid code point of view.
You can do the form submission from JQuery as an AJAX request and do the resulting in the success.
jQuery(document).ready(function(){
jQuery('#form').submit(function(ev) {
$.ajax({
url : 'url',
type : 'POST',
dataType: 'json',
data : $('#form').serialiseArray(),
success : function( data ) {
// Populate the result
}
});
ev.preventDefault();
});
});
Initially load all the values in Sport: Dropdown
Then dynamically populate the Tournament and Round
// To Trigger Sport Change
$(".sport").change(function () {
var selected_sport = $(".sport").val();
var dataString = 'sport=' + selected_sport;
var urlAddress = "get_sport.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".tournament").html(result_data);
// This will append the tournament drop-down dynamically
}
});
});
// To Trigger Tournament Change
$(".tournament").change(function () {
var selected_sport = $(".sport").val();
var selected_tournament = $(".tournament").val();
var dataString = 'sport=' + selected_sport + '&tournament=' + selected_tournament;
var urlAddress = "get_round.php";
$.ajax({
url: urlAddress,
cache: false,
method: 'post',
data: dataString,
dataType: 'html',
success: function (result_data) {
$(".round").html(result_data);
}
});
});
In your Corresponding PHP get_round.php
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
foreach ($row as $r) {
$round = $r['round'];
echo '<option value = "' . $round . '">' . $round . '</option>';
}
}

Categories