Ajax is not working in Codeigniter - php

Ajax is Not Working : I want to update one record using Code Igniter framework. when i passing po_id to below url. my ajax is not working. but without passing id my below ajax is working.
<a class="btn btn-success" href="<?php echo base_url('inventory_c/view_purchase_update/'.$result->po_id);?>">Update</a>
Controller:
public function view_purchase_update() {
$data['pitems'] = $this->inventory_m->purchase_items_update($po_id);
$data['sname'] = $this->inventory_m->getsuppname($supplier_id);
$data['sid'] = $this->inventory_m->getsuppid($po_id);
$this->load->view('superadmin/editable_purchase_update',$data);
}
Ajax Code:
$.ajax({
type: "POST",
url: "add_temp_purchase",
cache: false,
data: 'itemnum='+itemnum+'&itemname='+itemname+'&costprice='+costprice+'&quantity='+quantity+'&customer_id='+customer_id+'&sales='+sales,
dataType: "html",
success: function(returnhtml) {
}
});

When sending data with Ajax mind that it's JSON formatted.
What you can do is below:
$.post( "add_temp_purchase", {
itemnum: itemnum,
itemname: itemname,
costprice: costprice,
quantity: quantity,
customer_id: customer_id,
sales: sales
}).success(function( data ) {
alert( "success" );
});
In your controller you would have the follwing
public function postData() {
$postData = $this->input->post();
$itemNum = $postData['itemnum'];
#etc....
}
Aswell can you confirm you can print out $result->po_id in your view?
It seems that you never parse that to the view, in your controller you should do the following to make sure you have this
public function view_purchase_update() {
$data['pitems'] = $this->inventory_m->purchase_items_update($po_id);
$data['sname'] = $this->inventory_m->getsuppname($supplier_id);
$data['sid'] = $this->inventory_m->getsuppid($po_id);
$data['po_id'] = $po_id;
$this->load->view('superadmin/editable_purchase_update',$data);
}
Then in your view you will use it like this
<a class="btn btn-success" href="<?= base_url('inventory_c/view_purchase_update/'.$po_id);?>">Update</a>

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

How to bring data post ajax to Controller when redirect page

how to bring ajax post data to the controller when redirecting the page, I have got id_user data from <a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit_user "?>" id_user="<?php echo $row ['idx'] ?>">Edit</a> but when redirecting the data page is null / 0, how do I bring post ajax data to the redirect page through the controller, please help me, if something is unclear please apologize and can ask me ...
Note: I use PHP native MVC
This is my code
$(document).ready(function(){
$('.edit').on('click', function(){
var id_user =$(this).attr("id_user");
alert(id_user);
var url =$(this).attr("href");
$.ajax({
type:'post',
url: url,
data:{id_user:id_user},
success: function(data){
alert(data)
},
error:function(err){
alert(err)
}
});
});
});
This is my controller
public function edit(){
Template::setTitle('Edit User Management');
$id_user = (int)Request::post('id_user');
$result = $this->getUserbyId($id_user);
$dataresult = json_decode($result, true);
if($dataresult === NULL) {
echo "<script language = \"javascript\">window.alert(\No Have Data\");";
echo "javascript:history.back();</script>";
return false;
}
$data = $dataresult;
return $data;
this is my code
<a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit "?>" id_user="<?php echo $row ['idx'] ?>">Edit</a>
this is my problem
I have get data id_user, I cacth data use alert
but when I redirect page, this is result
I want to get data like this, when I redirect Page
This is my new error when I add Prevent Default
Since you have a list of rows and you render them somehow, you can assign an id of the record to each of the entity.
<a class="edit" href="<?php echo BASE_URL. "app.php/usermanagement/edit_user?id_user=" . $row['idx']; ?>">Edit</a>
Now, when you click, you make a GET request to your edit controller action with id_user parameter. You can handle this request like this:
public function edit_user(){
if(isset($_GET['id_user'])){
//TODO: make something with it
var_dump($id_user);
die();
} else {
//throw an error
}
}
And your JQuery code should looks like this:
$('.edit').on('click', function(){
var id_user =$(this).attr("id_user");
alert(id_user);
var url =$(this).attr("href");
$.ajax({
type:'post',
url: url,
data:{id_user:id_user},
success: function(data){
//alert(data);
window.location = '/app.php/usermanagement/edit_user?id_user=' + id_user;
},
error:function(err){
alert(err);
}
});
});

Get data from json encode

I am using echo json_encode($data); to send an array back to jquery ajax. I want to get data from json and retrieve it on input text and I got this error like: The URI you submitted has disallowed characters.
I don't know on how to pass data in model. Btw, I'm using codeigniter.
Once I click the edit button, a modal will appear. Please, help me guys!!
Button
<a onclick="edit_content_by_id('.$row->post_id.')" title="Edit"><span class="ti-pencil"></span>
Model
public function GetContentById($id) {
$query = $this->db->select('*')->from('cms_posts_tbl cpt')->
join('cms_contents_tbl cct', 'cct.post_id = cpt.post_id')->
join('cms_category_tbl ccat', 'ccat.post_category_id = cpt.post_category')->
where('post_id', $id)->get();
foreach($query as $row) {
$data = $row;
}
echo json_encode($data);
}
jQuery Ajax
function edit_content_by_id(id) {
var data = { content_id : id };
$.ajax({
type: 'POST', url: 'http://localhost:81/ci_sample/model/GetContentById('+ id +')',
data: data, dataType: 'json',
cache: false,
success:function(data) {
$('#modal_content').modal('show');
$('#modal_content').find($('post_title')).val(data.post_title);
}
});
}
header('Access-Control-Allow-Origin:*');
Go to config.php and configure this variable.
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-#\=';

How to update the data when click the button using ajax in Laravel?

I am using Laravel 5.4 and I have Check Out button in my table. I want when I click that button, it will update check out time in the database and update my table. I am trying to use ajax, but it is not working, but sometimes it is working too but not reload the table so I need to refresh the page manualy. Here is my button code:
<a type="button" name="checkout_btn" id="checkout_btn" data-id=" {{ $Data->VST_ID }}" class="btn btn-primary">Check Out</a>
This is my ajax code:
$('#checkout_btn').click(function addseries(e){
var VST_ID = $(e.currentTarget).attr('data-id');
alert("dfads");
$.ajax({
type: "GET",
url: 'visitor/checkout',
data: "VST_ID="+VST_ID,
success: function(data) {
console.log(data);
}
});
});
Here is my controller code:
public function Checkout(Request $request)
{
$visitor = Visitor::where("VST_ID",$request['VST_ID'])->first();
$visitor->VST_CHECKOUT = date('Y-m-d H:i:s');
$visitor->UPDATED_AT = date('Y-m-d H:i:s');
$visitor->UPDATED_BY = 'User';
$visitor->save();
return redirect()->route('Visitor.VList')->with('message','The Visitor has been Checked Out !');
}
You can do this by two methods.
1st: by making different view for table body.
In controller set view as below Example
if($request->ajax())
{
$records=\View::make('admin.settings.state.state-holiday-tbody',['contents'=>$contents,'active'=>$active,'tab'=>$tab])->render();
return response()->json(array('html'=>$records));
}
and then perform for loop to append data in table body.
Note: call function to get all table records on document ready.
2nd: Make table body using javascript for loop by getting all records in response.
I think if you want to update the data, the method is PUT and why are you using GET method?
$('#checkout_btn').click(function addseries(e){
var VST_ID = $(e.currentTarget).attr('data-id');
$.ajax({
type: "PUT",
url: 'visitor/checkout' + VST_ID,
success: function(data) {
console.log(data);
}
});
});
change your controller
public function Checkout(Request $request, $id)
{
$visitor = Visitor::find($id);
$visitor->VST_CHECKOUT = date('Y-m-d H:i:s');
$visitor->UPDATED_AT = date('Y-m-d H:i:s');
$visitor->UPDATED_BY = 'User';
$visitor->save();
return redirect()->route('Visitor.VList')->with('message','The Visitor has been Checked Out !');
}
and change your route.php
Route::put('visitor/checkout/{id}', 'visitorController#Checkout');

Using ajax to call a php function

I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}

Categories