PHP variables not being properly passed back to AJAX/jQuery POST on success despite using json_encode()

I've been grappling with this issue for hours. I am attempting to make a <div id=""data_friends> and a hidden input field update dynamically using AJAX. Here is the structure of the div tag:

<div class="friends-tab-list" id="data_friends">

    <?php 
    //Default query limits results to 8

    $sql = ("SELECT * FROM users WHERE FIND_IN_SET(?, friend_array) > 0 LIMIT 0,8");
    $query = mysqli_prepare($con, $sql);
    $query->bind_param('s', $username);
    $query->execute();

    $result = $query->get_result();

    $num_rows = $result->num_rows;

        while ($row = $result->fetch_assoc()) {
        $row['profile_pic']; 
        $row['username'];

        echo "<a class='profile-img-item' href='" . $row['username'] . "'>
              <img src='" . $row['profile_pic'] . "' title='" . $row['username'] . "'>
              </a>";
                }
        $query->close();

          ?>
</div>

The hidden input field looks like this:

<input id='max' type='hidden' value='<?php echo $num_rows; ?>'>

Upon clicking the View More Friends button, data is sent to

includes/handlers/ajax_load_profile_friends.php
through AJAX as shown below:

$.ajax({

    url:'includes/handlers/ajax_load_profile_friends.php',
    type:'POST',
    dataType: 'json',
    data:{'username':username, 'num_friends':num_friends, 'counter':counter},

        success: function(data) {
            $('#data_friends').html(data.html);
            $('#max').val(data.num_rows);
                }
        });

The output from ajax_load_profile_friends.php appears as follows:

$query = mysqli_prepare($con,"SELECT * FROM users WHERE FIND_IN_SET(?, friend_array) LIMIT $counter"); 
$query->bind_param('s', $username);
$query->execute();

$result = $query->get_result();

$num_rows = $result->num_rows;
}       

while ($row = $result->fetch_assoc()) {
$row['profile_pic']; 
$row['username'];

$html = "<a class='profile-img-item' href='" . $row['username'] . "'>
          <img src='" . $row['profile_pic'] . "' title='" . $row['username'] . "'>
         </a>";

}   

echo json_encode(array('num_rows' => $num_rows, 'html' => $html));

After execution, only one result displays instead of the expected 16 records per click. I assume that updating the hidden input field's value should occur using $('#max').val(data.num_rows);

The content within the hidden input field

<input id='max' type='hidden' value='<?php echo $num_rows; ?>'>
fails to update when implementing $('#max').val(data.num_rows);

It seems there might be an oversight in ajax_load_profile_friends.php causing these anomalies. When excluding json_encode() and utilizing the success function as such

$('#data_friends').html(data.html);
along with removing dataType: 'json', from AJAX, functionality resumes but without ability to update the hidden input value. The goal is correcting this method due to most examples favoring json_encode().

Answer №1

header( "Content-Type: application/json", TRUE );
$query = mysqli_prepare($con,"SELECT * FROM users WHERE FIND_IN_SET(?, friend_array) LIMIT $counter"); 
$query->bind_param('s', $username);
$query->execute();

$result = $query->get_result();

$num_rows = $result->num_rows;

$html='';

while ($row = $result->fetch_assoc()) {


$html .= "<a class='profile-img-item' href='" . $row['username'] . "'>
          <img src='" . $row['profile_pic'] . "' title='" . $row['username'] . "'>
         </a>";

}   

echo json_encode(array('num_rows' => $num_rows, 'html' => $html));

Answer №2

Make sure to define the $html variable before entering the while loop. Check out this code snippet for reference:

<?php

$query = mysqli_prepare($con,"SELECT * FROM users WHERE FIND_IN_SET(?, friend_array) LIMIT $counter"); 
$query->bind_param('s', $username);
$query->execute();

$result = $query->get_result();

$num_rows = $result->num_rows;
}       
$html = '';
while ($row = $result->fetch_assoc()) {
// $row['profile_pic']; 
// $row['username'];

$html .= "<a class='profile-img-item' href='" . $row['username'] . "'>
          <img src='" . $row['profile_pic'] . "' title='" . $row['username'] . "'>
         </a>";

}   

echo json_encode(array('num_rows' => $num_rows, 'html' => $html));

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

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

What is the best way to create a Laravel object for use in JavaScript in a Laravel Blade?

please add description hereI am looking to obtain an object with this particular style var zoz2= { "11-30--0001": "<a href=\"https:\/\/www.dooz.ps\/p\/107229\" >\u0625\u0637\u0644\u0627& ...

What are the steps to perform an Ajax request to an online web service?

I would like to send an AJAX request to an external web service using jQuery. However, I am encountering an error and unable to receive a successful response from the server. var url = "http://www.example.com/api/convert"; var requestData = { temperat ...

When attempting to make a GET request with vanilla JS to an express server, the response is coming back empty

I am trying to establish a request using the GET method to retrieve data in JSON format through AJAX. The route for this request is quite simple: app.get('/', function(req, res) { res.json({ answer: 42}) }); After opening / in the browser, ...

Adding options to an HTML select dropdown menu using data stored in an array

Having reviewed several questions related to this issue, I am still encountering difficulties. Below is the code snippet that I am struggling with: <body> <?php //To begin, there is a form with a drop-down menu and a button, which will trigge ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

Is there a way in jqGrid to invoke a function once the subGridRowCollapsed operation finishes?

I'm currently working with jqGrid's subgrids and I need a solution for invoking a specific method after collapsing a subgrid. Currently, my implementation is as follows: subGridRowCollapsed: function (subgrid_id, row_id) { adjust_slider_posi ...

Merge multiple echoes to create a single echoed string that is valid HTML

<?php // link to Google Docs spreadsheet $url='https://docs.google.com/spreadsheets/d/1_4d-MPxTUOVZbxTOlhjXv1ebTlBPQ-_JrYUlS1rqX5Q/pub?output=csv'; // open file for reading if (($handle = fopen($url, "r")) !== FALSE) { while (($data = fge ...

How can you show several copies of an image on an HTML page?

I am trying to show an image multiple times in a row using a combination of HTML, PHP, and CSS. Here is my code snippet: for ($i=20; $i<=320; $i=$i+300) { echo "<style> " . ".test{" . "position: absolute; left: " . $i . ...

What is preventing me from connecting to the BoM FTP server using PHP?

I'm facing difficulties in transferring an XML file from the Bureau of Meteorology (Australian) Public Access Data Feeds to my server using PHP. Despite being able to access the file through a browser, I am unable to interact with it using PHP through ...

Ajax is struggling to achieve any positive outcomes

I recently started exploring ajax and I'm having trouble figuring out what's causing the issue with the code? page.html <html> <head> <title>Ajax request</title> <script src="https://cdnjs.cloudflare.com/ajax/ ...

Function in controller making an Ajax request

As a beginner in AngularJS, I am looking to implement a controller with a save function that makes an ajax call. This is how my current code looks: var app = angular.module("myApp1", []); app.controller("AddController", ['$scope', $http { ...

Choose a punctuation mark using jQuery

I have a clock from W3Schools that I am working on here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock My goal is to make the ":" in the clock flicker, toggling between visible and hidden. I believe I need to select the ":" using jQuer ...

How does Angular5 perform with Bootstrap4?

Currently working on an Angular5 application and considering integrating bootstrap into it. I imported Bootstrap4, which includes dependencies on JQuery and Popper.js. Another option I came across is utilizing CSS grid for more versatility compared to boo ...

Steps to troubleshoot and resolve a bug that occurs after installing a module onto Magento 2

Upon installing the module "M2E Pro Amazon & eBay Integration", I encountered the following issue: composer require m2epro/magento2-extension:dev-master php bin/magento setup:upgrade An exception was thrown: [zzbusyco@nwpro5 public_html]S php bin/magent ...

Obtaining Values from Identical jQuery Buttons with the Same Class名称

I am facing an issue with my PHP script that generates buttons for each content schedule. The script outputs multiple HTML buttons with the same name, class, and ID, but their values are dynamically set based on a variable. In my jQuery code, I have selec ...

Sending data from the client side using AJAX and PHP to the server

Struggling with using AJAX to send values over to a PHP file for updating a MySQL database on the server. However, I've encountered an issue where the values don't seem to be properly transferred to the PHP file. This is the JavaScript code I am ...

Populating a Dual ListBox with JSON data

I'm currently using a dual listbox control from and am attempting to populate it with information retrieved from a JSON request. Initially, I populated the Duallistbox using a VB sub like this: Public Shared Sub GenerateDropDownListAndValues(dt As ...

Updating the jQuery datatable with new data after a page switch or another action

One of the features on my page is a jQuery datatable that I populate with data using the following script: $(document).ready(function () { var dataTable; $(document).on("click", ".myBtnClass", function () { if (dataTable != null) ...

Utilize an Ajax function to call the BOT listening URL within a Web method

My recently developed web application features a submit button that triggers an Ajax call to communicate with the BOT. The code snippet used for the Ajax function is as follows: <script> $(document).ready(function () { $("#btnSend& ...