Receiving Ajax Callback: extracting messages from PHP using JSON, then displaying them in a DIV element using JavaScript

As a complete beginner, I find JavaScript to be quite challenging and struggle with simple tasks.

I have a PHP script that retrieves data from a website using JS. This PHP script updates the database and returns a success message using the following code:

echo json_encode(array('success'=>'true'));

I've created a function that triggers actions when the "success" message is returned:

success: function(){
  ....
} 

Now I want to enhance it further. My PHP script will also return a message that should be displayed in a specific DIV.

The message could be something like:

"error-msg"=>"Could not write to DB." or "success-msg"=>"Data successfully saved in DB."

I'm unsure how to determine if the returned data is an "error-msg" or "success-msg." I don't know how to extract the message string and display it in the designated DIV.

Can anyone provide guidance on this issue?

Thank you!

Answer №1

Instead of opting for success_msg and error_msg, consider utilizing status_msg and status (within your PHP script).

status_msg will hold the text. status will carry "success" or "error". Alternatively, you can use any other marker you prefer.

To verify the message status in Javascript,

var response = JSON.parse(data);
console.log(response.status_msg); //show the message    
if(response.status == "success"){    
    //perform an action    
}    
else {    
    //perform another action    
}

Once the message is received, you can present it within a DIV using

document.getElementById("message").innerHTML = response.status_msg;

The structure of the HTML file would be as follows

<div id="message">
</div>

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

"Master the art of drag and drop in Dojo: Implementing a handler for the drop

My list is structured as follows: <div dojoType="dojo.dnd.Source" id="myList"> <div class="dojoDndItem">item 1</div> <div class="dojoDndItem">item 2</div> <div class="dojoDndItem">item 3</div> </div ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

What is the difference in memory usage for JavaScript objects between Node.js and Chrome?

It's puzzling to me why the size of the heap is twice as large as expected. I meticulously constructed a binary tree with perfection. I suspect v8 recognizes that each node consists of 3 fields. function buildTree(depth) { if (depth === 0) return n ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

Python Eve encountering WSGI issue [Errno 32] causing a broken pipe during an Ajax call

As I operate a simplistic wsgi server, from run import app if __name__ == "__main__": app.run(threaded=True, debug=True) When I send a get request to the server, it responds with a 200 message but no data. An error message is displayed: Error on r ...

Creating an API using a JSON file in Node.js

I am currently working on creating an API using Node.js with a JSON file. Initially, I set up a simple GET request in Node.js from the JSON file to filter out unnecessary data and build a new response based on the content of the JSON file. The code snipp ...

Tips for utilizing document.write() with a document rather than just plain text

Currently, I am utilizing socket.io to develop a party game that shares similarities with cards against humanity. My main concern is how to retain the players' names and scores without needing to transmit all the data to a new page whenever new games ...

Tips on moving information from one form to another after referencing the original page using Javascript and HTML

Imagine this scenario: A page with three text fields, each with default values. There is also a hyperlink that performs a database lookup and returns parameters to the same page where the hyperlink was clicked. The goal is for the text boxes to be automa ...

What is the proper way to use AJAX for sending data through a POST request?

Check out my Fiddle Currently, I am in the process of learning AJAX through a tutorial and so far, I have managed to retrieve the desired data and display it on the DOM quite effortlessly. However, I have encountered some difficulties when attempting to ...

The Ajax Success Function Failing to Execute as Expected

My dilemma lies in the fact that my Ajax Success Function is functioning incorrectly on one web page but properly on another. Isn't that frustrating? Both pages have identical code (copied and edited with different variables, of course). Functioning ...

Troubleshooting an issue with window.close in AngularJS

I'm struggling to properly execute the window.close function without encountering the error message below: Scripts may close only the windows that were opened by it. Here is the structure of my application: HTML: <html ng-app="mynewAPP" ng-co ...

Steps to invoke a function repeatedly for an animation

I found this code snippet while browsing a forum post about CSS animations. The question asked if it was possible to create a button that would restart the animation when clicked, even if it is in the middle of playing. They specifically requested no jQu ...

The Kendo UI grid encounters issues with pagination functionality after new data is inserted

I have implemented a Kendo UI grid in my AngularJS application for managing records, but I am facing an issue with pagination. Even though I have set the pageSize to 2, when I add a new record, it doesn't create a new page and instead shows the new re ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

PHP, having difficulty assigning value to variable using $_POST

Having a minor frustrating issue... I am transmitting a form value to PHP using AJAX, and it appears to be functioning properly. Upon performing var_dump in PHP, I can see my values and even set a variable and echo it correctly. However, this line $prod_i ...

Changing the position of x-axis labels in a Google Bar Chart to the top

I'm currently working with the Google Bar Chart and I'm trying to relocate the x-axis label to the top. I've tried writing the code, but so far it hasn't been successful. Could you please take a look at the fiddle and screen shot provid ...

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

The advantages and disadvantages of utilizing various methods to visually enhance HTML elements with JavaScript

After opening one of my web projects in IntelliJ, I noticed some JavaScript hints/errors that Netbeans did not detect. The error message was: > Assigned expression type string is not assignable to type CSSStyleDeclaration This error was related to thi ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Fixing the error "require() is not defined" when trying to call a function from JavaScript to Node.js

As I work on building my website, I discovered that Javascript lacks a built-in way to communicate with a database. Through my research, I came across node.js and decided to implement it. Here is a snippet of the code I've written: var mysql; var con; ...