Laravel 5.
I load view from controller using ajax.
When load first time then everything okay.
But when press f5 then it not work. ctrl+f5 then Okay.
I don't know what happen.
Please help me.
Controller
class TopSliderController extends Controller
{
public function index(Request $request)
{
return view('home.top_slider');
}
}
My javascript
(function($) {
load_view("/topic", "GET", "#test_top", []);
}(jQuery));
function load_view(url, method, field_id, param = []) {
$.ajax({
url: url, //+= '?_=' + (new Date()).getTime()
method: method,
data: {param},
timeout: 10000,
datatype: "html",
success:function(result)
{
$(field_id).html(result);
}
});
}
View
<div id="test_top">
</div>
Related
I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);
CartController Method
public function update(Request $request, $id)
{
$product = Product::find($id);
$data['cart_item_id'] = $product->$id;
$data['cart_item_name'] = $product->name;
$data['cart_item_price'] = $product->price;
\Gloudemans\Shoppingcart\Facades\Cart::add($data['cart_item_id'], $data['cart_item_name'], 1, $data['cart_item_price']);
return Response::json(['success' => true, 'data' => $data]);
}
script:
<script type="text/javascript">
$('.item_add').click(function (event) {
event.preventDefault();
var data = $('.item_add').serializeArray();
$.ajax({
url: $(this).attr('href'),
data: data,
type: 'GET',
dataType: 'JSON',
success: function (html) {
alert('Hello')
}
});
return false;
});
</script>
view:
<a href="{{route('cart.update',$productItem->id)}}" class="item_add">
When Im watching network-request-response I get nothing, why don't I get data which i return from controller?
I checked your code and it works.
I can suggest you have forgotten to run "gulp" for your javascripts after you added ajax method in it (this is the only reason why you see nothing in "network-request-response"). Because, if ajax works then there would be a response (with or without error).
I'm using Laravel 5 and want to make ajax call to a controller with some data:
$.ajax({
url : "/getOrgById",
data : JSON.stringify({id:1})
})
The routes.php has:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById($data) {
//code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}
How can I pass the data from ajax to route and then to controller?
I think the below example is what you're looking for
Route
Route::post('/getOrgById', 'HomeController#getOrgById');
Controller
public function getOrgById(Request $request) {
$id = $request->input('id');
}
JS
var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
//handle response
})
You should really look into resourceful controller actions. If you are wanting to fetch an organisation by its ID then you have an organisaiton entity, so create a corresponding organisation controller. This controller can then have a method to show an organisation by on its primary key value:
class OrganisationController
{
public function show($id)
{
return Organisation::findOrFail($id);
}
}
The route for this would look like:
Route::get('/organisations/{id}', 'OrganisationController#show');
You can then request this route via AJAX like so:
$.ajax({
method: 'GET',
url: '/organisations/' + id
});
You can use Input to get your variable
public function getOrgById() {
$data = \Input::get('data')
}
You can define paramers in your route:
Route::get('/getOrgById/{id}', 'HomeController#getOrgById');
And call it through:
$.ajax({
url : "/getOrgById" + id
})
You were almost right, but when using $data in your function declaration you're actually requiring a Query String variable, rather than a form request.
You have to add your Form Request in your Controller method, like so:
public function getOrgById(Request $request){
// do something here...
return response()->json(array('foo' => 'bar'));
}
Try with this,
HTML Form
<div id="loadingResponse"></div>
{!!Form::open(array('url'=>'test/submit', 'id'=>'submitForm','method'=>'POST'))!!}
{{Form::token()}}
<input type="text" name="data"/>
<button type="submit" class="btn btn-small btn-info">Send Data</button>
{{Form::close()}}
JS Ajax
$("#submitForm").submit(function(event) {
event.preventDefault();
$.ajax({
url : 'test/submit',
data : new FormData($("#submitForm")[0]),
dataType : 'JSON',
type : 'POST',
beforeSend: function(){
$("#loadingResponse").html("<img src='{{asset('img/loading.gif')}}' />");
},
success: function(response){
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Error '+xhr.status+' | '+thrownError);
},
});
});
PHP Route
...
Route::post("test/submit","TestController#submit");
...
PHP Controller
class TestController extends Controller
{
...
public function submit(Request $request)
{
response()->json(['msj' => $request->input('data')]);
}
...
}
ajax:
$.ajax({
type:'get',
url:'/getOrgById',
data:{
id:1
},
success:function(res){
}
});
routes.php:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById(Request $request) {
dd($request);
}
I'm using cakePHP 3.0 and I have a problem while using ajax. Indeed, I would like to execute the action "viewTab" of my controller "SpecimensController" on an array coming from my view "specimen"
<script type="text/javascript" >
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'specimens','action'=>'index'));?>",
data:{datas: $("select[name='filtreVariable\\[\\]']").map(function(){return $(this).val();}).get()},
dataType: 'text',
async:false,
success: function(data){
alert('success');
},
error: function (data) {
alert("error");
}
});
}
$("#filtre").submit(function(){
updateResult();
});
</script>
The action "viewTab" is just doing:
echo "success";
But I can't find the right url so the function success can be called. I tried many things and I always have the function error of ajax that is called. :/
If you haven't yet, place this line of code in your AppController where your initialize function is:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
In your controller for the function you're calling via ajax, try something like this:
public function index()
{
$data = ['testing'];
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html
I am trying to call controller in module using Ajax in prestashop 1.5, and I'm having hard time doing this.
I've created controller in module under the path:
$refresh_url = ($this->_path)."front/blockdiscoversellers.php";
and made instructions for button in js like:
var refresh = {
call: function() {
var $refresh = $("#manufacturer-refresh");
$refresh.click(function(e) {
refresh.ajax();
e.preventDefault();
});
},
ajax: function() {
var url = $("#manufacturer-refresh").data("url");
$.ajax({
url: url,
type: 'get',
data: {
controller : 'BlockDiscoverSellers',
ajax : true
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
};
and the body of controller looks like :
class BlockDiscoverSellers {
public function __construct()
{
die(var_dump($this->refreshManufacturers()));
}
public function refreshManufacturers()
{
$result = array("test" => "TESTER");
return Tools::jsonEncode($result);
}
}
I'm getting success in Ajax call but it looks like class and constructor are not initiated, so I am quite stuck with this problem.
It appears that prestashop when you use ajax call uses only structural type of programming. That means in ajax call there can be no class of any sort bootstrap will never initiate it even with controller parameter, and you have to die at the end of file ...