Guide on dividing and presenting ajax information into two separate div containers

I am attempting to showcase two sets of data on separate divs using ajax.

Below is the code I am utilizing for this task.

Here is the ajax implementation

   $(function () {
    $(".myBtn").click(function () {
        var id = $(this).data("id");
        var name = $(this).data("name");
        var dataString = 'id=' + id + '&list_id=' + <? php echo $id; ?>;
        var parent = $(this);

        if (name == 'up') {
            $(this).fadeIn(200).html;
            $.ajax({
                type: "POST",
                url: "vote_up.php",
                data: dataString,
                cache: false,
                dataType: 'json',
                success: function (json) {
                    parent.parent().find(".v-up").html(json.msg1);
                    parent.parent().find(".v-down").html(json.msg2);
                }
            });
        } else {
            $(this).fadeIn(200).html;
            $.ajax({
                type: "POST",
                url: "vote_down.php",
                data: dataString,
                cache: false,

                dataType: 'json',
                success: function (json) {
                    parent.parent().find(".v-down").html(json.msg2);
                    parent.parent().find(".v-up").html(json.msg1);
                }
            });
        }
        return false;
    });
});

This is the json response code

echo json_encode(array('msg1'=>$value1));
return;

echo json_encode(array('msg1'=>$value2));
return;

The code does not seem to be functioning correctly. It displays msg1 but fails to show msg2. Can anyone guide me on how to rectify this issue or point out what I might be doing wrong?

Answer №1

Based on the limited PHP code provided, it seems like you should use the following instead:

echo json_encode(array('message1'=>$value1, 'message2'=>$value2));
return;

This means that when you attempt to access the values as shown below:

success: function (json) {
    parent.parent().find(".some-class").html(json.message2);
    parent.parent().find(".another-class").html(json.message1);
}

The values will be displayed accordingly.

Answer №2

Combine both JSON strings into one and separate them in the script. Also, ensure that only the JSON string is outputted, nothing more. For example, like this: //PHP

$array = array("msg1"=>$value1, "msg2"=>$value2);
$toJSON = json_encode($array);
echo $toJSON;
die(); // To prevent additional output after this JSON string

//JS

[...]
success: function (json) {
                    parent.parent().find(".v-down").html(json.msg2);
                    parent.parent().find(".v-up").html(json.msg1);
                }
[...]

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

Retrieving information from database with the help of PHP and AJAX

I am having trouble printing data from a PHP and Ajax request that is initially encoded into JSON. Instead of displaying the data properly on the screen, it is showing elements from four rows all in a single line with commas separating them. $(document ...

Bootstrap 4 Card Body Spinner Overlay with Flex Alignment

Seeking to center a spinner both vertically and horizontally within a bootstrap 4 card body. Despite trying my-auto, justify-content-center & align-items-center, it seems like I'm missing something. I've double-checked the display types and ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

When utilizing KineticJS on a canvas that has been rotated with css3, the functionality of the events appears to be malfunctioning

Currently, I'm working on a rotating pie-chart widget using Kineticjs. However, I have run into an issue where the events don't seem to function correctly when drawing on a rotated canvas element (with the parent node being rotated 60deg using CS ...

PHP MySQL Table with a Date Range Filter

As someone who is new to PHP, I have a question. How can I set up a date range filter? I've looked at tutorials, but they haven't worked for me. I do have some code, but it doesn't include any functions. I want to implement this in a CRUD t ...

Achieving secure HTTPS connection with socket.io

At the moment, my setup involves: let connectTo = "http://myip:myport"; var socket = io.connect(connectTo, {secure: true}); on the client side and const port = myport; const io = require('socket.io')(port); on the server side. I am looking to ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...

install jquery package via npm and save it as a dependency

Currently using Ubuntu 16.04 Proxy settings are configured in ~/.npmrc, here is the setup: registry="http://registry.npmjs.org/" proxy="http://username:password@proxyconfig:port" strict-ssl=false http-proxy="http://username:password@proxyconfig:port" ht ...

Trigger function in React after the page finishes loading

I have a scenario where I need to display images onDrop within one of my components. To ensure a smooth drop experience, I am considering preloading the images using the following approach: componentDidMount(){ this.props.photos.forEach(picture => ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...

Is the Ajax component updating before the actionListener is activated?

My current setup involves using PrimeFaces <p:dialog> to open a popup HTML page and a <p:commandButton> to close it: When the Ok button is pressed, this is what happens: <p:commandButton id="submitButton" value="OK" actionList ...

How about I visit the campgrounds/edit page for a change?

In this get route, the previous link it was redirected from is stored in the req.session object under returnTo. Once redirected, it goes to the /login and we are able to view the object in the console. router.get('/login', (req, res) => { ...

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

Ajax script causes error 403 when loading content while scrolling

Currently in the process of creating a blog using the HubSpot platform. The primary goal is to have blog posts load dynamically as users scroll down the page. I came across a script that claims to achieve this functionality and is designed specifically for ...

What is the best way to utilize Ajax and Jquery in order to retrieve data from a PHP database and dynamically update elements with the fetched information?

I am currently enhancing a website to simplify the process for employees when editing products. At present, in order to change prices, someone has to log in to the database and manually alter them, followed by making adjustments to the HTML of the website ...