Using AJAX to send an array as a response from Laravel

After implementing Laravel to handle an AJAX post request, I encountered an issue with displaying the route data.

public function infoRoute(Request $request)
    {
        // Extracting required information
        $ship_id = $request->ship_id;
        $startDate = $request->datepicker_start;
        $endDate = $request->datepicker_end;

        // Retrieving all locations within the specified dates
        $routeArray = $this->measurementRepository->getCoordinates($ship_id, $startDate, $endDate);

        $ship = $this->shipRepository->getShipForId($ship_id);
        $info = $this->createRouteArrayForShip($ship, $routeArray);

        if($request->ajax()) {
            return response()->json(json_encode($info));
        }
    }

    protected function createRouteArrayForShip($ship, $routeArray)
    {
        $info['type'] = "showRoute";

        $index = 0;

        foreach($routeArray as $coordinates)
        {
            $info['info']['route']['loc'. $index] = $coordinates;
            $index++;
        }

        $info['info']['shipInfo'] = $ship;

        return $info;
    }

Upon receiving and processing the data using jQuery, everything displays successfully except for the route which appears empty.

Your assistance would be greatly appreciated,

Answer №1

When you use the response()->json() method, it automatically converts the provided array into JSON format using PHP's json_encode() function in the background. Therefore, there is no need to include json_encode() within the response()->json() call.

Instead, your code should be simplified to:

return response()->json($info);

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

"Learn how to dynamically update the value of a text box using a loop in jQuery when the

I am looking for a way to update the value of the second input field when the first one is changed. For example, if the user changes the value in "valuex00", I want the same value to be displayed in "valuey00". This should apply to all corresponding pairs ...

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

Load Image Timing Discrepancy in Web Development (jQuery/PHP/HTML)

I am currently using jQuery to develop a basic slideshow feature. Within my home.php file, I have created a slideshow. Additionally, there is a menubar that allows users to navigate to different pages. Upon clicking on "Home" in the menu, the home.php con ...

php, file actor

Is there a method to automatically remove the last character from each line in a file using PHP? I am working with a file containing multiple lines, and I need to delete the final character of each line. Do I have to iterate through the file line by line ...

Is there a way to trigger a modal to open in VueJS with Bootstrap?

I have been attempting to trigger a modal in my Vue Template using bootstrap. However, I am encountering an issue where the modal does not appear when I use jQuery on it. Below is the code snippet: <template> <div id="app_religion"> ...

Sending form information through AjaxPassing information from a form using

Currently, I am working on a project where one page opens a thickbox of another page that contains a form. Once the form is submitted and data is written to the database, I need the parent page of the thickbox to update specific rows of the form that have ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

Verify if the user is currently active

Is there a method to determine if the user is not active? I am currently utilizing raw PHP. I would like for the user to be automatically logged out once they close the window, indicating their inactivity. I attempted implementing window.addEventListener ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

Retrieving information from an ImmutableMultiDict in Flask

I'm currently in the process of learning how to utilize ajax with Flask. My approach involves sending an ajax request and handling the data as a post request within my Python file. The code snippet in my HTML file: var data = {"name":"John Doe","age ...

Using functions like nl2br() for new line breaks, preg_replace for replacing patterns, htmlspecialchars() for encoding special

I've reviewed all the answers on this topic, but I'm still struggling to find the correct method for sanitizing data. My task is to enter: <?php echo 'yes'; ?> <?php echo 'yes' ?> into a text area, submit it in ...

Having trouble with PHP's $_GET not reading my AJAX URL accurately

It seems like there might be an issue with how the $_GET variable is interpreting my ajax URL, possibly due to a deep linking plugin I have installed. The final URL that is causing trouble looks like this: /dashboard.php#/projectSetup.php?mode=edit&ge ...

The fsockopen whois function is functional when used on localhost, however, it encounters issues on the

When it comes to connecting to the whois server, I rely on this particular code snippet. The vpb_domain_whois is an array and everything seems to work perfectly fine in my localhost environment. However, once I upload it to my hosting server, an error pops ...

How to identify and assign labels to elements in a numpy group

I have a solid grasp on how to assign labels to elements in one input array as shown below: arr_value = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 1, 1]) arr_res_1 = np.array([0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9, 9, 9, 9]) # treat zeros in arr_value ...

Is it possible to include array elements in a dropdown menu using React?

Imagine you have an array called const places = [" a1", "a2", "a3"]; and <FormControl variant="outlined" className={classes.formControl}> <InputLabel id="dropdown_label">Testing</InputL ...

Determine if the same origin policy is in effect

Is there a method to determine if the same origin policy is applicable to a URL before attempting to use ajax methods? Below is an example of what I currently have: function testSameOrigin(url) { var loc = window.location, a = document.create ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

Is there a way for me to extract a random set of coordinates from a particular country using this GeoJson file?

My goal is to utilize the following GeoJson file Through PHP on my server, I want to be able to retrieve a random point by calling a URL like: http://example.com/point.php?country=Argentina and having it output one random point. I am aware that the geojs ...

Incorporate an Ajax request onto an existing link within a div element

Here is what I have: <div id="div-for-ajax-onclick"> <a href="http://www.google.com">Link to google</a> </div> $("#div-for-ajax-onclick").click(function() { // update database }); I am looking for a solution where if someone c ...