Passing values from view to controller and again from controller to view? - javascript

I have a controller suppose a and it has a function suppose index() where i passed data from my view suppose b using javascript like this:
var formURL = "<?php echo base_url();?>a/index/"+ $("#someid").val();
$.post(formURL).done(function(data){$("#something").html(data);
now i am receiving it in my controller like this:
public function index($somevalue= ""){
....
....
}
now after execution from the controller a i am again passing array values to the view b like this:
public function index($somevalue= ""){
....
....
$data['value1'] = $value1;
$data['value2'] = $value2;
$this->load->view('b', $data);
}
now when i am accessing the data in the view b like this:
<?php if (isset($value1)) {
echo $value1;
}?>
i am not getting the value of value1. what did i do wrong in this case???

It would be a lot lot better if you use AJAX. This is what it precisely does.
AJAX request to controller i.e (sending datas to controller)
Get the AJAX result i.e (sending datas back to views)
and from client side you can update it.
You can get the form values like
var formDatas = $('#form').serialize();
Then make an ajax request like
$.ajax({
type : 'POST',
url : 'url',
data : {formdata : formDatas },
success: function(result){
//update the view with the result
}
}

Related

Laravel download xls file with AJAX

I can't download my XLS file via Ajax
function downloadFile(response) {
var blob = new Blob([response], {type: 'application/vnd.ms-excel'})
var url = URL.createObjectURL(blob);
location.assign(url);
}
$('#export').click(function () {
$.ajax({
type: 'POST',
url : 'factures/engagements/selected/export',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
dataType: "json",
data : {
checkboxes : checkboxValues
}
}).done(downloadFile);
});
my controller :
public function exportFacturesEngagementSelected(Request $request){
$checkboxes = $request->input('checkboxes');
$collection = collect($checkboxes);
$engagements = EngagementOrder::whereIn('id' , $collection)->get();
$date = Carbon::now('Europe/Paris')->format('d-m-Y H:i:s');
$output = Excel::create('factures_engagements' . $date. '', function($excel) use ($engagements) {
$excel->sheet('Excel', function($sheet) use ($engagements) {
$sheet->loadView('engagements.exportExcelSelected')->with("engagements", $engagements);
});
})->export('xls');
return $output;
}
I only get the output preview of the file in my console network, but nothing happens in my browser; no file is downloaded. What am I doing wrong?
UPDATE #matticustard solution :
my checkboxValues is a json for exemple the result is
{920: "920", 927: "927", 931: "931", 939: "939"}
when i console log query i get :
undefinedcheckboxes=920&checkboxes=927&checkboxes=931&checkboxes=939&
When i try to get the values to my controller i made a $request->all() and i get :
array:2 [
"undefinedcheckboxes" => "920"
"checkboxes" => "939"
]
why i get undefinedcheckboxes and why i don't get the other ids ?
Try this
if your ajax success
location.href = path/to/file/property_title.xls
change this line
->export($type);
with
->store($type, 'public/reports/', true);
These days I've used this package
(my recommendation) for converting my model's collections to XLS and export that.
As I understand, you want to download the file via AJAX. I didn't got you at all, but I just can share my experience for helping you. This working with a normal POST request, but it will not refresh your page anyway.
So this is a working example:
In Controller
public function export(Request $request)
{
$data = $request->get('data'); // get incoming data field
return \Excel::download(new ExcelService($data), "custom-file-name-with-extension.xls");
}
In Service (or you can implement this in controller too)
namespace App\Services;
use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExcelService implements FromCollection
{
protected $data = null;
public function __construct($data)
{
$this->data = $data;
}
public function collection()
{
$items = Item::where('data', $data)->get(); // some query using incoming $data
return $items;
}
}
Route
Route::post('export', 'ItemController#export')->name('export');
There's really no reason to use AJAX or store the file. You can pass the checkbox data as parameters in the URL with a GET request and use an <iframe> to download the file. I guessed at the controller name, so adjust as necessary.
web.php
Change the route to GET.
Route::get('factures/engagements/selected/export', 'FactureController#exportFacturesEngagementSelected')->name('export');
JavaScript function and handler
Serialize the data as expected by your controller and make the request.
I guessed that checkboxValues was an array of values based on the actions taken in your controller. But you could serialize the form directly var query = $('form').serialize(); and adjust the controller to match the input.
function downloadFile() {
var query;
$.each(checkboxValues, function(index,value) {
query += 'checkboxes=' + value + '&';
});
$('<iframe />')
.attr('src', '/factures/engagements/selected/export?' + query)
.hide()
.appendTo('body');
}
$('#export').click(function () {
downloadFile();
});
FactureController.php
And use the download method in your controller.
// ...
->download('xls');

Call Php controller function with AJAX Codeigniter

I , im working with Ajax and Codeigniter to call function client-server
the php
public function mainViewClean() {
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
return "Ready";
}
//route $route['cleantags'] = 'user/mainViewClean';
And ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#btn_recargar").button().click(function(){
//window.location.href = "<?= base_url('home')?>";
$.ajax({
type:'POST',
url:'<?php echo base_url("cleantags"); ?>',
data:{'id':100},
success:function(data){
//window.location.href = "<?= base_url('home')?>";
alert(data);
}
});
});
});
</script>
The function excuse good , but javascript don't show any data , what im doing wrong?
Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json or text/html.
In order to write that data, you need to echo it from the server with PHP.
The return statement doesn't write data, it simply returns at the server level.
If you want to communicate between PHP functions, you have to use return. But if you want to output some data, you have to use echo
Client side
$.ajax({
url:'<?php echo base_url("cleantags"); ?>',
dataType: 'application/json',
success:function(response)
{
alert(response.foo);
}
})
Server Side
public function mainViewClean()
{
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
echo json_encode( array("foo"=>"Ready"));
}
Change return into :
echo "Ready";
If you're sending an array, at server side you need to json_encode, example :
// encode array into json string format
echo json_encode( array( 'name' => 'Osman' ) );
And in Js, you have 2 options, the 1st solution is :
success : function ( data ) {
// data now is coming in this form { "name" : "osman" }
// as the string data is coming from server-side
// you must parse it back into Javascript object
var newData = JSON.parse( data );
}
And the 2nd option is, add dataType properties inside ajax properties like following :
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
I'm fairly new as I only have been using AJAX , but I think your code has a few syntactical errors.
data: { id:100 } with no quotations around id.
I advise you need to look at more examples of ajax calls to fix these little errors.
You said your JS is working but not showing data?

Jquery ajax call in Cake PHP 3.0

Hi,
I'm trying to make a ajax request to the view A from the controller B like this :
In the view A :
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'B','action'=>'viewresult'));?>",
dataType: 'text',
async:false,
success: function(tab){
alert('success');
},
error: function (tab) {
alert('error');
}
});
}
In the controller B:
public function viewresult()
{
echo 'SUCCESS';
}
The problem is that in the 'response' of ajax, I've 'SUCCESS' but also the entire view A, I don't understand why...
I want only 'SUCCESS'...
Thanks in advance !
Detect if its ajax as per following code in cakephp way :
if($this->request->is('Ajax')) //Ajax Detection
{
$this->autoRender = false; // Set Render False
$this->response->body('Success');
return $this->response;
}
Check here for more detectors - http://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Network\Request::addDetector
You can also use $this->Url->build instead of including Router for creating links in view.
echo $this->Url->build(['action'=>'index']);
The easiest way to achieve it is adding die() at the end of your function so it prevents to load whole layout:
public function viewresult()
{
echo 'SUCCESS';
die;
}
OR
public function viewresult()
{
die('SUCCESS');
}
But more conventional way is using JSONView. Your action should look as follows:
public function viewresult()
{
$this->set('text', 'SUCCESS');
$this->set('_serialize', ['text']);
}
You also have to load RequestHandler component in initialize() method in your controller:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
You need to set allowed extensions for all routes connected later in routes.php:
Router::extensions('json', 'xml');
Now you can access your action adding extension .json at the end of it's URL, so you need to modify ajax call url:
url:"<?php echo Router::url(array('controller'=>'Main','action'=>'viewresult', '_ext' => 'json'));?>"
That's all, but keep in mind that this solution force you to handle JSON array in response. In this example output will be looks as follows:
{"text": "SUCCESS"}

Codeigniter: How to pass array from controller to view without refresh

Basically I have a form in the view with one input enabled, and multiple inputs disabled (only to show information derivated from the unique input).
Now, I need to send this input to the controller to make a query, and send back to the view an array with the fields information but without refresh the site (because I cant loose the progress that I have in this page).
Maybe the solution is to use javascript to send the controller the input field, and in the function return the array of values to refresh the form, but how?
EDIT: Sorry for my bad english.
var input = $('#input').val();
$.ajax({
type:"POST",
url: <?php echo base_url().'controllername/action'?>
data: {input : input},
success: function(data){
// this data should be contain an arra
$('#where_to_insert_array').html();
}
});
In controller action and in action
function action()
{
$data = $this->input->post('input');
get data from database on $data
make its array and then echo it
echo array();
}
Finally I understand how to pass the array from the controller to the view dynamically, this is the code:
The view javascript:
function getClient(){
if($('#cedula_cliente').val()){
$.ajax({
type : "post",
url: "<?php echo base_url().'index.php/clientes/getClienteFactura'?>",
cache: false,
data : {cedula : $('#cedula_cliente').val()},
success : function(json){
var obj=jQuery.parseJSON(json);
if(obj[0]){
$('#nombre_cliente').val(obj[0].nombre);
$('#apellido1_cliente').val(obj[0].apellido1);
$('#apellido2_cliente').val(obj[0].apellido2);
$('#dir_cliente').val(obj[0].dir);
}else{
alert("Usuario no encontrado");
}
},
});
}else{
alert("Debe ingresar una cédula de usuario");
}
}
Im using obj[0] because "cedula" is the primary key and It never will return more than 1 row.
And this is the controller function:
public function getClienteFactura(){
$cedula = $this->input->post('cedula');
$query = $this->Client_model->getClientByCedula($cedula);
echo json_encode($query);
}
Thanks for the answers, maybe I should have looked better on google, the key to solve the problem was Json.

AJAX call working on local server but not online

When a user goes to one of the pages (let's call it page1), the PHP loads the HTML content for an array containing data about the users.
Once the page is loaded (DOM ready), I use jQuery to perform an AJAX call to retrieve the HTML for that array of data. I do this to get the benefit of using separate PHP template files. In this way, PHP will call the PHP template for every array in the bi-dimensionnal array and return the HTML.
page1.php:
<script type="text/javascript">
var globalArray = <?php echo json_encode($freres); ?>;
jQuery(function($) {
liste(); // Ajax call to get HTML for the data in "globalArray"
});
</script>
AJAX call:
function liste() {
$.ajax({
data : {
array : globalArray,
dataName : 'someName',
file : 'templates/t_item_file'
},
dataType : 'html',
success : function(data, textStatus, jqXHR) {
var table = $('table');
var rows = $('<table>' + data + '</table>').find('tr');
rows.each(function(i, e) { // insert with fade-in animations
var row = $(e);
row.hide();
table.append(row);
row.delay(i * 15).fadeIn(250);
});
},
type : 'GET',
url : config.site + 'ajax/view' // configured in header
});
}
Somewhere in t_header.php:
<script type="text/javascript">
var config = {
base : "<?php echo base_url(); ?>",
site : "<?php echo site_url(); ?>"
};
</script>
The config route that redirects to ajax/view/...
$route['ajax/(:any)'] = 'c_ajax/$1';
The method of the controller c_ajax that handles the AJAX call:
public function view() {
$file = $this->input->get('file');
$array = $this->input->get('array');
$dataName = $this->input->get('dataName');
foreach ($array as $vars) {
$data[$dataName] = $vars;
$this->load->view($file, $data);
}
}
When I do this using EasyPHP on localhost, everything works fine, and I receive the HTML as expected, something like :
<TR>
<TD>...</TD>
//...
</TR>
<TR>
//...
And then I insert it into a table. But, when I try to do it on my website in FireBug, I can see that the AJAX response is not 200, but 302 Moved Temporarily.
Can anyone help me to figure out what to do to get it to work, because I spend almost the last four days learning jQuery and AJAX, and it doesn't work (online only).
Instead of
file : 'templates/t_item_file'
give full path of the controller
eg:"http://www.yourdomain.com/---/templates/t_item_file"
Problem solved. I load the HTML data in PHP and pass it to JavaScript, and then use jQuery to animate DOM Elements.
Previously, I didn't pass HTML but raw data in a PHP array, and then tried to get the HTML for all the elements of thie array via Ajax (HTML for all elements in only one call). I think there was too many parameters in the request and that's probably was caused the error.

Categories