Issues may arise when attempting to parse AJAX responses using Javascript/JQuery AJAX

There are many posts on this topic, but I am having trouble finding the specific information I need. Here is where I am struggling:

I have an AJAX request for an ID and an integer (which will be used as a margin to apply on the DOM later).

This is the request I am making:

$(function(){
    $("#divAccordion").accordion({
    //Accordion options here, not relevant
    }).sortable({
    //Other sortable options here, not relevant
    //This is the important part:
        update:
            function(event, ui){
                var data = $(this).sortable('toArray');
                $.ajax({
                    url:"prc.php",
                    type:"POST",
                    dataType:'JSON',/*--Added this also--*/
                    data:{sort:data},
                    contentType : "application/x-www-form-urlencoded;charset=UTF-8"
                }).done(
                    function(margin){
                        console.log(margin);//This log [sebastien20140804130001:45, sebastien20140804130002:30]
                        for(key in margin){
                            console.log(key+"=>"+margin[key]);
                        }
                    }
                );
            }
    });
});

When I check the console, this is what I see:

[sebastien20140804130001:45, sebastien20140804130002:30]
0=>[
1=>s
2=>e
3=>b
4=>a
...

Do you see the issue? My response (margin) is being returned as a string, causing my loop to iterate through each character instead of key/value pairs as expected.

Instead, I would like the output to look something like this:

[sebastien20140804130001:45, sebastien20140804130002:30]
sebastien20140804130001=>45
sebastien20140804130002=>30

One challenge I face is not knowing how many 'key/value' pairs I will receive or if the IDs will be in numeric order ([ID:MARGIN_TO_APPLY]).

My goal is to loop through each 'key/value' pair and apply something like this:

$('#'+key).css('margin-left', value);

If you need any additional information, please let me know in the comments section.

Thank you!

--EDIT--

Below is the server-side code that handles the request:

echo '{';/*--was [--*/
sortRN('rn_GLOBAL', 0);
echo '}';/*was ]--*/

function sortRN($dep, $i)
{
    if(isset($_POST['sort'][$i]) && $_POST['sort'][$i] != '')
    {
        $cnSort = new cConnexion('***', '***', '***', '***');
        if($cnSort->DBConnexion())
        {
            $query = "UPDATE ***.reunion SET rn_DEP = :DEP WHERE REPLACE(REPLACE(REPLACE(CONCAT('rn_', rn_SAMAORG, rn_DTSTART), ' ', ''), ':', ''), '-', '') = :ID";

            while(isset($_POST['sort'][$i]) && preg_match('#^.+[0-9]{4}$#', $_POST['sort'][$i]))
            {
                if($i > 0)
                {
                    echo ',';/*--Added this so there wouldn't always be a coma at the end--*/
                }

                switch($dep)
                {
                    case 'rn_GLOBAL':
                        $params = array('DEP'=>str_replace('rn_', '', $dep), 'ID'=>$_POST['sort'][$i]);

                        $rsSort = $cnSort->SecureExecute($query, $params);
                        if($rsSort)
                        {
                            echo '{"'.$_POST['sort'][$i].'":15}';/*--Changed every line like this to add {} and also removed the coma at the end--*/
                        }
                    break;

                  /* More cases follow... */

            }
            $i++;
        }

        $cnSort->DBDeconnexion();
        if(isset($_POST['sort'][$i]) && $_POST['sort'][$i] != '')
        {
            $ii = $i + 1;
            sortRN($_POST['sort'][$i], $ii);
        }
    }
    else
    {
        echo $cnSort->m_log->getMessageFR();
    }
}
}

A side note: The PHP script updates the database with the position of the jQuery sortable items and then echoes the element ID along with its corresponding margin value.

--EDIT2--

I've made some changes to the code, highlighted above.

Answer №1

  1. The data returned is not in valid JSON format according to the specifications outlined at http://json.org/. Instead of an array of elements, each element should be a properly structured object, like so:

    [{"sebastien20140804130001" : 45}, {"sebastien20140804130002": 30}]

  2. Upon receiving the response, you must either use JSON.parse(response) to convert it into a JSON object or configure your request with dataType: 'json' in jQuery to automatically handle the conversion.

Answer №2

This may not be the recommended approach, as it is best to structure your data properly in valid JSON following Rajkumar Madhuram's advice. However, for the sake of practice and learning about regular expressions, we can attempt the following solution:

function(parseMargin){
    var values = parseMargin.match(/(\w+:\d+)+/);
    var keyValues = [];
    for (var index=0 ; index< values.length; index++) {
        var keyValue = values[index].split(":");
        keyValues.push({ key: keyValue[0], value: keyValue[1] });
    }
    // At this point, you will have an array containing key-value pairs.
}

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

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

What steps can be taken to convert a list box into an editable box?

I created a listbox using a table because I needed to display two columns for the list. Now, I am attempting to enable editing the text directly within the table when I select an item from the listbox. Essentially, I want the selected item to become an edi ...

What is the best way to eliminate products that have already been utilized?

Take a look at my code snippet. $(function() { $("#tags input").on({ focusout: function() { var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // only allow certain characters if (txt) $("<span/& ...

Responsive HTML grid with a distinct line separating each row

My challenge is to create a layout that features a grid of floating divs with horizontal lines under intermediate rows. The catch is that there should not be a line under the last row, and if there is only one row of elements, no line should be displayed. ...

Scroll bar for multiple selection select tag without using div element (not supported in firefox)

.selector select[multiple="multiple"] { border-radius: 0; height: 200px; margin: 0 0 0 -1px; max-width: 368px !important; padding-left: 3px; width: 368px !important; } <select id="id_included_packages_from" class="filtered" multiple="multipl ...

Ways to verify form data for accuracy of responses

Here's what I have: Index.php: <?php include "phpscripts/databaseconn.php"; $conn = new mysqli('127.0.0.1', 'root', '', 'lidl'); if($conn->connect_error) { die('Could not connect: ' . mysql ...

Set the first link in a menu to be highlighted as active using jquery

In order to mark the first link in my menu as active, I need it to have specific CSS settings applied. Using jQuery to add these settings to every link when clicked on makes it a bit tricky (simple menu = clicking changes color). So, I want the first link ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

Issue with Div Element Not Expanding When Populated

I am facing an issue with a stack of nested divs, each having a specific ID for CSS styling. However, the outermost DIV tag is only expanding to a predetermined height value instead of automatically adjusting to fit its contents. This is a problem because ...

Solution for resolving AMP Error related to the Imply script tag within a nextjs application

Tag located outside the document head, which should only be a direct child of the document head. Error: Invalid attribute: data-amp-bind Fix: Make sure you are using only allowed attributes for AMP components. If you are using custom attributes, they sho ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Dynamically change the fill color of an SVG using styled-components

I've been attempting to target the fill property of my SVG using CSS in styled-components without any luck. Here is my SVG: <svg width="65" height="19" viewBox="0 0 65 19" fill="none" xmlns="http://www. ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

Animation displayed on page load before running

Is there a way to ensure that my animation runs smoothly without any lag or jankiness, either while the page is loading or immediately after loading? I have attempted to preload the images using a preload tag in the header of my HTML, but unfortunately, t ...

Is it possible to horizontally center an auto-fill grid using only CSS?

I would like to fill my page horizontally with as many blocks as possible and center the result. My goal is to have a grid that can resize when the window size changes: wide window xxx small window xx x Is it possible to achieve this without using Java ...

Exploring the blur() function in JavaScript through cold calling

There is a specific line of code that I need help with. document.getElementById("firstName").addEventListener("blur", validateField); Additionally, there is this block of code: validateField = (event) => { const el = event.targe ...

Creating interactive functionality for textareas and input fields in Vue: A beginner's guide

I need assistance with creating a function where changing the input field will also automatically update the textarea's value. I have successfully implemented Vue js for updating the input field based on the textarea, but I am struggling to reverse th ...

When submitting information through AJAX in ASP.NET MVC, the data turns out to be empty

Issues with MVC controller debugging: eventDetails properties are null despite having values on the client side Ajax Call $.ajax({ type: "POST", url: "/Home/schedule", data: { EventDetailsId: 1, Location: schedule ...