Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
how to pass data to ajax for an express api call

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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());

about 4 years ago · Juan Pablo Isaza Denunciar

0

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"
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda