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>';
}
}
Related
I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`
I am working on project that uses a dynamic or dependent dropdown list on CodeIgniter. This is my noob logic, the country value from Views passed to Models, then the Models get state data with same country value from Views, then Controllers get state data from that Models and pass it again to Views. And the problem is the state dropdown list show nothing.
Sorry, iam new in coding.
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model(){
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
}
function get_state_model(){
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
}
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function(){
$('#formCountry').change(function(){
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: {country_id:country_id},
success: function(data) {
$('#formState').html(data);
}
});
});
});
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
Thanks for your help.
You should not directly call model, instead call the Pkl controller, I'm assuming that you are using the index() method on Pkl controller :
$(document).ready(function () {
$('#formCountry').change(function () {
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data: {
country_id: country_id
},
success: function (data) {
$('#formState').html(''); // empty the select option element
$.each(data, function(){ // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
});
}
});
});
});
In my php code, I have two dropdowns which is the other one depends on the first one.
Here is the first dropdown:
<select class="form-control style" id="sel" >
<option style="color: black;" >Select...</option>
<?php foreach ($dtype as $row ) { ?>
<option style"color:black;" value="<?php echo $row['donations_type_id'];?>"> <?php echo $row['donations_type_name'];?></option>
<?php }?>
</select>
<tr>
<td>Available Donation:</td>
<td style="color: black; ">
<select name='avail' id='avail' class="form-control style" >
<option style="color:black;" value="">Select...</option>
</select>
</td>
</tr>
The second dropdown shows the data that corresponds whatever the user selects from the first dropdown.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
type: "POST",
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
success:function(data){
$("#avail").html(data);
}
});
});
});
</script>
In my controller:
public function showAvailable()
{
echo $id = $this->input->post('id', true);
$data['package'] = $this->Beneficiary_model->getDtype($id);
$output = null;
foreach ($data['package'] as $row ) {
$output.="<option value='".$row->package_id."'>".$row->package_name."</option>";
}
echo $output;
}
And in my model:
public function getDtype($id){
$this->db->select('package_id','package_name');
$this->db->from('package_table');
$this->db->where('package_type', $id);
$query = $this->db->get();
return $query->result();
}
When I tried to run the code and debug it through F12, it shows there that POST http://localhost:8999/samp/sampModule/showAvailable/2 404 (Not Found)
Why is it?
Can anyone help me with this error?
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
Take $(this) out of ajax object. It points now to ajax object itself. Try:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
**UPDATED**
Also, if the data is received from the server correctly but dropdown is still not rendered, the issue might be with the dataType property. There may be some problems with the response mime type, that cause the problem with the Intelligent Guess and data is treated as a json or xml string, so you can try to set it explicit:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
type: "POST",
dataType: 'html',
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
success:function(data){
$("#avail").html(data);
}
});
});
I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work
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);
}
});
});
});