Cascading dropdown list in Codeigniter not working - php

In one of my View, i have a modal popup containing 2 dropdown lists (ddlPublications & ddlEditions).On page load, ddlPublications will be populated while ddlEditions will remain empty.However, ddlEditions will be populated on the onchange event of ddlPublications.
View
<div class="modal-body" style="height: 100%;">
<div class="col-md-12">
<div class="form-group">
<label>Publication</label>
<select id="ddlPublication" name="ddlPublication" class="form-control" onchange="load_editions(this.value)">
<option value="0">--select--</option>
<?php
foreach ($pub_data as $key => $pdata) {
?>
<option value="<?php echo $pdata['pub_id'];?>"> <?php echo $pdata['pub_title'];?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Edition</label>
<div id="edn_div_data">
<select id="ddlEdition" name="ddlEdition" class="form-control">
<option value="0">--Select--</option>
</select>
</div>
</div>
</div>
</div>
<script>
function load_editions(pub_id){
alert(pub_id);
var p_id = pub_id;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>pmachine/pages/get_editions/"+pub_id,
dataType: 'json',
success: function(result){
$("#edn_div_data").html(result);
},
error: function(result) {
$("#edn_div_data").html("Sorry, something went wrong");
}
});
}
</script>
CONTROLLER
public function get_editions($pubid)
{
$data['edn_data'] = $this->Process_pages_model->pop_editions($pubid);
echo json_encode($data);
}
Problem
ddlEditions is not getting populated.It shows the message 'Sorry, something went wrong'.Please suggest what's wrong with my code.

It's hard to tell what the issue could be here because I see several places it could be failing. First of all, make sure you have debugging on. You can use the built in profiler https://www.codeigniter.com/userguide3/general/profiling.html or I believe you can use xdebug with a little manual setup. Now let's debug.
Start by replacing url in your ajax request with an actual url. So replace
<?php echo base_url(); ?>pmachine/pages/get_editions/ with the actual url, something like
localhost/pmachine/pages/get_editions/
Try creating a simple ajax example to make sure you have a good handle on it. Here is a question about basic php/ajax examples that you can use for reference:
Basic PHP and AJAX
Try echoing $data['edn_data'] rather than just $data.
Echo a string rather than $data to make sure you're even getting a response.
print_r($this-> Process_pages_model->pop_editions($_POST['pubid'])); to make sure you're getting the info from the database. If you're not getting anything, make sure you're connecting to your database with a basic connection test:
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
print_r($_POST['pubid']); to make sure you're getting your post data
Try returning the data without encoding it as JSON and remove the
dataType:json from your ajax request.

try to change your ajax pist function and your controller like this:
$data['edn_data'] = $this-> Process_pages_model->pop_editions($_POST['pubid']);
Ajax call
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>pmachine/pages/get_editions/"
data: {pubid: pub_id},
dataType: "json",
cache:false,
success: function(result){
$("#edn_div_data").html(result);
},
error: function(result) {
$("#edn_div_data").html("Sorry, something went wrong");
}
});

Your ajax success function replace the whole 'edn_div_data', which I doubt you rebuild the DOM within the result.
Try to console.log the result, and assume the result is:
{"edn_data":[{"edn_id":"1","edn_title":"Edition 1"},{"edn_id":"2","edn_title":"Edition 2"},{"edn_id":"3","edn_title":"Edition 3"}]}
and replace your ajax success function become like:
success: function(result){
for (var i = 0; i <= result.edn_data.length - 1; i++) {
$("#ddlEdition").append("<option value='"+result.edn_data[i].edn_id+"'>"+result.edn_data[i].edn_title+"</option>");
}
},

Related

Reload data continuously with Ajax

I have a page with some bootstrap cards. Information showing inside the card is retrieved from MySQL database.
What I need
I need these cards to be updated every 3 seconds without reloading the page. I know that Ajax is the way to do this (Update content without refreshing page). I am not familiar with Ajax. However, I tried as below
<script>
setInterval(
(function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return x;
})(), 3000);
</script>
Also I gave the following div with id inputFieldDisplay as below
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
My Issue
When I redirect to the mentioned page vTagInfoCall.php with all my php codes and contents, it is not loading anything to the div with id inputFieldDisplay. Did anyone know what am I doing wrong here?
Edit 1
Following is my vTagInfoCall.php file contents
<?php ob_start();?>
<?php include "db.php"; ?>
<?php
$tagQuery = "SELECT * FROM vtagdetails WHERE status = 0";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
$openItems = mysqli_num_rows($tagQueryExecute);
while($tagQueryRows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $tagQueryRows['srNumber'];
$Name = $tagQueryRows['Name'];
$Code = $tagQueryRows['Code'];
$customerName = $tagQueryRows['customers'];
$Type = $tagQueryRows['Type'];
session_start();
echo '<form method="post"> <div class="card cardBodyStyle">
<div class="card-body" >
<div class="row">
<input type="text" name= "srNum" value = "'.$srNumber.'" hidden>
<input type="text" name= "tpCode" value = "'.$Code.'" hidden>
<div class="col-sm"><i class="fab fa-500px"></i> '.$Name.'</div>
<div class="col-sm"><i class="fas fa-atom"></i> '.$Type.'</div>
<div class="col-sm"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
</div>
</div></div></form><br>';
}
?>
Edit 2
It is showing the following error in console. Can someone help why is the error?
I found two issues in code:
First in your script, please use below code:
<script>
setInterval(x, 3000);
function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
})
}
</script>
Second one is remove # from your id of div because # is just use to indicate id of element in jquery and .(dot) for class name of element. Please update your code with below code:
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
You can use directly in setInterval function
setInterval(function()
{
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
}, 3000);//time in milliseconds
And the problem is in Html div also as showed by madhuri and haisen.
Whenever you used attributes(name,id,class whatever) you dont need to put dot,# or other symbols in the div or input.
So please fix it. I think it will work definitely.
<div id="#inputFieldDisplay"></div> // Wrong because of #
<div id="inputFieldDisplay"></div> //Right
you html code with some incorrect in id="#inputFieldDisplay"
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
After many trials and methods, found out that I was using CDN of slim version of jQuery which caused this problem. Somehow there is some issue with Ajax in the slim version
I solved it by using the uncompressed version of jQuery CDN from here and that is it!!

Display MySQL queries on the same page

I've been searching for a while but nothing I've found match what I need.
I've got a form with 2 variables (dropdownlist) to query a DB (PHP and SQL).
Names of my variables are : "province" and "candidat".
My result page is action.php with all the sql/php code for the results.
Everything is going very fine except that after clicking on the submit button, a new page is opening : action.php with the results of my request.
Now, I wish to display this results on the same page as my form (id = form). The id of the div to display results is"success" (<div id="success">). There is an action on my form : action="action.php", should I remove it ?
I know that I have to use AJAX method but nothing that I've found match my needs. The other point is that I wish to be able to make another query and display the new results in this area.
If you know the solution or a tutorial that fit my needs... MANY THANKS of your help !
Start here: http://api.jquery.com/jQuery.ajax/
And do something along the lines of this:
$.ajax({
url: "action.php",
cache: false
}).done(function( response ) {
alert( response );
$("#success").html(response); //put the response into a DIV with id="success"
});
I'd recommend being more specific with your HTML id's that you are using.
$(document).ready(function(){
var datastring = "your data that is pass for php file";
$.ajax({
url: "action.php",
data: datastring,
type: "post",
success: function(response) {
alert(response);
}
});
});
Here's the code :
PROVINCE
">
<?php
}
?>
</select>
CANDIDAT
<?php
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
?>
<option value="<?php echo $data['id_candidat']; ?>">
<?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>
<?php
$id = $data['id_candidat'];
if ($id === $id)
{break;}
}
?>
</select>
<br/>
<input type="submit" class="submit" name="submit" value="ok" />
</form>
Content of action.php :

issue sending and retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>

updating combo values

I have a combo that simply displays some mysql databases. I also have a form that creates a database. I would like to dynamicly refresh the combo (if possible) to also display the new database created by the form. here is a snippet of the code:
<div id="tools">
<P>Add a Set list:<br>
<LABEL for="labelName">Set List Name: </LABEL>
<INPUT type="text" name="slName" id="slName"><button id="createSL" value="Create Setlist">Create Set</button>
</P><br>
<P>Delete a Set list:<br>
<? include("remSLcombo.php"); ?> <button href="#" type="button" id="delSl">Delete Setlist</button>
</P>
<p>Check how to reload combos</p>
</div><BR>
<? include("combo.php"); ?>
The Jquery function that is called to create the database:
$('#createSL').click(function(){
var sendIt = $("#slName").val();
$.ajax({
type: "POST",
url: "createSL.php",
data: {slName : sendIt},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function(response){
alert(response);
}
});
$("#selcombo").load("combo.php");
$("#tools").hide().html(data).fadeIn('fast');
});
Combo.php:
<?php
echo '<select id="tunelist" name="tunelist" >';
$link = mysql_connect('localhost', 'setlist', 'music');
$query = mysql_query("SHOW DATABASES");
echo '<option>Select a Show</option>';
while ($row = mysql_fetch_assoc($query)) {
if ($row['Database'] == "information_schema"){}
elseif ($row['Database'] == "performance_schema"){}
elseif ($row['Database'] == "mysql"){}
else{
echo '<option value="'.$row['Database'].'">'.$row['Database'].'</option>';
}
}
echo '</Select>';
?>
How do I go about refreshing the values in the combo (made by combo.php) after a database is added using the form above?
Any help as always is greatly appreciated!
Loren
Try moving
$("#selcombo").load("combo.php");
to inside of your success function:
success: function(response){
alert(response);
if (response == true) // or something like this to ensure the success of the operation
$("#selcombo").load("combo.php");
}
What you have to do is to give back in createSL.php the code of the new combobox and loaded there.
This is your code
success: function(response){
alert(response);
}
Write something like:
success: function(response){
$('#tunelist').html(response);
}
Where the response is similar to Combo.php

Codeigniter, getting ajax to run on button press

My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});

Categories