0

My backend JSON DB is running on http://localhost:3000/user and contains the following:

db.json

{
  "user": [
    {
      "id": 1,
      "name": "Stephen",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Ireland"
    },
    {
      "id": 2,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "England"
    },
    {
      "id": 3,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Wales"
    },
    {
      "id": 4,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Scotland"
    },
    {
      "id": 5,
      "name": "Simon",
      "profile": "[Unsplash URL Placeholder]",
      "team": "France"
    },
    {
      "id": 6,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Italy"
    },
    {
      "id": 7,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "USA"
    },
    {
      "id": 8,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "New Zealand"
    },
    {
      "id": 9,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Australia"
    },
    {
      "id": 10,
      "name": "Stephen",
      "profile": "[Unsplash URL Placeholder]",
      "team": "South Africa"
    },
    {
      "id": 11,
      "name": "Ted",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Fiji"
    },
    {
      "id": 12,
      "name": {},
      "profile": "[Unsplash URL Placeholder]",
      "team": "Chile"
    },
    {
      "id": 13,
      "name": {},
      "profile": "[Unsplash URL Placeholder]",
      "team": "Japan"
    },
    {
      "id": 14,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Namibia"
    },
    {
      "id": 15,
      "name": "[Available]",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Argentina"
    },
    {
      "id": 16,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Portugal"
    },
    {
      "id": 17,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Uruguay"
    },
    {
      "id": 18,
      "name": "Tony",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Tonga"
    },
    {
      "id": 19,
      "name": "",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Georgia"
    },
    {
      "id": 20,
      "name": "Simon",
      "profile": "[Unsplash URL Placeholder]",
      "team": "Samoa"
    }
  ]
}

In my JavaScript function, I want to send a HTTP GET request to the backend and filter the response to only show users which have an empty string in place of the name value. If true, I then want to send a PATCH request to update the JSON DB using the string which the user provided. If false, I want to alert the user. Here's what I currently have:

index.html

              <input class="appearance-none bg-transparent border-none w-full text-gray-700 mr-3 py-1 px-2 leading-tight focus:outline-none" id="name" type="text" placeholder="Jane Doe" aria-label="Full name" required>
              <button onclick="addNameTestTest()" type="submit" class="flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded" type="button">
                Sign Up
              </button>

index.js

function RandomNumber(min, max) {
    // Generate a random number between min (inclusive) and max (inclusive)
    //return Math.floor(Math.random()  (max - min + 1) + min);
    return Math.floor(Math.random() * 20) + 1;
}

function addNameTestTest() {
    var randomNumber = RandomNumber(1,20)
    var name = document.getElementById('name').value
    var test = $.ajax({
        url: "http://localhost:3000/user",
        method: "GET",
        dataType: 'JSON',
        success: function(res){
            console.log(res);
        }
    })
    var data = JSON.parse(test)
    var yourMatch = data.user.find(c => c.name === "")
    if (yourMatch == true){
        $.ajax({
            url: "http://localhost:3000/user/"+randomNumber+"",
            method: "PATCH",
            dataType: 'JSON',
            data: { 'name': name },
            success: function(name) {
                console.log(name);
            },
            error: function(xhr, status, error) {
                console.error('Error: ' + status + ' - ' + error);
            }

        })
    } else {
        alert("Error: The team which you were assigned has already been taken or else all teams have been allocated. Please refresh your browser and try again.");
    }
}

However, when I test this, I receive the following error: Uncaught SyntaxError: "[object Object]" is not valid JSON at JSON.parse

Error

Using jq and bash, I'd use the following to filter the data:

url="http://localhost:3000/user"
response=$(curl -X GET -H "Content-Type:application/json" $url)
responseTest=$(echo $response | jq '.[] | select(.name=="")')
echo $responseTest

If anyone could assist, that would be greatly appreciated.

1 Answers1

0

Your ajax call is async, and returns a promise object.

Something like this async/await approach should get you going in the right direction:

async function addNameTestTest() {
    ...
    var test = await $.ajax({
        url: "http://localhost:3000/user",
        method: "GET",
        dataType: 'JSON'      
    })
}

Your other approach is to put all your following code into the success callback. Javascript will not wait for the ajax call to resolve before moving on (by default), and that is your issue.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • Hi, as per your suggestions, I updated my function but now I'm receiving the following error: Uncaught SyntaxError: "undefined" is not valid JSON at JSON.parse (). Is there an alternative method to parse? – someguyhello Aug 20 '23 at 21:31
  • I suggest opening your debug panel and viewing in the network tab exactly what the backend returns – Steven Spungin Aug 20 '23 at 23:18