dina saber
dina saber

Reputation: 103

passing json array to ajax call in Javascript

guys i know its dummy questions but i spent hours on this and cant reach .. I am trying to pass a JSON array to JSP via an AJAX call in another JS file. It is giving me a 404 error. Any help would be appreciated. Here is my code:

function GridLibrary(fileName) {
    this.fileName = fileName;
}

GridLibrary.prototype = {
    setFileName : function(fileName) {
        this.fileName = fileName;
    },
    getFileName : function() {
        return this.fileName;
    }
};

GridLibrary.prototype.display = function() {
    $.ajax({
        url : this.getFileName(),
        dataType: "json",
        error : function(that, e) {
            console.log(e);
        },
        success : function(data) {
            alert("found");
        }
    });
};
var Json = [{
    "id": 1,
    "name": "name1",
    "age" : 10,
    "feedback": "feedback1"
}, {
    "id": 2,
    "name": "name2",
    "age" : 90,
    "feedback": "feedback2"
}, {
    "id": 3,
    "name": "name3",
    "age" : 30,
    "feedback": "feedback3"
}, {
    "id": 4,
    "name": "name4",
    "age" : 50,
    "feedback": "feedback4"
}];

new GridLibrary(Json).display();

Upvotes: 1

Views: 1129

Answers (1)

Jai
Jai

Reputation: 74738

You need to have a valid url to send the values to the backend:

function GridLibrary(url, data) {
  this.url = url;
  this.data = data;
}

GridLibrary.prototype = {
  setData: function(data) {
    this.data = data;
  },
  getData: function() {
    return this.data;
  },
  setUrl:function(url){ this.url = url; },
  getUrl:function(){ return this.url; },

  display : function() {
    $.ajax({
      url: this.getUrl, // <----the url where you want to send the data
      data:this.getData, //<----should be the array data
      dataType: "json",
      contentType:"application/json", // <----add this contentType
      error: function(that, e) {
        console.log(e);
      },
      success: function(data) {
        alert("found");
      }
    });
  }
};

var url = '/url/to/send',
    data = [{}....];

new GridLibrary(url, data).display();

Upvotes: 1

Related Questions