Home > Net >  how to pass data to ajax for an express api call
how to pass data to ajax for an express api call

Time:10-13

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.

    const parsedData = JSON.parse(localStorage.getItem('myData'));
    
   
    const container = document.getElementById('s1');
 
    parsedData.data.rows.forEach((result, idx) => {
      
     var a = result.master_id;
     var b = result.session_name;
     console.log(a,b,"a","b")
     
   
    var userData = {"pid":a,"session" :b};
     console.log(userData,"userData");
    sessionStorage.setItem("user", JSON.stringify(userData));
    console.log(userData,"data for api");

     const card = document.createElement('div');
     card.classList = 'card';

  
  const content = `
  <div class="row">
      <div class="card-body"  onclick="graphApi()">
  </div>
  </div>


  `;


  container.innerHTML  = content;
});

function graphApi(){
       
      var apiValue =JSON.parse( sessionStorage.getItem("user"));
       console.log(apiValue, "value from card");
       

        $.ajax({
        type: "POST",
        data:  apiValue,
        dataType:"json",
        
        url: "http://localhost:5000/graphFromcsv",                      
        success: function(data) {
        console.log(data,"graph api");
}
  error: function(err){
          alert("graph api failed to load");
          console.log(err);
        },
});

i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,

{
    "pid":"WE6",
    "session":"W.csv"
}

instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.

CodePudding user response:

You need to correct data key and their value(value must be string in case of json data) and also add contentType key like

$.ajax({
    type: "POST",
    data: sessionStorage.getItem("user") || '{}',
    dataType: "json",
    contentType: "application/json",
    url: "http://localhost:5000/graphFromcsv",
    success: function (data) {
        console.log(data, "graph api");
    },
    error: function (err) {
        alert("graph api failed to load");
        console.log(err);
    },
});

Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());

CodePudding user response:

Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:

  body: {
    apiValue: {
      "pid":"WE6",
      "session":"W.csv"
    }
  }

But if you use the link to the object like body: apiValue (without brackets) js will build it like:

body: {
  "pid":"WE6",
  "session":"W.csv"
}
  • Related