Featuring data utilizing Ajax JSON in CodeIgniter

How can I display the data using AJAX? After making the data call to the controller, the JSON data is available but the data for "name", "address", and "telp" based on the "id_data" is not showing up. How can I display this data?

Views

<input id="id_data" value="5" />

<input id="name">
<input id="address">
<input id="telp">

<script type="text/javascript">
$(document).ready(function() {
    var id = $('#id_data').val();
    $.ajax({
        url : "<?php echo site_url('my_controllers/show_data/')?>" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $('#name').text(data.name);
            $('#address').text(data.address);
            $('#telp').text(data.telp);
        }
    });     
})
</script>

Controllers

function show_data($id) {   
    $data = $this->my_models->get_data($id);
    echo json_encode($data);
}

Models

function get_data($id) {
    $query = $this->db->select('*')
                      ->from('tb_student')
                      ->where('id', $id)
                      ->get();

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $data) {
            $hasil[] = $data;
        }
        return $hasil;
    } 

}

Result JSON

[
    {"id":"5","name":"John","address":"Miami","telp":"012345678"},
    {"id":"5","name":"Smith","address":"Chichago","telp":"012345678"},
    {"id":"5","name":"Steve","address":"Texas","telp":"012345678"},
]

Answer №1

It appears that each dataset is being appended to an array named $hasil, which is then JSON encoded and sent back to the view. In the view, you should either iterate through the array or access its first key if it exists.

To display the first dataset from the response, you can use the following script:

$(document).ready(function() {
  var id = $('#id_data').val();
  $.ajax({
    url: "<?php echo site_url('my_controllers/show_data/')?>" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data) {
      if (data[0] === undefined) return;
      $('#name').text(data[0].name);
      $('#address').text(data[0].address);
      $('#telp').text(data[0].telp);
    }
  });
})

If you want to display all elements, one way to do so would be by creating DOM elements in a loop. Here's an example using data stored in a variable:

var json = [{
  "id": "5",
  "name": "John",
  "address": "Miami",
  "telp": "012345678"
}, {
  "id": "5",
  "name": "Smith",
  "address": "Chichago",
  "telp": "012345678"
}, {
  "id": "5",
  "name": "Steve",
  "address": "Texas",
  "telp": "012345678"
}];

function show(data, $view) {
  data.forEach(function(current, index, array) {
    var $form = $('<form />');
    
    var $input_id = $('<input />')
      .attr('name', 'id')
      .attr('type', 'hidden')
      .val(current.id);
    var $input_name = $('<input />')
      .attr('name', 'name')
      .attr('type', 'text')
      .val(current.name);
    var $input_address = $('<input />')
      .attr('name', 'address')
      .attr('type', 'text')
      .val(current.address);
    var $input_telp = $('<input />')
      .attr('name', 'telp')
      .attr('type', 'text')
      .val(current.telp);

    $form.append($input_id, $input_name, $input_address, $input_telp)
    $view.append($form);
  });
}

$(function() {
  show(json, $('#view'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="view"></div>

You may need to adjust the code to fit your specific Ajax callback, or you could integrate the show() function into your script and call it within the success callback like this:

$(document).ready(function() {
  var id = $('#id_data').val();
  $.ajax({
    url: "<?php echo site_url('my_controllers/show_data/')?>" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data) {
      show(data, $(document))
    }
  });
})

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

Using Javascript to make a call to a RESTful endpoint

My current challenge involves attempting to make a call to the Spotify API from JavaScript: function callAPI() { var xhttp = new XMLHttpRequest(); xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track'); ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...

Using user-generated input to manipulate the options of a jQuery function

Can anyone help me with controlling an input in jQuery? jQuery.ajax({ type: "get", dataType: "jsonp", url: "http://www.foo.com/something.php", data: {numberInput: "NUMBER I WANT TO CONTROL" }, I have an HTML input field: <input type="text ...

Using React to display data from a nested JSON object in a table

I am currently working on parsing a JSON object into a table using React. However, I am facing an issue with utilizing the .map() function to create a row for every unique combination of course code, name, transferable_credits, transferable_credits -> i ...

Tips for dynamically populating a mat-table dataSource

While working with backend data streaming, I encountered an issue where trying to push an event to dataSource resulted in an error stating that dataSource is not defined. Can anyone provide guidance on how to dynamically add data to a materialize table? s ...

Unable to use jQuery to delete class from an element

Here is the markup I am working with: <div class="row"> <img src="image.png" class="download-image regular-image" /> <div class="options"> <p>download</p> </div> <img src="image.png" class="download-image r ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

Effortless login authentication using Disqus through Google or Facebook tokens

I have set up my website to allow users to authenticate through Google and Facebook using passport, which uses the OAuth 2.0 API. Additionally, I am utilizing Disqus to manage the comments system on my site. However, I am running into a problem where user ...

Disable browser suggestions in Material UI's Autocomplete component

Encountering an issue with Material-ui Autocomplete: import Autocomplete from "@material-ui/lab/Autocomplete"; Currently using it in: <Autocomplete id="checkboxes-tags-demo" autoComplete={false} options={sta ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

A problem has occurred in Next.js where FileReader is not recognized and is causing a Reference

Exploring the latest features of Next.js 13 with the /app directory, I encountered an issue while using the FileReader in a basic client-side component that manages an input form. Here is a brief overview of the code: "use client"; import React, ...

Using ThreeJS to project a mouse click onto the XZ plane

I am currently working on implementing offline routing in a 3D map within a ThreeJS scene. My goal is to allow the user to click on a point and have a cube navigate to that point. While the navigation functionality is working correctly, I am facing an issu ...

Adding the highcharts-more.src.js file to an Angular 2 project: A step-by-step guide

I have linked highcharts-more to the system variable: 'highcharts-more': 'node_modules/highcharts/highcharts-more.src.js' But I keep getting an error message saying: Error in dev/process/templates/detail.template.html:40:33 ORIGINAL ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...

Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are: all generated values must be distinct the order of values remains consistent upon each run of the generator each value should be significantly diff ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

- **Rewrite** this text to be unique:- **Bold

Check out this relevant jsFiddle link Below is a list where I aim to make all occurrences of the word 'Bold' bold: <ul id = "list"> <li>Make this word Bold</li> <li>Bold this as well</li> <ul> ...

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...