Break down the errors in the JSON response for each field

Previously, I was using AJAX post with the normal dataType 'html'. However, I have now switched to using dataType 'json'.

Before implementing json, I used to split response errors and display them next to the input fields using spans.

This is the old AJAX success code for splitting errors when using 'html' as the data type:

    success:
           function(data){

  var data_array = split('*');
                 for(var i=0; i<data_array.length-1; i++)
                 {
                    messgae_array = data_array[i].split(':');
                    $("#"+messgae_array[0]+"_error").html(messgae_array[1]);
                    $("#"+messgae_array[0]).css({"border":"1px solid red"});
                 }

}

This is an example of an input field in the form:

<input type="text" id="uname" name="uname" value="" class="inplaceError" />
<span id="uname_error"></span>

I have more inputs but have just shown an example of how they look.

For each input, there is a corresponding span element holding the errors from the AJAX response.

Now, the challenge lies in updating the code that previously worked with HTML responses to work with JSON responses. As someone new to JavaScript/AJAX/JSON, I am unsure of how to modify the split code to handle JSON responses. Any assistance would be greatly appreciated.

Edit:

The error messages are generated like this:

   if(isset($_POST['p']) && !empty($_POST['p']))
    {
        if($password == $retype)
            {
            $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
        // Create salted password (Careful with the chilli)
        $password = hash('sha512', $password.$random_salt);

        }
        else
        {
          $message['password']='&nbsp;password not match';
        }

and so on .

  $message['email']='&nbsp;wrong email';

And here is the foreach loop generating JSON array for the errors:

  foreach($message as $key => $val) {


          $return = array('error' => $key, 'message' => $val );
         echo json_encode($return);

           }

Something appears to be incorrect in the foreach loop for the errors, resulting in incorrect handling in the AJAX response code. Any insights on what might be going wrong?

Answer №1

There is no need to manually split strings in your data when working with JSON. By ensuring it is in the correct format, you can easily access the information using object notation or array notation:

var json = '{
  "someVar":true,
  "error":"my fatal error message"
}';

var obj = JSON.parse(json);

alert(obj.error);

The purpose of JSON is to simplify data access and usage. If you find yourself still splitting strings to extract data from JSON, then there may be a more efficient way to handle it.

UPDATE: Consider utilizing nested JSON structures if you want to better categorize and manage your messages.

var json = "errors": [{
        "id": "001",
        "field": "textfield1",
        "message": "message1."
    },
    {
        "id": "002",
        "field": "textfield2",
        "message": "message2."
    }];

    var obj = JSON.parse(json);

You can now easily customize the appearance of these fields and show the messages:

foreach(obj.errors as err) {
  $("#"+err.field).html(err.message);
  $("#"+err.field).css({"border":"1px solid red"});
}

Answer №2

function handleResponse(response)
        {
          // Let's assume the response data is in the format of a JSON string like this
          // var response= [{"error":"username","message":"&nbsp;incorrect password."},{"error":"email","message":"&nbsp;incorrect name"}];
          // Instead of splitting the data with "*", parse it as JSON

          // Update your JSON parser to this method
          let dataArray = JSON.parse(response);
          for (let item in dataArray )
          {
             $("#"+dataArray[item].error+"_error").html(dataArray[item].message);
             $("#"+dataArray[item].error).css({"border":"1px solid red"});
          }    
}

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

Breaking down arrays in Typescript

Let's say I have an array like this: public taskListCustom: any=[ {title: 'Task 1', status: 'done'}, {title: 'Task 2', status: 'done'}, {title: 'Task 3', status: 'done'}, {title: 'Task ...

Unable to interpret JSON array

Having a Jquery problem that's giving me trouble with finding a clear solution. $( document ).ready(function() { handleJson(); }); function handleJson(){ $.getJSON("fileList.json", function(json) { $. ...

Dynamically loading a webpage with an element roster

I have a list and I want it so that when a user clicks on the sport1 list item, results from the database table sport1 will be displayed. Similarly, if they click on the education1 list item, results from the education1 table should be shown. The issue i ...

Developing a personalized Django widget featuring hints for "suggestions" derived from the validation process

I currently have a simple model setup: class MyModel(models.Model): my_field = models.CharField() Additionally, I have created a basic form for this model: class MyFrom(forms.ModelForm): class Meta: model = MyModel Furthermore, I have i ...

POST data not being sent via AJAX

I am trying to use AJAX to submit form data to a PHP function, but it seems like the data is not being transmitted. Here is the code for the HTML Form: <form onSubmit="return registration();" id="registration_form"> <input type="email" id="e ...

What is the process of transforming a list of JSON objects into a list of POJO strings that includes specific fields from each object?

I am working with a JSON document that describes a list of objects, and the structure looks like this: [ { "txId": "ffff", "sender" : "0xwwwwwww", "recepient" : "0xeferfef" }, { "txId": "ffff", "sender" : "0xwwwwwww", ...

Passing values dynamically to a JavaScript function within a Chrome extension using Python at runtime

I have encountered a unique challenge in my automation work, which I detailed in this query It's important to note that I am utilizing Python with Selenium WebDriver As I navigate through a series of changes and obstacles, I find myself exploring th ...

Manipulate a nested array in MongoDB with JavaScript array functions

Having trouble updating a field with mixed types in my mongoose schema. Although I acknowledge this may not be the ideal schema setup, there are specific reasons why it's structured this way. My goal is to perform array-like operations using JavaScrip ...

Unable to save data to file: ENOENT error - file not found

I'm currently working on creating a folder named "build" that will house numerous map files and JavaScript files. However, I've encountered the following issue. Snippet of the code: "scripts": { "prestart": "d2-manifest package.json manifes ...

JavaScript scope: retrieving variable information

Even though this question has been asked multiple times in various ways, I am looking to extract the value of the selected variable in another part of the highest-level function (the alert function currently returns undefined). I understand that I need t ...

Tips on extracting code differences from code inspector

Utilizing the Chrome code inspector is extremely valuable, but I often find it challenging to track the modifications made to CSS and HTML live. This becomes particularly cumbersome when there are multiple tags being modified. Are there any Chromium exten ...

Ways to display a different landing page when navigating to the homepage of a website

In the Next application, I have set up a dynamic route at the root of my pages folder as src/pages/[page].js While this works smoothly for pages with slugs like example.com/my-page, it poses a challenge when trying to access a designated slug named homepa ...

Save and showcase SQL, PHP, HTML, and JS code exactly as it is preserved in MYSQL database

Is there a way to store and display complete JS, PHP, and HTML code in MySQL without altering the format? The stored PHP code should appear as: <?php echo "something"; ?> And not just: something For JavaScript: <script> document.write(&ap ...

Incorporating an NPM JavaScript library into Laravel version 8

I've integrated the mobiscroll javascript component library into my new Laravel 8 app by adding the minified css/js files to the public/css and public/js directories. However, I'd like to find a more seamless way to include these components by us ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Difficulty surfaced in the React project following relocation to a different device

I'm new to using React and webpack with babel loader in my app. My project was running smoothly until I changed machines. I copied all the files except for node_modules (which I installed with npm install). Now, when I try to run or build the projec ...

A method of binding data from an array of objects in Vue using v-bind

I am tasked with rendering a board that is 20x15 and placing creatures on it. The information on where to place the creatures is stored in this.creaturesOnBoard within the gameEngine. My plan is to take X and y coordinates, then check if a creature exists ...

The JavaScript code snippets are ineffective, yielding an error message of "resource failed to load."

<? echo '<html> <script language=javascript> function validate() { alert("validate"); document.form1.action="validate.php"; document.form1.submit(); return false; } function del() { alert("delete"); document.form ...

Develop React routes on the fly

Currently, I am working on a React App that requires the creation of Routes dynamically based on data models sent by the backend in JSON format. For example: { "Route1": [ { "id": 1, "visible": true, "other_data": "..." } ], "Route3": [ { "i ...

Load data into Datatable using an Ajax request

I am trying to populate a table with values using an AJAX call. Here is the code snippet: initTable(); function initTable (){ return $('#exEmpListTable').dataTable({ "bPaginate": false, "sScrollY": "200px", "bScrollC ...