Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links.

Here is a snippet of my JavaScript code:

$(document).ready(function() {
    var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
    var searchRequest = null;

$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
    minLength: 3,
    source: function(request, response) {
        if (searchRequest !== null) {
            searchRequest.abort();
        }
        searchRequest = $.ajax({
            url: attr,
            method: 'get',
            dataType: "json",
            data: {nom: request.term},
            success: function(data) {
                searchRequest = null;
                console.log(data);

  $.each(data, function (i, v) {
  --- CREATE A VARIABLE TO STORE THE RESULT ---
  });

  return THE 'SOME VARIABLE;

  }
}).fail(function() {
                searchRequest = null;
            });
    }
 });
});

The console output after logging data shows:

Object {École secondaire De Rochebelle: "/GestigrisC/app_dev.php/lieux/voir/2", École secondaire la Camaradière: "/GestigrisC/app_dev.php/lieux/voir/3"} 

I have control over the JSON feed, so I can modify it to help create the necessary variable for returning results.

Thank you for your assistance!

Answer №1

If your goal is simply to create links and insert them into your HTML code, then the following snippet may be what you are seeking:

onSuccess: function(response) {
  let linkElements = '';
  $.each(response, function (index, value) {
    linkElements += '<a href="'+value+'">'+index+'</a>';
  });
  $('#target_container').html(linkElements);
}

Answer №2

Thank you for your assistance, I appreciate it :)

$(document).ready(function() {
var attribute = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var requestSearch = null;

$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
    minLength: 3,
    source: function(request, response) {
        if (requestSearch !== null) {
            requestSearch.abort();
        }
        requestSearch = $.ajax({
            url: attribute,
            method: 'get',
            dataType: "json",
            data: {nom: request.term},
            success : function(data){
            response($.map(data, function(obj){
            return {label: obj.type +  ' | ' + obj.label, type: obj.type, id: obj.id};
            }));
        }
        }).fail(function() {
            requestSearch = null;
        });
},
select: function (event, userInterface) {
    $('#leseulsteve_lieuxbundle_lieutype_nom').val(userInterface.item.label);
    $('#leseulsteve_lieuxbundle_lieutype_type').val(userInterface.item.type);
    $('#leseulsteve_lieuxbundle_lieutype_id').val(userInterface.item.id);
    $('#form').submit();
}
});
});

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

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Changing the dropdown icon in Autocomplete with Material-UI: A Step-by-Step Guide

Is it possible to change the icon for the open/close dropdown list without affecting the functionality? I attempted to use endAdornment but lost functionality for both remove and open/close icons. I simply want to replace Material-UI's custom arrow w ...

Dealing with a checkbox click event in Vuejs when there is no parent element involvement

In the table below, you can see checkboxes displayed as images: example image of a table with checkboxes Here is an example code snippet: <tbody> <tr @click="goDetail"> <th scope="row><input type="checkbox" /></th> <t ...

What is the method to output JSON using the mongodb ruby driver?

After executing a find query in the mongodb JavaScript console, I receive a well-formatted JSON response. However, when running the same query using the Ruby driver, it stores the result as a Ruby object. Is there a way to convert this back to JSON forma ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

Is it possible for a mobile web application to continue running even when the screen is

Thinking about creating a mobile web application with the use of jQuery Mobile for tracking truck deliveries. I'm interested in sending GPS coordinates back to the server periodically. Is this possible even when the screen is turned off? If not, any ...

Is there a way to transform these into five columns within a single row using the Material-UI Grid system?

I'm trying to align 5 columns in one row, but I'm struggling to achieve the desired layout. Here is what I currently have: https://i.stack.imgur.com/d3z3n.png Any tips on how to make all columns appear in a single row? You can also view my att ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

How can I prevent the same JavaScript from loading twice in PHP, JavaScript, and HTML when using `<script>'?

Is there a PHP equivalent of require_once or include_once for JavaScript within the <script> tag? While I understand that <script> is part of HTML, I'm curious if such functionality exists in either PHP or HTML. I am looking to avoid load ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

How can the HTML source code be printed without showing it in a window or tab?

Here's the scenario: I'm making an ajax post request to a controller action, which returns complete html source code. I want to print this html source as if it were being displayed in a browser without opening a new tab or window. Is there a way ...

What is the best way to send a continuous stream of data in Express?

I've been attempting to configure an Express application to send the response as a stream. var Readable = require('stream').Readable; var rs = Readable(); app.get('/report', function(req,res) { res.statusCode = 200; ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...

Encountering an Error When Trying to Read a JSON String: TypeError - string indices must be

I have been working on a program that involves reading a JSON string through a user interface and using it to perform various functions, such as breaking down mathematical equations. However, I am encountering an error message: "TypeError: string indice ...