You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何在AJAX中编写URL?调用storeProduct方法遇404错误

Fixing the Page Not Found Error for Your AJAX Call to storeProduct

It looks like the core issue here is a mismatch between your AJAX URL and the actual route definition. Let’s break down how to fix this step by step:

1. Correct the AJAX URL

Your storeProduct route is defined as a POST request to the URI product_catalog, not product_catalog/storeProduct. The as => 'storeProduct' is just a route alias (for easy reference) and doesn’t add to the URL path.

Instead of hardcoding the URL, use Laravel’s route helper to generate the correct URL dynamically—this is best practice because it avoids breaking your code if you ever change the route URI later. Here’s how to adjust your AJAX code:

$(".my_form").submit(function(event) {
    event.preventDefault(); // Make sure this line is fully written!
    
    // Generate the correct URL using the route name
    var url = "{{ route('storeProduct') }}";
    
    // Collect form data (includes product_id and campaign_id if they're in the form)
    var formData = $(this).serialize();
    
    // Send the AJAX POST request
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        success: function(response) {
            // Handle success (e.g., show a confirmation message)
            console.log("Data saved successfully!");
        },
        error: function(xhr) {
            // Handle errors (e.g., log validation issues)
            console.error("Error saving data:", xhr.responseText);
        }
    });
});

2. Include the CSRF Token

Laravel requires a CSRF token for all POST requests to prevent cross-site request forgery. You have two easy ways to add this:

Option 1: Add a hidden input to your form

<form class="my_form">
    <!-- Your existing form fields (product_id, campaign_id) -->
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <button type="submit">Save</button>
</form>

Option 2: Set global AJAX headers

Add this meta tag to your HTML <head>:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then add this JavaScript to include the token in all AJAX requests:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

3. Verify Your Controller Method

Double-check that your storeProduct method in front\ProductCatalogController is set up to accept and save the data correctly. Here’s a basic example:

use Illuminate\Http\Request;

public function storeProduct(Request $request)
{
    // Validate incoming data (adjust rules to match your needs)
    $validated = $request->validate([
        'product_id' => 'required|integer',
        'campaign_id' => 'required|integer',
    ]);
    
    // Save to your database (replace with your model logic)
    // Example: ProductCampaign::create($validated);
    
    return response()->json(['success' => true]);
}

4. Check for Base URL Issues

If you still get a 404, confirm your app’s base URL is correct. If your app lives in a subdirectory, the route helper will automatically handle this, but if you ever hardcode the URL, make sure to include the full path (e.g., /my-app/product_catalog instead of ./product_catalog).

By following these steps, your AJAX call should correctly hit the storeProduct method and save product_id and campaign_id to your database without the Page Not Found error.

内容的提问来源于stack exchange,提问作者Unnati Patadia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:47:04