Ajax request on Controller fails - php

I have a problem with the following code in Laravel. I need to send some variables to my controller, do something with them and return three variables back. I made have made the ajax call, the route and the controller but the ajax call fail. As an error code I receive this.
View
function gg() {
var slider_value = document.getElementById('paradnyi').value;
var checkbox_value = document.getElementById('check_box').value;
var dto = {slider_value : slider_value, checkbox_value : checkbox_value};
$.ajax({
url : "/calc_change",
contentType : 'application/json',
data : JSON.stringify(dto),
type : 'POST',
success: function(data) {
document.getElementById('visits').innerHTML = data[0];
document.getElementById('slaves').innerHTML = data[1];
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
}
Routes
Route::post('/calc_change',['uses'=>'PagesController#calc_change','as'=>'calc_change']);
Controller
public function calc_change(Request $request){
$data = array();
$data[]=1;
$data[]=2;
//dd($data);
return response()->json($data);
}

You have to add this code before ajax call in jquery section
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Related

Laravel 6 - Ajax - retreiving file - Internal error 500

I'm trying to fetch file via ajax from the laravel storage (I don't want to use the public folder as the docs should be only available for the admins). So the Ajax function calls a Route (post) , which calls the controller function to respond, but getting 500 internal server error in the console all the time.
If I dd() the request, or some string right in the begining of the controller function I get that back as output. so the request actually happens with the proper data. CSRF tokens are included.
The route:
Route::post('/tes/admin/filter/docview/', 'AdminTravelExpenseController#showdoc')-
>name('admin.tes.displayDoc');
The controller:
public function __construct()
{
$this->middleware('auth');
//adminvalidator here
}
public function showdoc(Request $request){
$item = \App\TravelExpense::find($request['id']);
if($request['src'] == 1){
$url = $item->doc_url1 ;
}
else{
$url = $item->doc_url2 ;
}
if (!Storage::disk('local')->exists($filePath)){
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return \Response::json($response);
}
And the ajax:
$('.docview').on('click',function(){
var id = $(this).data('id');
var src = $(this).data('src');
var form_data = new FormData();
form_data.append('id', id);
form_data.append('src', src);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/tes/admin/filter/docview/',
type: "POST",
processData: false,
contentType: false,
data: form_data,
success: function(data){
console.log(data);
$('.docDisplay').html(data);
}
});
});
Not sure what I'm missing here.
Thanks for the help in advance!

CodeIgniter unable to get Ajax data into variable

I have an Ajax post from a js file. This all works, but I am not able to set data to a variable and echo this to the screen.
I guess I do not know how to set class variables?
get Ajax code:
public function get_info()
{
// $test = $this->input->post();
var_dump($this->input->post());
$original_property_text = $this->input->post('original_property_text');
// set_ajax($original_property_text);
//$new_property_text = $this->input->post('new_property_text');
//return $test;
}
class variables and constructor:
class Users extends CI_Controller{
// gobal vars
var $new_property_text = '';
var $original_property_text = '';
var $changes = array();
function __construct() {
parent::__construct();
//$changes[] = $this->get_info();
}
*** edit *****
ajax code:
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {
'original_property_text': $original_property_text,
'new_property_text': $new_property_text
},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Quick answer, use this in your PHP :
public function get_info()
{
// better to use json when you need to return array
header('Content-Type: application/json');
echo json_encode( $this->input->post() );
exit();
}
In your ajax code (using jQuery framework) :
// call your controller in ajax
$.post('yourUrlHere', $('#yourForm').serialize(),
function(data) {
console.log(data);
// you manipulate json, so you can use : alert(data.property);'
}, 'json');
'$' defines variable so convert your php value to javascript object.
data: {original_property_text: '<?=$original_property_text?>', new_property_text: '<?=$new_property_text?>'},
Or,
var original_property_text = '<?=$original_property_text?>';
var new_property_text = '<?=$new_property_text?>';
var base_url = '<?=base_url();?>';
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {original_property_text: original_property_text, new_property_text: new_property_text},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
And Get Using Your get function
print_r($_POST);exit

Reading a very simple ajax request in Laravel

I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');

Laravel 5: Returning Eloquent Model Object as an Ajax Response

I am trying to return an Eloquent Model Object as an Ajax Response that i get from search process and i want to pass it to the view.
JS
$(document).ready( function() {
$(".client_search_option").change(function(){
var selectedClientTypeVal = "";
var selectedSmsDecisionVal = "";
var selectedClientType = $('input[type=radio][name=clientType]:checked');
var selectedSmsDecision = $('input[type=radio][name=sms_decision]:checked');
if (selectedClientType.length > 0) {
selectedClientTypeVal = selectedClientType.val();
}
if (selectedSmsDecision.length > 0) {
selectedSmsDecisionVal = selectedSmsDecision.val();
}
//alert(selectedClientTypeVal);
//alert(selectedSmsDecisionVal);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'http://localhost/pages/clientSearchAjax',
type: 'POST',
data: {_token: CSRF_TOKEN, selectedClientTypeVal:selectedClientTypeVal,selectedSmsDecisionVal:selectedSmsDecisionVal},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error:function(){
alert("An error has occured !");
}
});
});
});
Contoller
public function clientSearch(){
$client_option = Input::get('selectedClientTypeVal');
$sms_option = Input::get('selectedSmsDecisionVal');
if($client_option == 'all' && $sms_option == 'all'){
$ajax_clients = Client::with('clientType')->paginate(5);
}else{
$ajax_clients = Client::with('clientType')->where('clienttype_id', $client_option)->where('send_sms', $sms_option)->paginate(5);
}
return $ajax_clients->toJson();
}
I am sure that $ajax_client object is not null, i test it and i am able to get data from database but when i want to pass it to the view(or console) it shows up like undefined. How can pass it to the view(or console) and get the values of model's columns. Any help would be appreciated.
Try replacing
return $ajax_clients->toJson();
with
return $ajax_clients;
Laravel automatically converts Eloquent objects to JSON, moreover it will set content type header to application/json, which is something you don't do in your code and what might cause the issues you describe.

Kohana - how to create form without refresh?

How to create jQuery + ajax form without refresh?
This is my controller and views:
http://pastebin.com/GL5xVXFZ
In "clear" PHP I create something like this:
$(document).ready(function(){
$("form#submit").submit(function() {
var note = $('#note').attr('value');
$.ajax({
type: "POST",
url: "add.php",
data: "note="+ note,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
in add.php file is INSERT to Database.
There are more complicated ways of doing this for example detecting an ajax request in your action and then if detected print out a javascript response. The way you would do this is
JAVASCRIPT
function postForm(note){
$.ajax({
url : '/controller/action',
type : 'POST',
data : 'note='+note,
success : function(jsn){
var json = $.parseJSON(jsn);
if(json.status == 200)
alert('Completed Successfully');
else
alert('Not Completed Successfully');
},
error : function(xhr){
//Debugging
console.log(xhr);
}
});
}
PHP
<?php
Class Controller_ControllerName extends Controller_Template{
public $template = 'template';
public function action_index(){}
public function action_form(){
$this->auto_render = false; // <-EDITED
$array = array();
//PROCESSING FORM CODE HERE
if($success){
$array['status'] = 200;
}else{
$array['status'] = 500;
}
print json_encode($array);
}
}
?>
this is an example i have done without testing but this surely should be enough for you to work on

Categories