Using Laravel to dynamically load a post with a specific custom identifier through an asynchronous HTTP request

When I click on a post link, I want to load my post via AJAX. How can I send the post ID through AJAX?

In my Blade file, there is a link:

{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}

I have defined the route as follows:

Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController@show']);

The controller action looks like this:

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'));
}

Now, I'm attempting the following:

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;
});

However, it's not working for me. What am I doing wrong?

Answer №1

Make sure your JavaScript function is passing the parameters correctly:

$.ajax({
    url: '/articles/' + postId + '-' + title,
    success: function (result) {
        console.log(result)
    }      
});

You previously had

url: '/articles/{postId}-{title}'
, but this would send a request to /articles/{postId}-{title}, which is not a valid URL format -- you should use a URL like /articles/123-example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing two ajax calls within a non-existent div that has only just been appended

I've been developing a website similar to 9gag. I attempted to incorporate a voting feature created by someone else, as I'm not well-versed in AJAX requests, but it just doesn't seem to be functioning. My index.php file fetches five posts f ...

Is there a way to recycle an image and ensure that the web browser only needs to download it once?

Is there a way to effectively reuse the same image multiple times on my website without inefficiently downloading it each time? ...

Encountering Vue Router Error while integrating Laravel 9 with Vite and Vue CLI 3

I am struggling to fix it, please assist me. I can't seem to pinpoint the issue and need some guidance. Error Image Links: https://i.stack.imgur.com/VhVXL.png https://i.stack.imgur.com/IENFm.png ...

Sharing variables between controllers in LaravelPassing data between controllers in Laravel

Recently, I started learning Laravel and came across a scenario where I have two controllers: CartController with the function finalizeCart and PaymentController with the function postPayment. Now, I am trying to figure out how to transfer the variable " ...

Dynamic data in highcharts pie charts allows for the customization and selection of colors

I am working with a pie chart that looks like this { type : 'pie', data : [], //dynamic data goes here center : [50, 15 ], size : 80, showInLegend : false, dataLabels : enabled: true, } Now, I am interested in changing the color of ...

What is the best way to retrieve an object from a form request using Laravel and convert it into an array?

{ $student = Student::find($id)->user_works; $works = $requests['sample_work']; foreach($student as $id => $student_work) { $work = UserWork::find($student_work->id); $work->u ...

Disguise the pop-up text in jQuery by utilizing the hide feature

Currently, I am utilizing the title attribute of my 'a' tag to display and hide corresponding images. However, the annoying title text pops up when hovering on the 'a'. Is there a way to disable this pop-up text without completely disa ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Tips for obtaining a collection of subelements based on a particular index in jQuery

I have a sample DOM structure: <div class="x"> <div class="y"> <span>a</span> <span>b</span> <span>c</span> </div> <div class="y"> <span>d</span> <span> ...

Utilize a stored string as the destination for the content of an object

We are currently working on processing a large amount of json data and trying to specify which parts of it to use using string variables. My goal is to convert a string into an object path to access the content of an item. The following code works correc ...

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

Tips for deleting elements that do not have a specific class assigned

My HTML page is quite large. Various elements such as p, h1, and div are labeled with the 'keep_me' class. Is there a way to remove all elements from the page that do not have this class using jQuery? I attempted something like this, but it didn ...

Tips for transforming an html form into an ajax request for a rest controller when dealing with a multi-select field

I am encountering an issue with the field "roles" as it is a select list with multiple choices. I need to convert this field into an array, but I have not been able to find any information on how to do so. Any assistance would be greatly appreciated. Thi ...

Exploring the Magic of Laravel Eloquent: Understanding the Intricacies of a

Recently delving into Laravel-eloquent, I am seeking guidance on transforming this SQL query to Eloquent format: select fl.id, fut.id, fut.firebase_topic_id, ft.id, fl.created_at from firebase_logs fl, firebase_user_topics fut, firebase_to ...

Passing Table values from a View to a Controller in ASP.Net MVC

In my view, I have created a table that functions as a timesheet with an option to add more rows using a button. <table class="table table-bordered table-responsive table-hover" id="mytab" cellspacing="0" cellpadding=" ...

Uploading files through AJAX modal window (elevate)

Is there a way to successfully upload files within an AJAX modal window in Lift? I attempted the following approach: ajaxForm( bind("upload", template, "file" -> SHtml.fileUpload(processFile _), "submit" -> SHtml.ajaxSubmit("Subm ...

When utilizing the php base_url, I am unable to initiate a redirect to a different page using ajax

My aim is to utilize ajax in order to redirect to another page when a certain condition is met. However, I am facing difficulties when trying to achieve this using the php base_url. Strangely enough, if I use the direct path (http://localhost/CRH/......), ...

Is there a way to obtain an Instagram login token through AJAX?

I'm encountering issues while trying to receive a token from Instagram. Despite using the following code, I keep running into these errors: SEC7127: CORS request blocked the redirect. SCRIPT7002: XMLHttpRequest: Network Error 0x2ef1, Unable to final ...

Effortless JavaScript function for retrieving the chosen value from a dropdown menu/select element

I've figured out how to retrieve the value or text of a selected item in a dropdown menu: document.getElementById('selNames').options[document.getElementById('selNames').selectedIndex].value In order to simplify this code, I&apos ...

What is the best way to save data from a jQuery plugin to a database using ASP .NET MVC?

I have a jQuery plugin called "Slider" that displays the current price of an item. I would like to enhance it by allowing users to change prices using the jQuery slider and update them in the database. Here is the model: public class Item { public in ...