Refreshing other view from jquery function - php

I write my application in PHP. I have this code:
$.ajax({
type: 'POST',
async: false,
url: $("#loginForm").attr('action'),
data: {
username: $("#username").val(),
password: $("#password").val()
},
dataType: 'text',
cache: false,
success: function(mess) {
console.log(mess);
if(mess=='true') {
console.log('true');
console.log(window.location.href);
window.location.href = "mainLogged";
$("#cao").html('homepage.php',"cao cao ovde sam");
} else {
$("#greska").html("Unesite ispravne podatke!");
$("#username").val("");
$("#password").val("");
}
}
}
When variable "mess" is 'true' I call controller mainLogged. I want to change a section with id "#cao" in homepage.php which is calling by controller mainLogged. Is this possible?

when you write window.location.href = "mainLogged"; the rest code is useless.
Now if you want to change some section here "#cao" you can do it in multiple ways
you can use cookie
you can use query params.
you can use session
Example using uri segment(query value) :
change this window.location.href = "mainLogged"; to this window.location.href = "mainLogged/1";
now catch it to controller like this
$seg = $this->uri->segment(2);
and in view check if $seg is 1 than do your staff

When you login you always end up in mainLogged controller's index function as there is no function mentioned, no need to send any query strings from the ajax, as you know that you ended up here after login. So, in this controller, just set a variable here for the value of the #cao and load it to the view.
function index(){
$data = array();
$data['cao'] = 'value_for_cao';
$this->load->view('view', $data);
}
Now, in the view you just echo out the value:
<input id="cao" value="<?php echo $cao ?>" />
Hope it helps.

Related

codeigniter not returning json/ajax response

I have read a lot on codeIgniter ajax response. I have and modified my ajax script multiple times yet codeIgniter does not return the json response although I see the response when debugging with firefox developer browser under the network tab of web console. here's what i have written
AJAX script
$("#class_id").change(function(){
var class_id = $("#class_id").val();
alert(class_id);
alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
dataType: 'json',
data: {class_id: class_id},
success: function(response) {
$("#res").html(reponse.class_id);
}
});
return false;
});
controller
function set_class_id()
{
if ($this->session->userdata('teacher_login') != 1)
redirect(base_url(), 'refresh');
//echo "dsdsd".$this->input->POST('class_id');
if (!empty($this->input->POST('class_id')))
{
$page_data = array('class_id' => $this->input->POST('class_id'));
//$response["JSON"] = json_encode($page_data);
$response = array('class_id' => $this->input->POST('class_id'));
echo json_encode($page_data);
$this->load->view('backend/index', $page_data);
}
}
Have you tried using
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
Also, check th output class for more info Codeigniter Output Class
So I figured a way out. using just php, I sent the class_id to the controller using a submit button then checked for the response on the page to enable the subject dropdown. Although i haven't figured why the ajax isn't working yet. thanks guys for your inputs

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 :)

Check db and then redirect using Ajax

So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>

Use codeiginiter and ajax following the rules codeigniter

I'm struggeling to use codeigniter the way it was created. I'm opening an edit page (order). I want to change data on the page which will be dynamically saved after leaving a field. But when I'm not succeeding in the way codeigniter works or with other words on a "nice way". I don't want to be depending on the uri structure and get the data with uri segment, like the code is now. I want to improve the code beneath but i'm not succeeding...
This is the code to open my view
public function edit($id = NULL) {
// Fetch a page or set a new one
$this->load->model('shop_m');
$this->load->model('details_m');
$this->data['subtitle'] = 'incoming';
if ($id) {
if($this->transfer_m->get_permission($id) > 0){
$this->data['transfer'] = $this->transfer_m->get_rec($id);
// $this->data['transfer'] = $this->transfer_m->get($id,true);
count($this->data['transfer']) || $this->data['errors'][] = 'page could not be found';
$this->data['details'] = $this->details_m->get_by(array('doc_no' => $id),FALSE);
}
else{
redirect('admin/Dashboard', 'refresh');
}
} else {
$this->data['transfer'] = $this->transfer_m->get_new();
}
$this->data['shop_from'] = $this->shop_m->get($this->data['transfer']->from_customer,TRUE);
$this->data['shop_to'] = $this->shop_m->get($this->data['transfer']->to_customer,TRUE);
// Load the view
$this->data['subview'] = 'pages/details/transfer_edit';
$this->load->view('pages/main', $this->data);
}
My ajax call
function add_shop(shop){
var id = $('#doc_no').text();
$.ajax({
url: base_url+"/admin/transfer/add_shop/"+id+"/"+shop,
async: false,
type: "POST",
data: "",
dataType: "html",
success: function(data) {
$('#ajax-content-container').hide();
}
})
}
my controller function to add a shop
public function add_shop($id){
$data = array('to_customer' => $this->uri->segment(5));
$this->transfer_m->save($data,$id);
}
Any help will be appreciated!!
You can use post. Modify your ajax call and pass the data like below. See the document here https://api.jquery.com/jquery.post/
data: { id: id, shop: shop }
This data can be accessed $this->input->post('id'); $this->input->post('shop');

codeigniter view won't show up from passing javascript/ajax parameter

I'm integrating codeigniter with phpgrid, and I'm having a trouble with passing the row values from phpgrid (in VIEW A) to another view (VIEW B) through javascript and codeigniter controllers
I have a virtual column like this in PHPGRID (VIEW A):
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject, rowid){
var sessid = rowObject[0];
return '<input type="button" value="View" onclick="btnView('+sessid+')">';
}
COLFORMATTER;
and the javascript in VIEW A:
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
}
});
return false;
}
in the Codeigniter CONTROLLERS:
public function tes(){
$data['sessid'] = $_POST['sessid'];
$this->load->view('view_b', $data);
}
I can't seem to load the view. I used Mozilla's Firebug to know the response, it's true that the response is the code of my view_b view, but how can I switch to that view?
//Your are using ajax for some operation and want to reload the view page the you can test these options:
1) take a div in current view page and assing ajax retrun message to that div
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
$("#divid").html(msg);
}
});
return false;
}
//Or 2)just redirect to your view page again
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
window.location.href=path to your view page;//<?php echo base_url()."index.php/controller/function"; ?>
}
});
return false;
}
If I understand correctly you want to go from VIEW A to VIEW B (meaning an actual change in the window location) and pass a value to VIEW B so it can generate some dynamic content. Well, AJAX is not the solution here since it will not trigger a change of page but instead will return the markup/text of the response as a string.
But there are still a number of ways you can achieve what you want, using Codeigniter the simpler way would be to use an argument for your controller method that you can send as part of the uri in a link:
HTML
View
Since you're using Javascript to generate the markup you would need something like this
return 'View';
*Note that you will now have a link instead of a button but you can use CSS to style it any way you want it.
You would now retrieve the value in your controller like this:
PHP
public function tes($sessid){
$data['sessid'] = $sessid;
$this->load->view('view_b', $data);
}
Pretty simple. A second option will be to use a form instead of your button to send the value using either GET or POST, forms do trigger a change in page whenever they are submitted:
HTML
<form action="http://example.com/index.php/main/tes" method="get">
<input type="submit" value="{ssid}" name="sessid" />
</form>
Again using javascript:
return '<form action="<?php echo site_url('main/tes')?>" method="get">'
+'<input type="submit" value="'+sessid+'" name="sessid" />'
+'</form>';
And to get the value in your controller:
PHP
public function tes(){
$data['sessid'] = $_GET['sessid']; //OR $_POST['sessid']
$this->load->view('view_b', $data);
}
Turns out that passing a variable from javascript to codeigniter controller is just:
function btnView(sessid){
window.location = "printvo/"+sessid;
}
I was using ajax because I don't know how to pass the variable, I always thought that passing variable is using brackets: window.location = "printvo("+sessid+")"; and that didn't work.

Categories