I am attempting to send an array from the controller to JavaScript using AJAX, but instead of returning as an array, it is being returned as a string

Here is the code snippet from my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AjaxController extends Controller
{

    public function showOrder($id){
        $result = DB::select('select * from menu_tbl where id = ?', array($id));
        return json_encode($result);
    }
}

This is the javascript code I'm using:

function addOrder(id){
    $.ajax({
        method: "GET",
        url: "/showOrder/"+id,
        success: function (data){
            alert(data["name"] + " " + data);

            //document.getElementById("name").innerHTML = data['name'];
            //document.getElementById("price").innerHTML = data['price'];
            //$("#buying").modal();
        },
    });
}

And here is the result I'm getting:

undefined [{"id":1,"name":"Chicken Cordon Bleu","category":"chicken","price":800,"description":"blah blah","img":"img\/mcdonalds-burger.jpg","hot":0,"spicy":0}]

I am struggling with the 'data['name']' returning as 'undefined'. Is there an issue in my code or does 'DB:select' not return an array but a String instead? Any help would be appreciated as I am new to Laravel. Thank you!

Answer №1

Here is the updated code for you to use.

 function displayOrder($orderID){
        $result = DB::table('menu_tbl')->where('id',$orderID)->first();
        return \Response::json($result);

    }

Your jQuery code should look like this.

success: function (response){
        alert(response.name);
},

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

Loading New Page When Iframe is Loaded

I am currently working with an iframe that reflects the appscript I have created. Is there a way to automatically redirect the user to a different page when they change a link or submit a form within the iframe? <div class="embed-responsive em ...

Using Express JS to implement a post method for multipart form data transmission

I recently attempted to send form data to my express js server. Below is the code snippet from my pug file: form(action="/profile" method="post" enctype="multipart/form-data") input(type="file" accept="image/*" name="profileimage") input(type="text" nam ...

Plotting Polyline Path on Google Maps using Angular

I am attempting to create a simple polyline connecting two markers using Angular-google-maps. While I have successfully positioned my two markers, I am encountering some complexity when trying to draw a polyline between them. It seems that my logic may no ...

If the user fails to respond, Alexa will show an error message indicating that the skill response was marked as a failure

After completing the code for my Alexa skill, I encountered a problem. My fact-based skill template is set to wait for responses after the output, but if Alexa doesn't hear a response within 8 seconds, it generates an error (Skill response was marked ...

Every time I try to reload the page in my comment app, all the comments mysteriously

I've noticed that my comment app is functioning properly, but the issue arises when I refresh the page and the comments disappear. Upon checking the log, it seems that the body is inserted into the comments table (it is saved). What could be going wro ...

JavaScript first, middle, and last names

When working with Javascript, I have encountered a challenge. I am attempting to extract the First, Middle, and Last names from a full name input into three separate fields - Character Length, Middle Name, and Initials. At this point, I have successfull ...

Is it possible to utilize Angular.js as a full substitute for a traditional JavaScript template engine?

While angular excels in two-way data binding and single-page applications, could it also serve as a viable replacement for a JavaScript template engine? Let's dive into the potential pros and cons of this approach. ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

Learn the process of adjusting opacity for a specific color in CSS

At the moment, this is the code I'm using to apply a color to an element using jss. const styleSheet = theme => ({ root: { backgroundColor: theme.colors.red, }, }) I am interested in finding out if there is a way to add opacity based o ...

Unable to apply ng-class when condition is met after ng-click

I am currently experiencing an issue with ng-class. When I click, I pass a variable and then check if it is true in ng-class. If it is indeed true, I append the "col-xs-6" class. Here is what I have attempted: <div ng-class="{'col-xs-6': myV ...

Methods for effectively redirecting a Java ResponseWriter

I am looking for a way to view the output of my ResponseWriter directly in standard output for debugging purposes. Unfortunately, since the response will be handled by JavaScript, I am unable to see the output there. Is there a simple solution to redirect ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Automatically Adjust Text Size to Fit Input Forms using jQuery

Does anyone know how to use jQuery to dynamically change the font size in a form input field so that it always remains visible and fits even as the user types more text? I want the font size to start at 13px and progressively shrink as the text reaches the ...

transmit information during the loading process to the webpage fetched via ajax

When trying to load a page called url.php and pass the variable $x to it, I encountered an issue. var myid=mydata.id; $.ajax({ url:'url.php' ,async: true ,cache: ...

Concerning Java's Map and Array functionalities

When working with Javascript, we have the ability to create statements like the one below. var f_names = { 'a' : 'Apple', 'b' : 'Banana' 'c& ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

Tips for choosing elements that are not next to each other in a JavaScript array

If I have an array and want to select non-consecutive elements, such as the second and fifth elements, is there a simple method to do this? For example: a = ["a","b","c","d","e"] a.select_elements([1,4]) // should yield ["b","e"] EDIT: After some reflec ...

Deactivate a modal in Bootstrap 4 once it is closed

Trying to find a resolution for my issue. Utilizing bootstrap4 in a Laravel project and facing a problem with modals. Here is the code snippet: $("#newAddressBtn").on('click', function () { $('#modalAddressees').modal(&apo ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...