Framework - Codeigniter
I need to populate multiple drop down lists on view onload function. Currently I use five Ajax requests to populate five dropdowns. I think this is inefficient and will reduce my application performance and increase the bandwidth usage. Is there any efficient alternative way to do this? (like populate them all in single Ajax call)
In my View
$(document).ready(function() {
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_main_catagories",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#main_catagory').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_sub_catagories",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#sub_catagory').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_serving_types",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#common_serving_type').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_approved_suppliers",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#supplier_name').html(data);
}
})
}
})
My Controller
public function fetch_mother_companies()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_mother_companies();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->id.'>'.$row->company_name.'</option>';
}
}
else {
}
echo $output;
}
public function fetch_main_catagories()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_main_catagories();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->id.'>'.$row->category_name.'</option>';
}
}
else {
}
echo $output;
}
public function fetch_sub_catagories()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_sub_catagories();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->category_id.'>'.$row->category_name.'</option>';
}
}
else {
}
echo $output;
}
Related
View urlCreate code
$ajaxSaveTestGrid = Yii::$app->urlManager->createUrl('testgrid/ajaxsave');
This Is My View Ajax Code
function saveRow(id, index) {
if(id == 'tbl_testGrid') {
save(id, index);
}
}
function save(id, index) {
var testGrid_name = $('#testGrid_name' + index).val();
var testGrid_qty = $('#testGrid_qty' + index).val();
var testGrid_price = $('#testGrid_price' + index).val();
var url = '$ajaxSaveTestGrid';
// alert(testGrid_name+testGrid_qty+testGrid_price);
$.ajax({
type: 'GET',
url: url,
data: {
testGrid_name:testGrid_name,
testGrid_qty:testGrid_qty,
testGrid_price:testGrid_price
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
if(response == 'error') {
alert('Fail to save! Please try again');
} else {
$('#testGrid_name' + index).attr(\"disabled\",true);
$('#testGrid_qty' + index).attr(\"disabled\",true);
$('#testGrid_price' + index).attr(\"disabled\", true);
$('#testGrid_save_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_delete_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_edit_button' + index).attr(\"class\", \"show\");
$('#hid_testGrid_id' + index).val(response[0].testgrid.id);
$('html,body').animate({scrollTop: $('#btn_testGrid').offset().top});
}
}
});
}
This is my Controller
public function actionAjaxsave() {
$result = array();
$testGrid_name = $_GET['testGrid_name'];
$testGrid_qty = $_GET['testGrid_qty'];
$testGrid_price = $_GET['testGrid_price'];
$model = new Testgrid();
$model->name = $testGrid_name;
$model->price = $testGrid_price;
$model->qty = $testGrid_qty;
if ($model->save()) {
array_push($result, ['testgrid' => $model]);
$result = Json::encode($result);
echo $result;
} else {
echo 'error';
}
}
It occurring Internal Server Error
I want to save json Data to model.
Internal Server Error means that your code has fatal errors and error displaying is turned off. If you want to see the error itself, you must enable error displaying.
Check out the following question with its answers: How do I get PHP errors to display?
After you see the error, you can fix it.
PS:
$testGrid_name = $_GET['testGrid_name'];
This is not a recommended way to access GET variables. Use Yii::$app->request->get('testGrid_name') instead
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
break;
}
}
return $country();
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
echo $country('$capital');
echo $country('$currency');
echo $country('$region');
?>
I followed this post - https://stackoverflow.com/a/38906191/3939981
If I rewrite the code inside function, it works
<?php function getCurrencyFor($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
$currency = $country->currency[0];
$capital = $country->capital;
$region = $country->region;
echo $capital;
echo $currency;
echo $region;
break;
}
}
return $currency;
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Aruba");
?>
Maybe some parts of the code did not work..Any comments and thoughs
You could use this code. Note that if you want a function to return three values, you should create an array with those values, and return that array. I also renamed the function, since it does not only return currency information:
function getCountryInfo($arr, $findCountry) {
foreach($arr as $country) {
if ($country->name->common == $findCountry) {
return array(
"currency" => $country->currency[0],
"capital" => $country->capital,
"region" => $country->region
);
}
}
}
$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$country = getCountryInfo($arr, "Aruba");
echo $country['capital'] . "<br>";
echo $country['currency'] . "<br>";
echo $country['region'] . "<br>";
I am trying to make a button which can load more posts with ajax, but I'm having a problem.
this is my php code:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
"post_type" => "portfolio",
"posts_per_page" => 2,
"paged" => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) :
?>
<div class="row" id="portfolio-posts">
<?php
$page_layout = get_field("page_layout");
$page_class = "";
if($page_layout == "1") {
$page_class = "col-md-4";
} else {
$page_class = "col-md-3";
}
while($query->have_posts()) : $query->the_post(); ?>
<div class="<?php echo $page_class; ?> single-post">
<div class="project-con project2-con">
<div class="overlay">
<div class="overlay-inner">
<h3><?php the_title(); ?></h3>
<hr>
<span><?php echo get_the_term_list( $post->ID, 'masonry-categories', '', ', '); ?></span>
</div>
</div>
<?php
if(has_post_thumbnail()) {
the_post_thumbnail("portfolio");
}
else {
echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/assets/images/default.png" />';
}
?>
</div>
</div>
<?php endwhile; ?>
</div>
<div class="button">
load more
</div>
<?php endif; ?>
and this is my javascript code:
var page = 1;
var loadMorePosts = jQuery('#load-more-posts').text();
function loadMore() {
page++;
$.ajax({
type: "GET",
url: './page/' + page,
beforeSend: function () {
jQuery('#load-more-posts').html("<i class='fa fa-spinner fa-spin'></i>");
},
complete: function () {
},
success: function (data) {
var $data = jQuery(data).find('.single-post,.single-blog');
if ($data.length > 0) {
jQuery('#load-more-posts').html(loadMorePosts);
jQuery('#portfolio-posts,#blog-posts').append($data);
$data.css("display", "none");
$data.fadeIn("slow");
}
else {
jQuery('#load-more-posts').html('No More Posts');
}
},
error: function () {
jQuery('#load-more-posts').html('No More Posts');
}
});
}
The error message I'm getting is:
Failed to load resource: the server responded with a status of 404
(Not found)
Instead of using the rewritten URL in Ajax:
url: './page/' + page
Use the URL with paged parameter, like so:
url: '.?paged=' + page
This problem happens a lot, because of .htaccess redirects. I've managed to solve the exact problem using these kinds of URLs.
I need help with this, I can't see where is the problem.
When I set source for autocomplete in html file, it works fine, when I same source or database values print out in ajax.php and return it via ajax it doesn't work. What could be the problem? Help please.
Html :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Auto complete</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.18.custom.min.js"></script>
<link rel="stylesheet" media="all" type="text/css" href="jquery-ui-1.8.custom.css" />
<style type="text/css">
.ui-autocomplete-loading {
background: url("images/loader.gif") no-repeat scroll right center white;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#ac").autocomplete({
minLength: 2,
//source: [{"value":"Some Name","id":1},{"value":"Some Othername","id":2}]
source: function( request, response){
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
'term':request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log('Success : ' + data);
},
error: function(message){
alert(message);
}
});
},
select: function( event, ui ) {
}
});
});
</script>
</head>
<body>
<input type="text" id="ac" name="ac" size="100" />
</body>
</html>
and my ajax.php file:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'test_db';
$server = mysql_connect($dbhost, $dbuser, $dbpass);
$connection = mysql_select_db($dbname, $server);
$term = $_GET['term'];
$qstring = "SELECT user_id,tName FROM `csv_data` WHERE tName LIKE '%" . $term . "%'";
$result = mysql_query($qstring);
$return_arr = array();
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {//loop through the retrieved values
$row_a = array();
if ($row['tName'] != null) {
$i++;
$row_a['value'] = ($row['tName']);
$row_a['id'] = (int) $i;
array_push($return_arr, $row_a);
}
}
mysql_close($server);
header("Content-type: text/x-json");
/*$my_arr = array(
array("value" => "Some Name", "id" => 1),
array("value" => "Some Othername", "id" => 2)
);*/
//echo json_encode($return_arr);
print json_encode($return_arr);
//print json_encode($my_arr);
This is response from firebug(generated from database).
[{"value":"4 erste Spiele","id":1},{"value":"Meine ersten Spiele \"Blinde Kuh\"","id":2},{"value":"4 erste Spiele","id":3},{"value":"Meine ersten Spiele \"Blinde Kuh\"","id":4},{"value":"4 erste Spiele","id":5},{"value":"Meine ersten Spiele \"Blinde Kuh\"","id":6},{"value":"Maxi Kleine Spielewelt","id":7}]
The parameter response is actually a callback tthat you have to call - passing it your data - to display the result popup menu. Simply call it in the "success" callback:
source: function(request, response) {
$.ajax({
...
success: function(data) {
// pass your data to the response callback
response(data);
},
error: function(message) {
// pass an empty array to close the menu if it was initially opened
response([]);
}
});
},
I have the following jquery ajax request
$(document).ready(function(){
var friendrequest = $(".friendrequest").val();
$(".afriendreq").click(function(){
$(".afriendreq").hide();
$.ajax({ type: "POST", url:"functions/ajaxfriends.php", data:"friendrequest" ,success:function(result){
$(".cfriendreq").show();
}});
});
});
And it gets the input from here
while ($row = mysql_fetch_array($search)) {
d
?>
<div id="search_container">
<div id="search_image"><img src="<?php echo $row['picture'] ?>"></img></div>
<input type="hidden" value="<?php echo $row['id'] ?>" id="friendrequest" ></input>
<div id="search_name"> <?php echo $row['first_name'] . " " . $row['last_name']; ?> </div>
<div id="search_friend"><a class="afriendreq">Send Friend Request</a><a class="cfriendreq" style="display:none;">Cancel Friend Request</div>
</div><?php
echo "<br />";
}
?>
Unfortunately it's not working though. Can anyone find the problem because it's bugging me?
Also the functions/ajaxfriends.php is
<?php
include 'functions.php';
if (isset($_POST['friendrequest'])){
$friendrequest= $_POST['friendrequest'];
$friendrequest= filter ($_POST['friendrequest']);
$sql_connectfriend = " INSERT INTO friends (`useridone` ,`useridtwo` ,`request`) VALUES ('$_SESSION[user_id]', '$friendrequest', '1' ";
$search = mysql_query($sql_connectfriend, $link) or die("Insertion Failed:" . mysql_error());
}
?>
Can anyone see why?
Thanks in advance.
Try:
$.ajax({
url: 'functions/ajaxfriends.php',
type: 'POST',
data: { friendrequest: friendrequest },
success: function(result) {
$('.cfriendreq').show();
}
});