CodeIgniter and JSON objects: how to push my data to database? - javascript

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!!

Trigger this from your Js file. (include jQuery Library)
provide url, post key and value you will receive post parameters at specified URL.
jQuery.post("<URL>", {dataname: datavalue}, function( r ) {
console.log(r);
});
I am also using ajax.

From your Original Post, I see that you have a JSON object. If it is already in object form, there's no need for you to convert it at all. Just assign that JSON to a variable and pass that variable to your ajax data parameter like so:
$("#hexa-btn").on("click", function () {
var json = { "index": 0, "x": 50, "y": 80, "weight": 2, "px": 50, "py": 80, "fixed": 0 };
$.ajax({
type: "POST",
url: "/prototype/returndata",
data: json,
success: function(data){
console.log(data.index);
console.log(data.x);
console.log(data.y);
}
});
});

Using ajax can solve your problem!
$.ajax({
type: "POST",
url: "test.php",
data: yourData,
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have m

Related

JSON Data cannot be stored in variable

Im trying to load the content of a JSON File into an variable.
Before, the variable looked something like this:
var Data = {
teams : [
["Team 1", "Team 2"],
["Team 3", "Team 4"]
],
results : [
[[1,2], [3,4]],
[[4,6], [2,1]]
]}
Now I have a JSON File looking something like this:
{"teams":[["Team 1","Team 2"],["Team 3","Team 4"],"results":[[[[1,2],[3,4]],[[4,6],[2,1]]]}
Now I want that the the content of the JSON File is stored in the Data Variable before. I tried it with Ajax which looks like this:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data
},
});
Console.log works perfect, but the Data is not saved in the variable and I'm getting the error: Uncaught ReferenceError: Data is not defined.
I also tried it with var Data = JSON.parse(data), but this doesn't seem to work either.
And now I'm stuck without any clue.
Thanks for help in advance.
I'm not sure what your code looks like after the ajax call, but I'm guessing the the code where you are using Data is after the ajax call. ajax is asynchrounous. That means that your code doesn't wait for it to finish before moving on. Any code that needs to wait until after it's done fetching the data, you can put in the .success function. Also, it's worth noting that success only gets called when the ajax request is successful. If you want to handle errors, you can use .error Something like this should work:
$.ajax({
type: "GET",
dataType : 'json',
async: true,
url: 'data.json',
success: function(data) {
console.log(data)
var Data = data;
// Anything that needs to use Data would go inside here
},
error: function(err) {
// handle errors
console.error(err);
}
});
// Any code here will not wait until `Data` is defined
// console.log(Data) // error

Parse a json reply from a jquery result in php

I have a simple search form which query an external server for result with jquery
$("#formsearch").on("submit", function (event) {
// everything looks good!
event.preventDefault();
submitFormSearch();
});
function submitFormSearch(){
// Initiate Variables With Form Content
var searchinput = $("#searchinput").val();
$.ajax({
type: "GET",
url: "https://external-server/api/",
headers: {"Authorization": "xxxxxxxxxxxxxx"},
data: "action=Search&query="+searchinput,
success:function(json){
console.log(json);
$.ajax({
type: "POST",
url:'search_func.php',
data: "func=parse&json="+json,
success:function(data) {
console.log(data);
$('#risultato_ricerca').html(data);
}
});
}
});
}
The first GET ajax works properly and I get correct data but trying to send this json data to my php script in post I can't get data.
This is the code in search_func.php
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'parse':
parse($_POST['json']);
break;
default:
break;
}
}
function parse($json) {
$obj = json_decode($json,true);
var_dump($obj);
}
... it displays NULL
Where I'm wrong ?
EDIT:
SOLVED
changing:
data: "func=parse&json="+json,
to:
data: { func: 'parse', json: JSON.stringify(json) },
json code is correctly passed to search_func.php
Changed function parse in php file to:
function parse($json) {
$data = json_decode(stripslashes($json),true);
print_r($data);
}
Thank you.
Is the javascript json variable correctly filled (i.e. what does your console show you?) Possible you must encode the json variable to a string before posting.
i.e: instead of data: "func=parse&json="+json, use data: "func=parse&json="+JSON.stringify(json),
See this: http://api.jquery.com/jquery.ajax/
The correct syntax is: data: { func: 'parse', json: my_json_here }
If this doesn't works is probably that you have to encode the JSON to a string (see JSON.stringify())

Passing SQL results from controller to chart.js

Situation
I would like to pass the count of X from my SQL database from my controller to my view where a chart picks up this data and renders it.
What I have done so far
So far I have the controller code. which gets the count from the table and I am trying to pass this figure back to the chart.
public ActionResult currentPopulation()
{
var dests = db.personal_info.Count();
// return Json(dests, JsonRequestBehavior.AllowGet);
return Content(JsonConvert.SerializeObject(dests), "application/json");
}
I also have the chart (code below) from the view
<script>
var barChartData = {
url: '/Home/currentPopulation',//Local
type: "GET",
dataType: "JSON",
labels: ["A", "B", "C"],
datasets: [
{
// url: '/Home/currentPopulation',//Local
// type: "GET",
// dataType: "JSON",
fillColor: "#26B99A", //rgba(220,220,220,0.5)
strokeColor: "#26B99A", //rgba(220,220,220,0.8)
highlightFill: "#36CAAB", //rgba(220,220,220,0.75)
highlightStroke: "#36CAAB", //rgba(220,220,220,1)
data: [51, 30, 40], //this is the hard coded values which the chart loads
//
},
],
}
$(document).ready(function () {
// new Chart($("#canvas_bar").get(0).getContext("2d")).Bar()
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
tooltipFillColor: "rgba(51, 51, 51, 0.55)",
responsive: true,
barDatasetSpacing: 6,
barValueSpacing: 5
});
});
</script>
Problem
The problem I have is that, I cannot replace the [51,30,40] for the A,B,C values
which is supposed to come from my controller. I am a bit confused as my action "currentPopulation" is not getting called, and i cannot move the link cause according to the code, the data is picked up from barChartData and assign when the new chart is called.
new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
Any help would be appreciated.
If you want your controller to be hit you need to make an ajax request. This ajax call should be done on the action which you want the controller to be called. Button click or so on. Start using console.logs to debug your javascript.
If you want this code to be execute on page open, wrap the ajax call in document.ready function.
$.ajax({
type: "POST",
url: "Home/currentPopulation",
//data: jsonData, if you need to post some data to the controller.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var aData = response.d;
console.log(aData);
//build here your **data** as object wanted by Bar. Colors which you want and so on, options could be empty object {}. I think is possible to call bar without options, you need to read the documentation.
var ctx = $("#myChart").get(0).getContext("2d");
var myBarChart = new Chart(ctx).Bar(data, options);
}
function OnErrorCall(response)
{
alert('error');
}
Here I show you little example how to do it. You can just google chart.js with mvc there is a lot of examples. Check if the url is correctly written I think you should remove the / in the begging.
This is just suggestion.
Also if you had the money and this is serious chart project use highcharts.js ! This is the best library which can work totally offline and gives you really good flexibility.
Usefull links:
ChartJS documentation

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

How to post this array and print in php?

How can I send this array back to the server so I can handle it in PHP?
<script>
var myJSONObject = {
"onw": [
{"name": "nilesh", "age": "31", "sal": "4000"},
{"name1": "nitin", "age": "11", "sal": "14000"}]
};
document.write(myJSONObject.join());
</script>
You can use serialization method. i.e serialize the javascript variable and pass it to php, in php file you can deserialize the same.
serializing : Serializing to JSON in jQuery
Ref: http://api.jquery.com/serializeArray/
Never use document.write as its outdated, the preferred way to add elements to DOM is using appendChild
Example Code for appending:
var textNode = document.createTextNode("some text"); // creates new text node
textNode.appendChild(document.body); // adds to the end of the body
For posting data to php by using jquery:
Before sending it to server, you need to format it as String using JSON.stringify
var formattedData = JSON.stringify(myJSONObject )
$.ajax({
type: "POST",
url: "server.php",
data: formattedData ,
dataType: 'json',
success: function () {
alert("Data posted to php and processed succesfully");
}
});
var json_text = JSON.stringify(myJSONObject, null, 2);
alert(json_text);

Categories