Laravel - load post with custom id via ajax - php

I want to load my post via AJAX when I click on a post link, how I can send my post ID via AJAX?
I've got a link in my Blade file:
{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}
I've got the following route definition:
Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController#show']);
And controller action:
public function show($id, $slug = null)
{
$post = $this->news->getById($id, 'news');
if ($slug != $post->slug){
return Redirect::route('news', ['id' => $post->id, 'slug' => $post->slug]);
}
Event::fire('posts.views', $post);
return View::make('post/post', compact('post'));
}
And then I'm trying this:
var postTitle = $(".link--to--post");
postTitle.click(function () {
$.ajax({
url: '/news/{id}-{slug}',
type: 'GET',
data: $(this),
success: function (data) {
console.log(data)
}
});
return false;
});
But this doesn't work for me, what am I doing wrong?

Your javascript should pass the parameters like this:
$.ajax({
url: '/news/' + id + '-' + slug,
success: function (data) {
console.log(data)
}
});
You had url: '/news/{id}-{slug}', which would perform a GET request to /news/{id}-{slug}, which isn't a valid route -- you want a URL like /news/1-foo.

Related

AJAX works locally; 404 on production

I have a Laravel application that works perfectly locally, but every AJAX call returns 404 when hosted. I'm unsure if this is from a sever config error, a missing php.ini setting, or something else? I've included an example of a failing call.
AJAX/JQ:
var url = "/final-review";
$("#review_note_text").change(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$('#review_note_loader').show();
var formData = {
note_text: $('#review_note_text').val(),
};
var type = "POST";
var reviewNoteUrl = url + '/review-note';
$.ajax({
type: type,
url: reviewNoteUrl,
data: formData,
dataType: 'json',
success: function (data) {
$('#failure-message-review').hide();
$('#success-message-review p').html("Saved successfully" + '×');
$('#success-message-review').show();
$('#review_note_loader').removeClass("halted-loader").hide();
},
error: function (data) {
$('#review_note_loader').addClass("halted-loader");
$('#failure-message-review p').html("Something went wrong, your record was not updated. <strong>Error Code: " + data.status + "</strong>" + '×');
$('#failure-message-review').show();
}
});
});
My Corresponding Route:
Route::post('final-review/review-note', 'FinalReviewController#update_review_note');
Controller Function
public function update_review_note(Request $request){
$validatedData = $request->validate([
'note_text' => 'nullable|string',
]);
$note = \App\ReviewNote::create([
'note_text' => $request->get('note_text'),
'author' => Auth::user()->name,
'created_at' => now()
]);
return Response::json($note);
}
SOLVED:
I had to change the "url" var in my blade template to be:
var url = "{{ url('/final-review') }}";
In my AJAX I was defining "url" as "/final-review", which led to a route of "foobar.com/final-review/params" what I really needed was "foobar.com/app-name/final-review/params".
Testing locally, I did not have "app-name" in my URL.

Pass a View Data From Controller to Ajax View File - Laravel 5

From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}

Laravel Pass Data to controller through ajax

I'm trying to send 2 variables to FavorisController: {{ Auth::user()->id }} and the id that I have in the URL
This is what I've tried so far
Route:
Route::get('annonce_test/{id}','FavorisController#create' );
My ajax script
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/{id}',
type: 'GET',
data: {id: 1, id_user: $id_user},
success: function(data){
alert(Ajouter au Favoris avec succes);
},
error: function(){},
});""
});
});
FavorisController
public function create(Requests $request)
{
$id_annonce = $_GET['id'];
$id_user = $_GET['id_user'];
$query = DB::table('annonce_residentiel_user')
->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id_user)
);
}
I got the error trying to get property of non-object {{ Auth::user()->id }}
But is this the correct way to do it? I mean if I have another script for deleting I should chage the url in my ajax script.
Move Auth::user() part from JS script to PHP:
->insertGetId(['annonce_residentiel_id' => $id_annonce , 'user_id' => auth()->user()->id]);
Also, make sure user is authenticated with something like:
if (auth()->check()) {
// Do stuff.
}
Based on your route definition $id is the argument for the create method and to get more data from the ajax call you should use Input::get. Also the route will be activated only when the url in the ajax call has the format of ex: annonce_test/25. check the update to the ajax call.
Route:
Route::get('annonce_test/{id}','FavorisController#create' );
Ajax call:
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/'+id_user,
type: 'GET',
data: {id: 1},
success: function(data){
alert(Ajouter au Favoris avec success);
},
error: function(){},
});
});
});
FavorisController:
public function create($id)
{
$id_annonce = Input::get['id'];
$query = DB::table('annonce_residentiel_user')->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id));
}

No response data ajax jquery laravel

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

ZF2: Call redirect() url | trigger GET from a post action

I have a simple post which looks like
$.ajax({
url: '/album/createAlbum.html',
type: 'POST',
dataType: 'json',
async: true,
data: postData,
success: function (data) {
console.log("Successfully saved album");
console.log(data);
return data;
},
error: function (data) {
console.log("FAILED to save album");
return false;
}
});
and a simple action which looks like
public function createAlbumAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$album = $request->getPost('album');
//First check to see if the user already has that album
$albumObject = $this->_dataService->getAlbum($userID, $album);
if ($albumObject){
//This is the issue
$this->redirect()->toRoute('albumModule', array('controller' => 'album', 'action' => 'edit'));
} else {
$albumObject = $this->_dataService->createAlbum($userID, $album);
}
$messages = array();
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
} else {
$response->setContent(\Zend\Json\Json::encode(array('albumID' => $albumObject->getAlbumID())));
}
return $response;
}
The issue I'm having is on the redirect(), I know that the redirect will send me to that route, but I need to tell the browser to GET that route. I can't figure out how to do this from a POST. I read something about setting the header to 303 so that the browser knows to do redirect, but I wouldn't know how to return that in my JSON response.
Even when I try to do header:("Location: " ...) that won't tell the browser to GET the url.
I just ended up going with this
On the ajax call
error: function (request, textStatus, errorThrown) {
console.log("FAILED to save album");
//The Album already exists, so redirect to it
window.location = request.getResponseHeader('redirectURL');
return false;
},
On the ZF2 Action
$response->setStatusCode(Response::STATUS_CODE_301)->getHeaders()
->addHeaders(array('redirectURL' => $this->url()->fromRoute('albumModule', array('controller' => 'album', 'action' => 'edit', 'id' => $albumObject->getAlbumID()))));
return $response;

Categories