Issues arise when using PHP4 in conjunction with Ajax, the json_encode function, and

I have been tasked with a project for my company that requires PHP4 development. The goal is to display a list of mobile phone brands and their prices, as well as the ability to filter them using multiple checkboxes. However, I am facing an issue where the information from the database is not being displayed.

index.php

<!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>AJAX filter demo</title>
        <style>
          body {
            padding: 10px;
          }

          h1 {
              margin: 0 0 0.5em 0;
              color: #343434;
              font-weight: normal;
              font-family: 'Ultra', sans-serif;   
              font-size: 36px;
              line-height: 42px;
              text-transform: uppercase;
              text-shadow: 0 2px white, 0 3px #777;
          }

          h2 {
              margin: 1em 0 0.3em 0;
              color: #343434;
              font-weight: normal;
              font-size: 30px;
              line-height: 40px;
              font-family: 'Orienta', sans-serif;
          }

          #phones {
            font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
            font-size: 12px;
            background: #fff;
            margin: 15px 25px 0 0;
            border-collapse: collapse;
            text-align: center;
            float: left;
            width: 300px;
          }

          #phones th {
            font-size: 14px;
            font-weight: normal;
            color: #039;
            padding: 10px 8px;
            border-bottom: 2px solid #6678b1;
          }

          #phones td {
            border-bottom: 1px solid #ccc;
            color: #669;
            padding: 8px 10px;
          }

          #phones tbody tr:hover td {
            color: #009;
          }

          #filter {
            float:left;
          }
        </style>
      </head>
      <body> 
        <h1>Mobile Phones Database</h1>

        <table id="phones">
          <thead>
            <tr>
              <th>ID</th>
              <th>Brand</th>
              <th>Model</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>

        <div id="filter">
          <h2>Filter Options</h2>
          <div>
            <input type="checkbox" id="Samsung" checked>
            <label for="Samsung">Samsung</label>
          </div>
          <div>
            <input type="checkbox" id="iPhone" checked>
            <label for="iPhone">iPhone</label>
          </div>
          <div>
            <input type="checkbox" id="HTC" checked>
            <label for="HTC">HTC</label>
          </div>
          <div>
            <input type="checkbox" id="LG" checked>
            <label for="LG">LG</label>
          </div>
          <div>
            <input type="checkbox" id="Nokia" checked>
            <label for="Nokia">Nokia</label>
          </div>
        </div>

        <script src="http://code.jquery.com/jquery-latest.js"></script> 
        <script>
          function makeTable(data){
            console.log(data);
           var tbl_body = "";
              $.each(data, function() {
                var tbl_row = "";
                $.each(this, function(k , v) {
                  tbl_row += "<td>"+v+"</td>";
                })
                tbl_body += "<tr>"+tbl_row+"</tr>";
              })

            return tbl_body;
          }

          function getPhoneFilterOptions(){
            var opts = [];
            $checkboxes.each(function(){
              if(this.checked){
                opts.push(this.id);
              }
            });

            return opts;
          }

          function updatePhones(opts){
            $.ajax({
              type: "POST",
              url: "submit.php",
              dataType : 'json',
              cache: false,
              data: {filterOpts: opts},
              success: function(records){
                $('#phones tbody').html(makeTable(records));
              }
            });
          }

          var $checkboxes = $("input:checkbox");
          $checkboxes.on("change", function(){
            var opts = getPhoneFilterOptions();
            updatePhones(opts);
          });

          $checkboxes.trigger("change");
        </script> 
      </body> 
    </html>

submit.php

<?php 
require 'Database.php';
#### SET NAMES FOR UTF8 ###################################################
require_once('Json.php');

  $opts = $_POST['filterOpts'];
  foreach ($opts as &$opt) {
      $opt = sprintf("'%s'", mysql_real_escape_string($opt));
  }
  $query = sprintf(
      "SELECT mobile_phone.id, name, model, price
       FROM mobile_phone
       INNER JOIN brand ON brand_id = brand.id
       WHERE name IN (%s)",
      join(',', $opts)
  );

  $result = mysql_query($query);
  $data   = array();
  while ($row = mysql_fetch_assoc($result)) {
      $data[] = $row;
  }

  echo json_encode($data);
?>

Json enter link description here

Answer №1

The functions json_encode and json_decode are not available in PHP4. It is recommended to utilize a JSON manipulation library for PHP4.

Note: If you have included the Json.php file, remember that it does not contain the json_* functions. Instead, the Json.php file includes the Services_JSON class. Please refer to this example:

$jsonObj = new Services_JSON();
echo $jsonObj->encode($data);

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

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

Incorporating external API information into Google Maps

My current challenge involves creating a polygon on Google Maps using data obtained from an external API found at . Upon analyzing the API response, the following information is provided: { "id": 28, "name": "Local spots", "description": "", "isprivate": ...

Transferring an array between jQuery and PHP and vice versa

When users select categories from a list of project options, the div below should update to display projects that match those categories. However, despite following instructions from a similar Stack Overflow post on sending arrays with Ajax to PHP scripts, ...

Selecting JavaScript Libraries During the Development of a Web Application

Transitioning from PHP & Java/Android development to web app development can feel overwhelming, especially with the abundance of Javascript Frameworks available. Check out this comparison of popular JavaScript frameworks View a list of the top JavaSc ...

Can you fill a spinner on an Android device by using a JSONArray?

Is it feasible to accomplish this task? Assuming I have a JSON array structured like below: { "locations": [ { "id": 1, "loc": "miami" }, { "id": 2, "loc": "manhattan" }, { "id": ...

What are the reasons to steer clear of setting y.innerHTML equal to x.innerHTML?

If we have a DIV x on the webpage and want to duplicate its contents into another DIV y, we might be tempted to use the following code: y.innerHTML = x.innerHTML; This can also be achieved using jQuery: $(y).html( $(x).html() ); However, it is recommen ...

Exploring the functionalities of JSON and AJAX with a two-dimensional array

I have created a function to call JSON data, but it's not working. Any suggestions on how to properly call it? function fetchCompanyExpensesType(elementId){ $.ajax({ url: "../../modal/get_companyexpenses_type.php", dataType: ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

Send the user to the chosen option in the dropdown menu

My goal is to redirect the user based on the option they select. I am having an issue with my HTML code as it currently redirects to "example.com/page" instead of "example.com/page/1". Can someone please assist me in resolving this problem? <select clas ...

Issue encountered when attempting to utilize multiple datasets with Twitter Typeahead/Bloodhound

Hello, I am currently learning how to use Typeahead and Bloodhound with the latest javascript. Below is a snippet of my code: Html: <div id="multiple-datasets"> <input class="typeahead" type="text" placeholder="NBA and NHL teams"> </div ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

Utilizing `v-model` on a component that contains `<script setup>` in Nuxt can cause issues with the standard `<script>` tags

Working on a Nuxt3 project, I have implemented v-model on a component. Following the guidance from Vue documentation, here is how it should be done: In the parent component: <MyInput v-model="myData" placeholder="My placeholder" /&g ...

What is the best way to retrieve all the values from a JSON array?

At the moment, my access to data is limited to just the initial section of the array: [ { /*start*/ "username" : "Bob", "password":"123456", "bio":"Hi", /*End*/ "data": [ { ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

What is the best way to retrieve the following database results after clicking a button with Node.js?

Currently, my Node.js setup is successfully connected to my webpage and pulling data from a MySQL database. I have managed to display the first row of data as button values in the HTML code below. However, what I now want is for the user to be able to cl ...

Step-by-step guide on inserting a dictionary entry into a JSON file

In my current coding project, I am working towards formatting data in JSON and saving it to a file. The desired JSON format that I am aiming for is as follows: { "Name": "Anurag", "resetRecordedDate": false, "ED": { "Link": "google.com" ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

"Experiencing issues with Mongoimport when using JSON files - the provided JSON file seems

My attempt to import JSON data into MongoDB via a JSON file using the command below is resulting in an error: mongoimport --db my_db --collection m_data --type json --file /home/uname/email_my.json -v One of my key values contains a complete HTML with sp ...