0

I've been trying to get a POST request from an API, and I'm not having that much luck in pushing it through. I'm wondering if it's because one of the parameters I'm passing is an array of objects. Been trying to get this to work for a few hours with no luck.

This post function requires two parameters, userId and classId.

//here's the api I'm calling, obviously not the actual URL

let apisource = www.exampleapi.com

//this is the class

let classId = 12345;

//these are students in the class

let userArray = [{
  "name": "user1",
  "userId": 101
}, {
  "name": "user2",
  "userId": 102
}]

I'm writing a function that takes this userArray and matches it up to a class that contains the userIds.

Here's my API call so far:

function getStudents(classId, userArray) {
  $.post(apisource) + "classes"), {
    userId: userArray.userId,
    classId: classId
  }, function(data, status) {
    console.log("students in class loaded)
  }
}

Nothing ever loads. Anyone have any suggestions or pointers for something I might be doing wrong?

8
  • 1
    Did you use the DevTools of your browser to see if there's an error and if the request is sent at all? This would be important to know Commented Mar 12, 2019 at 23:47
  • The request isn't even going through. I think I'm missing something or maybe I've written something incorrectly. Commented Mar 12, 2019 at 23:48
  • Where do you call the getStudents function? Commented Mar 12, 2019 at 23:50
  • 2
    I think you should move the ) after apisource to the end of your function Commented Mar 12, 2019 at 23:54
  • 1
    1. The code has syntax errors 2. requesting something from another domain requires the URL starting with http:// 3. it also requires support for CORS requests Commented Mar 13, 2019 at 0:41

3 Answers 3

3

There are a few issues here.

For example:

userArray.userId

This part of the code is definitively invalid. Arrays have indexes, not keys like objects, for example. This means you cannot access the userId param, as you haven't defined in which index it is.

Considering your array has two items:

let userArray = [
  { name: 'user1', userId: 101 }, // index 0
  { name: 'user2', userId: 102 } // index 1
];

You would need to access the user id in the following fashion:

userArray[0].userId // Returns 101
userArray[1].userId // Returns 102

As for the request itself, it could look like something like this:

let apisource = www.exampleapi.com;
let classId = 12345;
$.ajax({  
   type: 'POST',
   url:  apisource,
   data: JSON.stringify({ userId: userArray[0].userId, classId: classId }),
   contentType: "application/json"
});
Sign up to request clarification or add additional context in comments.

1 Comment

if you're going to post JSON, you need to set the content-type
1

Fist of all, you cant access to userId property of the userArray, you need to pick the object first like "userArray[0].userId" or any logic to get one element.

In other hand, i recommed you to use the fetch function, is easier to use and the code look more clean with promise.

var apisource = 'https://example.com/';
var data = {}; // the user picked

fetch(apisource , {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

source: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

6 Comments

I'd move your catch to the end, otherwise it will transform the rejected promise into a resolved one
Not really, i agree with you moving the catch to the end, but not for that reason, the the catch will execute just when the Promise really get rejected, no matter the order. source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
That's not correct. If the promise chain is rejected at the fetch() or res.json() stage, the catch will catch that rejection, log the error and then because it doesn't throw another error or return a rejected promise, your last then will execute as if everything is fine
Here's a little JSFiddle demo for you. Try swapping the catch to the end and you'll see the difference
oh you're right, this is really kinda weird behavior. But thanks for the info Phils. - cheers.
|
1

It looks like you need to refactor your post implementation this way to avoid some syntax errors.

function getStudents(classId, userArray) {
  $.post( apisource + "classes", { 
    userId: userArray.userId,
    classId: classId 
  })
  .done(function( data, status ) {
    console.log("students in class loaded")
  });
}

1 Comment

Thanks, this helped a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.