Leia_Organa
Leia_Organa

Reputation: 2094

Making a POST request to an API in JavaScript/jQuery

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?

Upvotes: 0

Views: 68

Answers (3)

James Garcia
James Garcia

Reputation: 186

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")
  });
}

Upvotes: 1

Vlatko Vlahek
Vlatko Vlahek

Reputation: 1889

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"
});

Upvotes: 3

ogastonc
ogastonc

Reputation: 34

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

Upvotes: 1

Related Questions