I am working with laravel 10 php 8.10, Here javascript ajax button is working fine for php artisan serve http://127.0.0.1, while giving error for **MAMP PRO** (localhost:888 Error occurred while processing request.) and not working with url http://localhost:8888/xxx/public Here is the snippet of the html and js

Needed Help to resolve the issue.

**HTML**

@if($row->soc_extra==1)
                        <a class="updatesocialmediaStatus" id="socialmedia-{{ $row->id }}" socialmedia_id="{{ $row->id }}" href="javascript:void(0)"><i class="fas fa-toggle-on" soc-extra="Active"></i></a>
                    @else
                        <a class="updatesocialmediaStatus" id="page-{{ $row->id }}" socialmedia_id="{{ $row->id }}" style='color:#007bff;' style="color:gray" href="javascript:void(0)"><i class="fas fa-toggle-off" soc-extra="Inactive"></i></a>
                    @endif
                      &nbsp;&nbsp;
                      <a style='color:#007bff;' href="{{ url('admin/social-media/edit/'.$row->id) }}"><i class="fas fa-edit"></i></a>
                        &nbsp;&nbsp;
                        <a style='color:#007bff;' class="confirmDelete" name="socialmedia" title="Delete socialmedia" href="javascript:void(0)" record="socialmedia" recordid="{{ $row->id }}" <?php /*href="{{ url('admin/delete-socialmedia/'.$row['id']) }}"*/ ?>><i class="fas fa-trash"></i></a>
                        &nbsp;&nbsp;
@endforeach


**JS**

<script>
    $(document).on("click", ".updatesocialmediaStatus", function(){
        var soc_extra = $(this).children("i").attr("soc-extra");
        var social_media_id = $(this).attr("socialmedia_id");

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'post',
            url: '/admin/update-socialmedia-status',
            data: {soc_extra: soc_extra, social_media_id: social_media_id},
            success:function(resp){
                if (resp['status'] == 0) {
                    $("#socialmedia-" + social_media_id).html("<i class='fas fa-toggle-off' style='color:grey' soc-extra='Inactive'></i>");
                } else if (resp['status'] == 1) {
                    $("#socialmedia-" + social_media_id).html("<i class='fas fa-toggle-on' style='color:#007bff' soc-extra='Active'></i>");
                }
             },
             error:function(xhr, textStatus, errorThrown){
                 console.log(xhr.responseText);
                 alert('Error occurred while processing request.');
             }
         });
    });
    </script>

Needed help to resolve this issue.

4

There are 4 best solutions below

1
ChipChop Gizmo On

Is your MAMP Apache port for localhost definitely set to port 8888 rather than port 80?

I've done that few times (8888 for testing 80 for deployment) and left Ajax calls targeting localhost instead of localhost:8888 or other way around.

Or, you may have to explicitly target the 8888 in your Ajax call i.e.

url: 'http://localhost:8888/admin/update-socialmedia-status'

Hope that helps?

1
akash gupta On

when you use MAMP PRO, the server runs on http://localhost:8888, and if your JavaScript code tries to make requests to http://localhost:8888 from a different domain (e.g., http://127.0.0.1:8000), it may encounter a CORS issue.

To resolve the CORS issue, you can do the following: Enable CORS on the server-side php artisan make:middleware CorsMiddleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware {
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');

        return $response;
    } }

protected $middleware = [ \App\Http\Middleware\CorsMiddleware::class, ];

// Correct URL const url = 'http://localhost:8888/xxx/public/api/some-endpoint';

// Correct AJAX request $.ajax({
    url: url,
    type: 'GET',
    // Other AJAX settings... });
0
ChipChop Gizmo On

Honestly, the only way to debug Ajax is not to use Ajax! Basically the question is, is the problem with the backend and it's crashing or is it the actual Ajax call being malformed i.e. refused.

What I would do is to create a test page (on the backend) that would have all parameters that it's expecting from Ajax hardcoded, so every single POST variable that is expecting pre-baked and the result just to be a simple echo that spits the result on the page or even just a simple - echo "ok"; Then simply hit that page address in the browser, if it spits out whatever data you need than it's Ajax, if it doesn't then it's the backend, maybe communication with a database or something like that but you may get a better error description if you have enabled php to show errors.

If the first "all variables set" test goes through, then hit the same page with Ajax, if that doesn't work target one variable at the time, you only have 4 things: X-CSRF-TOKEN,soc_extra, social_media_id and the actual route

Depending on the server's reverse proxy it may also be the header issue, or the route, try targeting a fully qualified URI first i.e. url:'https://www.xxx.xom/admin/update-socialmedia-status' with or without the "/" at the end

0
SilvaHps On

Finally solved. It was due to the difference in the base URL when running the code with php artisan serve and localhost:8888 (MAMP).

When i was using php artisan serve, the server is running at http://127.0.0.1:8000/ by default, and my URL for the AJAX request is /admin/update-socialmedia-status, which works fine.

However, whenever i was using MAMP, it sets up the server at http://localhost:8888/project_folder/, which means the base URL is different. Consequently, when my AJAX request uses /admin/update-socialmedia-status as the URL, it's trying to access http://localhost:8888/admin/update-socialmedia-status, which doesn't exist.

Here's how I modify my code to achieve that:

var baseUrl = '';

<script>
    $(document).on("click", ".updatesocialmediaStatus", function(){
        var soc_extra = $(this).children("i").attr("soc-extra");
        var social_media_id = $(this).attr("socialmedia_id");

        // Get base URL dynamically
        var baseUrl = '<?php echo url('/'); ?>';

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            type: 'post',
            url: baseUrl + '/admin/update-socialmedia-status',
            data: {soc_extra: soc_extra, social_media_id: social_media_id},
            success:function(resp){
                if (resp['status'] == 0) {
                    $("#socialmedia-" + social_media_id).html("<i class='fas fa-toggle-off' style='color:grey' soc-extra='Inactive'></i>");
                } else if (resp['status'] == 1) {
                    $("#socialmedia-" + social_media_id).html("<i class='fas fa-toggle-on' style='color:#007bff' soc-extra='Active'></i>");
                }
             },
             error:function(xhr, textStatus, errorThrown){
                 console.log(xhr.responseText);
                 alert('Error occurred while processing request.');
             }
         });
    });
</script>