I have a JS file that manages my data (push the data in my JSON objects, etc), and the classic MVC structure of files from CodeIgniter.
My JS contains my JSON objects that I would like to push in my database. How could I do for it? How can I reach the controller and the model from my JS file? I just can't figure out what is the right process to achieve my goal! And I find nothing similar to my question.
EDIT
The data to push into the database is a part of the entire JSON object.The data to push is, for example: { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 }
In my JS file, I have tried this code:
$("#hexa-btn").on("click", function () {
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: JSONshapes.shapes[0].nodes[0],
cache: false,
success:
function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});
And my controller has this function:
function returndata(){
$index = $this->input->post('index');
$x = $this->input->post('x');
$y = $this->input->post('y');
$weight = $this->input->post('weight');
$px = $this->input->post('px');
$py = $this->input->post('py');
$fixed = $this->input->post('fixed'); ;
echo json_encode(array('node'=>$node));
}
I am not sure at all about this function. It seems this is the role of the model to do this job, isn'it?
2nd EDIT So, I tried the solution of @Harish Lalwani, but this time with my array of nodes (not only one). I have the following function in the JavaScript file:
function sendNode(){
var node_url = "/prototype/insert_node";
var data_node = JSON.stringify(JSONshapes.shapes[0].nodes);
$.post(node_url, {'node_data': data_node}, function(data){
console.log(data.index);
});
}
and the following one in the controller (thank to this post):
function insert_node(){
$node_data = $this->input->post('node_data');
$node_data = json_decode($node_data,true);
echo 'Your Data: ' . $node_data[0]['index'];
},
But, when printing the data, I get undefined
. The variable data_node
is the following (so, is an array):
[{"index":0,"x":50,"y":80,"weight":2,"px":50,"py":80,"fixed":0},{"index":1,"x":189,"y":107,"weight":2,"px":189,"py":107},{"index":2,"x":95,"y":145,"weight":2,"px":95,"py":145}]
Now, I don't know anymore what to do! I find really too few examples. Can anyone put me out of my misery? Thank you very much in advance!!