Retrieve and display json data from codeigniter function

How can to display data from database (SQL) using ajax (json) and codeigniter or php? i've tried to do it but the result is "undefined" here is my code:

How can to display data from database (SQL) using ajax (json) and codeigniter or php? i've tried to do it but the result is "undefined" here is my code:

jquery codes:

$('[id^="menuitem_"]').on('click',function(){
var menuID = $(this).attr('id').split("_")[1];
        $.ajax({
            url:"<?php echo base_url();?>Vendors_search/Get_Business_By_Type",
            method:"POST",
            dataType: "text",
            data: {menuID:menuID},
            success:function(resp){

              var obj = $.parseJSON(resp);
              var values = Object.values(obj); 
              $.each(obj,function(key,val){

              $('.business_id').append('<strong>' + val.business_name + '</strong>');
            });
    }

        });

Codeigniter codes:

function Get_Business_By_Type(){
    $obj = $this->input->post('menuID');     
    if($this->Search_obj_model->getBusinessType($obj)){
    $bus_type = $this->Search_obj_model->getBusinessType($obj);  
    $result['business_details'] = $this->Search_obj_model->getBusinessType($obj);
        }
        else{
            $result['message'] = 'Oooops! We could not find your request. Try again later';
        }
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($result));
    $string = $this->output->get_output();
    echo $string;
    exit();
 }

how to build a new json string from existing json string

I have multiple files that contain json data that looks like this:

I have multiple files that contain json data that looks like this:

1.json:

[{
    "id": 2100059,
    "email": "",
    "company": "acme",
    "job_title": "",
    "first_name": "Jane",
    "last_name": "Doe"
 }, 
 {
    "id": 2199991,
    "email": "",
    "company": "Widgets Inc",
    "job_title": "",
    "first_name": "John",
    "last_name": "Doe"
 }]

2.json:

[{
    "id": 123456,
    "email": "",
    "company": "acme",
    "job_title": "",
    "first_name": "GI Jame",
    "last_name": "Adf"
 }, 
 {
    "id": 000001,
    "email": "",
    "company": "Widgets Inc",
    "job_title": "",
    "first_name": "bob",
    "last_name": "billy"
 }]

How can I combine these two lists so that it's just one string, with one set of []?

So far, I'm writing the logic read in the contents of each file into separate strings. But then I'm thinking I should: 1. json_decode() each string to treat it like an object

Not sure how to append to the object though. any tips would be appreciated.

EDIT 1

I decided to read each file contents into an array, and then try the tips suggested below to use array_merge. when i do a print_r on my array, it looks like this: (bogus data, but you should get the idea)

Array
(
    [0] => [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}]
    [1] => [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}]
[2] =&gt; [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}
[3] =&gt;[{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}]

)

And then this is the logic I have that tries to combine all this into one json string:

    print_r($allpages);
$finaljsonstring ='';
foreach ($allpages as $item)
{
$finaljsonstring = $finaljsonstring + json_encode(array_merge(json_decode($item)));
}
echo $finaljsonstring;

But something is going wrong. (I'm calling this as ajax so it's hard to debug) but when i console.log the results from the ajax call, nothing is returned. Ultimately, what I need to return to the front end is a single array of json strings like this:

[{}, {},{}]

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Explore JSON and how JavaScript Objects can be used to access data within JSON data format and output to your web page

Guide to learning how to use JavaScript Objects and JSON data. JSON is the most popular format for data exchange between applications. If you are interested in connected to a web API chances are its JSON formatted. Learn to use AJAX to connect and bring JSON data into your JavaScript!

This course shows you how to work with JSON formatted data, output content, loop JSON data, Parse JSON and a whole lot more.

JSON (JavaScript Object Notation) is a syntax for data. JSON is easier to use than XML and human readable. Most modern web APIs output data in JSON formats. It's a lightweight data interchange format that is quickly becoming the default format for data exchange on internet today! JSON is lightweight, language independent and easy to read and write. JSON is better than XML and more popular!

Within the lessons of this course we will explore

  • JavaScript data types used to hold variables and how they work
  • JSON and how to write JSON data
  • How to add values into a JSON object
  • Accessing JSON data and bringing it into JavaScript
  • JavaScript JSON parse and stringify methods
  • Adding JSON to local storage
  • Retrieving back data within JSON formats, updating and working with JSON
  • Connecting to a web API using fetch
  • Retrieving JSON data from a web API and outputting the results into your web page
  • Iterating threw multiple results from an API
  • Google Spreadsheet data as JSON and how to practice retrieving data
  • All of the source code and resources are in included
  • Explore different methods of working with the JSON data stringify and parsing
  • How JavaScript objects can use Arrays to hold multiple items
  • How JavaScript arrays work and store data

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript and JSON

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Programming Tutorial | Full JavaScript Course for Beginners 2019

The complete beginner’s guide to JSON

The Complete Guide to JSON Web Tokens

JWT Fundamentals for Beginners

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

New ES2019 Features Every JavaScript Developer Should Know

Using JSON correctly in JavaScript and PHP

Using JSON correctly in JavaScript and PHP

JSON is an indispensable part for web applications. Here you will learn how to exchange and store JSON data correctly between JavaScript (client-side) and PHP (server-side).

Table of contents
  • Reading and saving JSON in PHP
  • Read JSON
  • Save JSON
  • Send JSON from PHP to JavaScript
  • JSON in JavaScript
  • Conclusion

JSON stands for JavaScript Object Notation and is a very simple and compact data format for storing and sending data. Data is often exchanged between the user (client) and the server. In this article we look at the data transfer and storage of JSON.

{
  "ceos": [
    {
      "id": "1",
      "name": "Steve Jobs"
    },
    {
      "id": "2",
      "name": "Bill Gates"
    },
    {
      "id": "3",
      "name": "Paul Allen"
    }
  ]
}

This is an example for JSON. Three entries with the attributes id and name are stored in the category ceos.

You can validate and format your JSON with this tool.

Since I would like to go more into the use of JavaScript and PHP here, you can have a look at the exact structure of JSON in this article if you are interested.

Reading and saving JSON in PHP

Reading JSON

In principle, JSON data can be stored very easily. A simple text file is sufficient to store the data there. When it comes to small amounts of data, this is also a common and good solution. However, if you have a lot of data, or data that is added dynamically (like a contact form), it is recommended to store the data in a database.

But here we start from small amounts of data and on the server side we have a file named storage.json with the following content (same content as the example above, minified only):

{"heroes":[{"id":"1","name":"Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}

The following lines can be used to read in and output the file:

<?php 
$file = file_get_contents("storage.json");
print_r($file);
?>

The unformatted output gives us the simple text content of the file:

{"heroes":[{"id":"1","name":"Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}

We can’t do much with this data in this form. We could write our own parser to convert it into an object or array. But it is much easier.

PHP offers us the function json_decode() to convert the JSON string into an object.

<?php 
$file = file_get_contents("storage.json");
$json_decoded = json_decode($file);
print_r($json_decoded);
?>

The JSON string has been converted to an object and we can treat it like any other object in PHP. This output looks like this:

stdClass Object
(
    [heroes] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => Steve Jobs
                )
        [1] =&gt; stdClass Object
            (
                [id] =&gt; 2
                [name] =&gt; Bill Gates
            )

        [2] =&gt; stdClass Object
            (
                [id] =&gt; 3
                [name] =&gt; Paul Allen
            )

        [3] =&gt; stdClass Object
            (
                [id] =&gt; 4
                [name] =&gt; Sundar Pichai
            )

    )

)

As already mentioned we can now use normal object operators to display or change the values of the object:

<?php
$file = file_get_contents("storage.json");
$json_decoded = json_decode($file);

echo $json_decoded->heroes[0]->name; // Output: Steve Jobs

$json_decoded->heroes[0]->name = "CEO Steve Jobs";

echo $json_decoded->heroes[0]->name; // Output: CEO Steve Jobs
?>

Save JSON

Once we have adjusted our data as desired, we can save it again.

<?php
$filename = "storage.json";
$file = file_get_contents($filename);
$json_decoded = json_decode($file);

$json_decoded->heroes[0]->name = "CEO Steve Jobs";

$json_encoded = json_encode($json_decoded);
file_put_contents($filename, $json_encoded);
?>

Since we decoded the JSON string while reading it out, we have to encode it again before saving it. This is done in PHP via json_encode(). That’s it, too. Simple, isn’t it?

Send JSON from PHP to JavaScript

To request data on the client side I like to use jQuery. Here is an example, which makes an Ajax request to our server.php and gets the data returned.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<title>JSON in JavaScript and PHP</title>
</head>

<body>

&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;script&gt;
    $.getJSON('server.php', {}, function(data) {
        console.log(data);
    });
&lt;/script&gt;

</body>

</html>

server.php

<?php
$file = file_get_contents("storage.json");
exit($file);
?>

The console output looks like this:


This gives us normal access in JavaScript to the data that originally came from our storage.json.

JSON in JavaScript

If we now have a JSON string in JavaScript, we can convert it to a JavaScript object using the JSON.parse() function. It looks like this:

var json = '{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}';

var obj = JSON.parse(json);
console.log(obj);

The output is identical to the output from our storage.json.


Conversely, we can convert a JavaScript object to JSON with JSON.stringify().

var json = '{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}';

var obj = JSON.parse(json);

var jsonAgain = JSON.stringify(obj);
console.log(jsonAgain);

The console output is then again our JSON string, which we also have in the variable json.

{"heroes":[{"id":"1","name":"CEO Steve Jobs"},{"id":"2","name":"Bill Gates"},{"id":"3","name":"Paul Allen"},{"id":"4","name":"Sundar Pichai"}]}
Conclusion

We have discussed the most important JSON functions for JavaScript and PHP. JSON is simply a very simple and compact data format. As you have now seen, the use in JavaScript and PHP is also quite simple. If you have any questions, please feel free to contact me via the comments! 

Originally published  at webdeasy.de on 21. May 2019

========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ The complete beginner’s guide to JSON

☞ The Complete Guide to JSON Web Tokens

☞ Svelte.js - The Complete Guide

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ The Complete Node.js Developer Course (3rd Edition)

☞ PHP for Beginners - Become a PHP Master - CMS Project

☞ Learn Object Oriented PHP By Building a Complete Website

☞ MEVP Stack Vue JS 2 Course: MySQL + Express.js + Vue.js +PHP

☞ Object Oriented PHP & MVC

☞ PHP OOP: Object Oriented Programming for beginners + Project