AJAX and Codeigniter Controller - php

I want to dynamically parse RSS feeds.
I have a select list and I would like to send a value (id) to the controller with ajax.
and after, I want to parse RSS feeds corresponding to the id
My Controller home.php :
function view($type = NULL)
{
$data = array();
$this->load->model('flux_model');
if ($type == "ajax") {// load ajax view
$flux = $this->flux_model->get_one_flux($this->input->post('id'));// ajax id
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('messages_list', $data);
}
else{ // load the default view
$nb_min = 0;
$nb_max = 7;
$nombre = mt_rand($nb_min,$nb_max);
$flux = $this->flux_model->get_one_flux($nombre);
$flux2 = $flux[0]->url_flux;
$xml = new SimpleXMLElement($flux2, NULL, TRUE);
//my foreach
$this->load->view('default', $data);
}
}
Ajax script :
$("#myform1 #rss").change(function(){
var msg = $('#myform1 #rss').val();
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
});
view default works, I parse an RSS feed randomly
but with the ajax view, I have this error:
Message: SimpleXMLElement::__construct(): I/O warning : failed to load external entity ""
it looks like I do not get the id?! ajax problem?

I think your issue is with
$.post("<?= site_url('home/view/ajax') ?>" [etc.]
Because many sites' configurations will prevent cross-site Ajax requests (See XSS), your $.post will be prevented. Instead, try something like:
$.post("controller/method/parameters" [etc.]
Example:
In your JavaScript:
$.post("ajax/myajax/myparam",{},function(data) { alert(data); });
And in your controllers/ajax.php file:
class Ajax extends CI_Controller
public function __construct()
{
parent::__construct();
}
public function myAjax(parameter='')
{
/**
* Load models, or whatever. Then echo the results, so that
* $.post gets its "data" var.
*/
}
}
I hope this helps!

I just replace :
$.post("<?= site_url('home/view/ajax') ?>", {id: msg}, function() {
$('#main').load("<?= site_url('home/view/ajax') ?>");
$('##myform1 #country').val('');
});
by
$.post('<?= site_url('home/view/ajax') ?>', options, function(data) {
$('#content').html(data);
})

Related

use ajax call to load a view codeigniter

I am trying to load a view through ajax passing in a post variable through controller following is my ajax call:
$('#image_id').on('click',function(){
var image_id = $('#image_id').val();
alert(image_id);
if(image_id != '')
{
alert('called');
$.ajax({
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
});
}
else
{
alert('Error');
}
});
I am using the add_id to retrieve data from the database in my controller below:
public function load_add()
{
$this->load->model('Product_model');
$data['advert_data']=$this->Product_model->get_specific_add($this->input->post('add_id'));
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add',$data);
$this->load->view('include/footer');
}
I am getting an error at the point of data retrieval from DB, as the model does not have the add_id. Following is my model code
public function get_specific_add($image_id)
{
$this->db->select('adverts.title,adverts.item_condition,adverts.add_type,adverts.address,adverts.price,adverts.negotiable,adverts.product_description,adverts.create_time, users.first_name,users.last_name,users.mobile,users.email,users.image_name');
$this->db->from('adverts,countries,states,cities,users');
$this->db->where('adverts.id= $image_id_new');
$this->db->where('adverts.country_id=countries.id');
$this->db->where('adverts.city_id=states.id');
$this->db->where('adverts.area=cities.id');
$this->db->where('adverts.user_id=users.id ');
$this->db->where('adverts.id= $image_id');
$query = $this->db->get();
return $query->result();
}
Appreciate if someone can help me on this. The page i am trying to load is Site/site_load_add. Thanks
You've call same url with both GET|POST, First call POST is ok, but in GET that's your error.
$.ajax({
// first call is OK!
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
// BUG HERE, This's a GET call and with No query string
// Will `$this->input->post('add_id')` found nothing.
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
Thank you all for the support, I got this sorted by passing the ID of the advert a below:
public function load_add($id)
{
$this->load->model('Product_model');
$data['advert_data'] = $this->Product_model->get_specific_add($id);
$data['adverts'] = $this->Product_model->get_adverts();//get database query output to the array
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add', $data);
$this->load->view('include/footer');
}
Thanks

AJAX on success return HTML files instead the data value?

I have this simple AJAX code to get the User Timezone whenever he is successfully login to the dashboard.
JS
<script type="text/javascript">
$(document).ready(function(){
'use strict';
/**
* Getting user current timezone offset
*/
var timezone_offset = new Date().getTimezoneOffset();
timezone_offset = timezone_offset == 0 ? 0 : -timezone_offset;
$.ajax({
type: "POST",
url: "<?php echo base_url('dashboard'); ?>",
data: {"timezone": timezone_offset},
cache: false,
success: function(data){
alert(data);
},
error: function(){
console.log('error');
}
});
});
</script>
Controller
public function index()
{
$data = $this->global_data->logged_user();
$data['page_title'] = 'Dashboard';
$data['page_directory'] = 'pages/dashboard';
$data['greeting'] = $this->global_helpers->greeting() . ' !';
$chart_data = array();
$order_history = $this->trade_history->chart_data();
foreach($order_history AS $d)
{
$chart_data[] = array(
'y' => $this->global_helpers->month_name($d->month) ."' ". $d->year,
'a' => $d->profit,
'b' => $d->loss
);
}
echo $_POST['timezone'];
$data['chart_data'] = json_encode($chart_data);
$this->load->view('template', $data);
}
But the problem is, when it's success why it's return the HTML header? not the data I wish to get?
What do I do wrong here? And I put this AJAX code in footer.php file. Sorry for this silly question but I just got stuck here.
I appreciated any kind of helps, Thanks!
Edited
Sorry for this silly post, I can't use that way, i just need to create another controller for handling any kind of AJAX value, so the problem will be fixed.
Well, you can't render HTML inside an alert anyway.
I see that you ended up solving this issue, but, FYI, if you ever need a controller to return HTML as data, use the third parameter on view method:
echo $this->load->view('template', $data, TRUE);
See more at Codeigniter docs :)

How to switch called php page using AJAX in wordpress

I have an several online application forms built into a (they differ per country) and I need to switch from one to the other with a users button click.
The code I have does this however it also produces a 500 error which breaks any other scripts.
Can anyone give me an idea of what I am doing wrong?
//Update appURL
if (jQuery('button[id="ukApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/uk/uk-application.php";
} else if (jQuery('button[id="itlApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/itl/it-application.php";
}
//Get URL path
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
//Country Application URL
function getOutput() {
jQuery.ajax({
url: getContextPath() + appURL,
complete: function (response) {
jQuery('#output').html(response.responseText);
},
error: function () {
jQuery('#output').html('Bummer: there was an error!');
}
});
return false;
}
here is your ajax function
$.ajax({
url: ajax.url,
...
dataType: "json",
success: function(response) {
$('#myDiv').html(response.html);
},
})
and the php function
function my_ajax_load() {
$post_id = $_POST['post_id'];
ob_start();
include(locate_template('my-template-file.php',false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
in your template file you can use your variables declared in the function, in this example you can you $post_id inside the my-template-file.php
For example:
<?php /* Template name: My template */
if($post_id) {
echo get_the_title($post_id);
}
?>
500 error is caused by php error not ajax or jquery, check out your template file for a php errors
There was a missing image being called by the page I was trying to load, the error only showed up in the logs. Thanks all :)

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this

Ajax method calls same function in controller but needs to load different results in different areas

I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}

Categories