PHP strips out JSON node (array)? - javascript

I'm trying to log some stuff in a JSON file.
An entry looks like this:
{
"bookindId":"30779265",
"timestamp":"1428447744",
"plate":"D-GO9872",
"cityId":"RLD",
"zoneId":"759",
"highDemandZones":[
"402",
"429",
"714",
"715",
"721",
"728",
"732",
"734",
"742",
"756",
"758",
"763"
],
"accountId":"151426",
"date":"20150408",
"formattedDate":"08.04.2015, 01:02 Uhr"
},
But sometimes, highDemandZones is just missing:
{
"bookindId":"30779279",
"timestamp":"1428447762",
"plate":"D-GO120",
"cityId":"RLD",
"zoneId":"759",
"accountId":"151426",
"date":"20150408",
"formattedDate":"08.04.2015, 01:02 Uhr"
},
My problem is that even if there aren't any highDemandZones, it should at least be in there as an empty array. Also I can defenitely say that it shouldn't be empty either. Which leads me to the conclusion that my php code is flawed.
This is the javascript function
App.prototype.trackBooking = function() {
var self = this;
// [... stripped out other code for clarity]
// get high demand zones
var highDemandZones = [];
$.each(this.model.zoneDemands, function(id, details) {
if(details.demand == 'HIGH') {
highDemandZones.push(id);
}
});
// [... stripped out other code for clarity]
var obj = {
bookindId: this.model.user.booking.bookingId,
timestamp: Math.round(Date.now() / 1000),
plate: this.model.user.booking.vehicle.numberPlate,
cityId: this.model.city.id,
zoneId: car.zoneId,
highDemandZones: highDemandZones,
accountId: this.model.user.accountId,
date: todayFormatted,
formattedDate: day + '.' + month + '.' + year + ', ' + hours + ':' + minutes + ' Uhr'
};
return $.ajax({
type: "POST",
dataType: 'json',
url: 'php/ajax.php',
data: {
booking: obj,
action: 'trackBooking'
}
}).success(function(data) {
console.log('TRACKED');
console.log(data);
}).fail(function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
});
};
This is php function that'll save this obj to a JSON file
function saveBooking($booking) {
// get current bookings
$json = file_get_contents("../reporting/bookings.json");
$bookingsArr = json_decode($json, true);
if(!isset($bookingsArr[$booking['date']])) {
$bookingsArr[$booking['date']] = array();
}
// push new booking into current bookings array
array_push($bookingsArr[$booking['date']], $booking);
// convert to JSON
$jsonString = json_encode($bookingsArr);
// save into JSON file
file_put_contents('../reporting/bookings.json', $jsonString);
// return JSON
echo $jsonString;
}
Do you have any ideas when this could occur? The IDs (the strings inside highDemandZones) never have extended characters like é.
There are defenitely nodes being stripped out even though the array is not empty. The JSON is valid.

Related

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

JSON.stringify and $http request

I have a JS String, like so:
user_fav = "21,16";
This has to go thru a function where it becomes a JSON array with an id key, like so:
{"id":21},{"id":16}
And this goes into an $http request:
return $http({
method: 'GET',
url: getUrl('products'),
params: {
pageSize: 2000,
pageNumber: 1,
"filter": { "q": { "$or": [{"id":21},{"id":16}] } }, // <-- HERE
sort: []
}
});
Now if I run the above $http request everything works fine, but if I convert the String (user_fav) into that JSON and send this to the $http request it fires an error. This is my converter:
user_fav = "21,16";
var user_fav_to_array = "";
var splitFav = user_fav.split(",");
for (var i = 0; i < splitFav.length; i++) {
user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
}
var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);
//Result: JSONFavs => {"id":21},{"id":16}
So this gives an error:
return $http({
method: 'GET',
url: getUrl('products'),
params: {
pageSize: 2000,
pageNumber: 1,
"filter": { "q": { "$or": [JSONFavs] } }, // <-- HERE
sort: []
}
});
Madame and messier the error is 417 (Critical Exception), this is coming from the Backand.com syste
Have a look at the code below. What your code actually doing is assigning a Json STRING to $or property. But really needed is to assign array of items (as expected). Let me know if you have any questions
user_fav = "21,16";
//Dont need this
//var user_fav_to_array = "";
// New Variable to save array items
var arrayData =[];
var splitFav = user_fav.split(",");
for (var i = 0; i < splitFav.length; i++) {
// don't need this
//user_fav_to_array += JSON.stringify({ id: parseInt(splitFav[i]) }) + ',';
// Just create a simple javascript object with id and put it into array at i index
arrayData[i]={ id: parseInt(splitFav[i]) };
}
//var JSONFavs = user_fav_to_array.substring(0, user_fav_to_array.length - 1);
// Then in Http Request filter, it should be just like this "$or": arrayData
"filter": { "q": { "$or": arrayData } }
This might have to deal with your variable - var user_fav_to_array = "";
You may want to change it to the following var user_fav_to_array = [];
Since it has the quotations it may be causing your variable to behave in a way that you don't want it to. Unless strings are treated as arrays in javascript.

Javascript - json data not being transferred into memory properly

I have a json file that contains 16,490 lines of data. Here's a snippet:
[
...
["alrightty",2 ],
["alrighttyy",1 ],
["alrighty",100 ],
["alrightyy",1 ],
["alrigt",1 ],
...
]
This data will be used for my sentiment analysis thesis project. I used the following code to extract the data from the json file:
var positive_words_list = {}
function readJSONFile(filename,type) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'json',
success: function(data) {
switch (type) {
case "pos" : positive_words = data; break;
case "neg" : negative_words = data; break;
case "afinn" : afinn_words = data; break;
}
},
async: false
});
}
readJSONFile('js/json/positivekeywords.json','pos');
for (var i = 0; i < positive_words.length; i++) {
row = positive_words[i];
positive_words_list[row[0]] = row[1];
};
What this code does is extract the data from the json file and then put it in a 1-dimensional array with each word as an array index and the number as the value.
Now I have this code run when the site loads inside $(function() { ... }); so positive_words_list should contain the data on load time. The thing is after the site loads and I do positive_words_list.length in the console, it outputs 63. As I said, there should be 16,490 entries.
Did I miss something? What am I doing wrong?
Thanks!
John
EDIT: I should add that when I do a positive_words.length in the console, I get the correct number of elements, 164,950
As far as I can see positive_words_list is a JavaScript object that does not have length property out of the box. So the only reason why you get the magic number 63 is because your array of arrays contain entity with word length as a first item; something like:
[
...
['length', 63],
...
]
In order to get number of keys in JavaScript Object you can either do Object.keys(positive_words_list).length or iterate over all properties and increment the counter:
function size(obj) {
var key,
counter = 0;
for(key in obj) {
if(obj.hasOwnProperty(key)) {
counter++;
}
}
return counter;
}
size(positive_words_list); // <- will return number of properties in object
Your snippet may be modified in the following manner:
HTML
<h1 id="data">Number of positive words is ...</h1>
JavaScript
$(function(){
var positive_words,
positive_words_list = {};
function readJSONFile(filename,type) {
$.ajax({
type: 'GET',
url: filename,
dataType: 'json',
success: function(data) {
switch (type) {
case "pos" : positive_words = data; break;
case "neg" : negative_words = data; break;
case "afinn" : afinn_words = data; break;
}
},
async: false
});
}
readJSONFile('data.json','pos');
for (var i = 0; i < positive_words.length; i++) {
row = positive_words[i];
positive_words_list[row[0]] = row[1];
};
$('#data').html('Number of positive words is ' + Object.keys(positive_words_list).length);
});
Plunker: http://plnkr.co/edit/uhHZ1zEuUHXHIQrd1BVa?p=preview
positive_words_list is an object, not an array, so you should result in:
positive_words_list["alrightty"] === 2
positive_words_list["alrighttyy"] === 1
and so forth. You can get an array of the keys of the object using:
Object.keys(positive_words_list)
Object.keys(positive_words_list).length
Which will return an array of the keys of your object. Note that Object.keys is an ES5 feature available in most current browsers.

jQuery : update the database with all of the data from the ajax-request

am trying to update database.
For that iam doing like this
From js code
var data = {
"jobid": $('#jobid').val(),
"names": $('#names').val(),
"scripttype": $('#testscripts').val()
};
var msg="";
for(i = 1; i <=4; i++) {
data["Param" + i + "Key"] = $('#key' + i).val();
data["Param" + i + "Value"] = $('#value' + i).val();
}
$.ajax({
type: 'post',
url: "/save",
dataType: "json",
data: data
});
in node.js side
jobsCollection.update({
_id: id
}, {
$set: {
names: record.names,
script: record.scripttype,
// i dont know what should i place in this part???
// i have to set paramkey and paramValues
}
},
{
upsert: true
},
function (err, result) {
if (!err) return context.sendJson([], 404);
});
in record.names and record.scripttype getting proper values.
I don't know how to set values got from the for loop for updating
request going
Request: /save
{ jobid: '',
names: 'first',
scripttype: 'fow',
Param1Key: '1',
Param1Value: 'oneeeeee',
Param2Key: '2',
Param2Value: 'twoooooooo'
etc........
............
}
Since the property names are dynamic, you'll need to use the indexer-style property accessor of JavaScript as shown below.
Just reverse the process basically. I'm not sure where the data is located at the point you're calling update, so I called it sourceData in the example below;
// create an object with the well known-property names
var set = {
names : record.names,
script : record.scripttype
};
// now loop through the params and set each one individually
for(i = 1; i <=4; i++) {
var key = "Param" + i + "Key"; // build a key string
set[key] = sourceData[key]; // grab the data and set it
key = "Param" + i + "Value"; // and repeat
set[key] = sourceData[key];
}
then, pass it to your update:
jobsCollection.update({
_id: id
}, {
$set: set // pass the object created above
}, /* etc. */
If you don't know the count of Params, you could:
send it
use instead for .. in to loop through all the properties
For #2:
for(var key in sourceData) {
// you could filter the property names here if you'd like
// (like if only Params# were important)
set[key] = sourceData[key];
}

Parsing JSON object with embedded array, how?

Consider the following Javascript. The JSON object I'm parsing has an array on it called History. Each object in the History (resp[0].History) array has a UniqueID property. How do I get at that UniqueID property for each object in the array please?
// Retrieve individual licence information.
function loadLicenceDetails(uniqueID) {
document.body.style.cursor = 'wait';
$('#loadingLicenceDiv').modal('show');
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/JadeLicensingWebService/default.asmx/GetLicenceDetails',
dataType: 'json',
data: '{"licenceHolder":"' + $.cookie("companyName") + '","uniqueID":"' + uniqueID + '"}',
success: function (data) {
resp = $.parseJSON(data.d);
$('#inputLicenceName').val(resp[0].LicenceName);
$('#licenceKeyInput').val(resp[0].LicenceKey);
$('#selectProductType').val(resp[0].Product);
$('#selectDuration').val(resp[0].Duration);
$('#startDateInput').val(resp[0].StartDate);
$('#expiryDateInput').val(resp[0].ExpiryDate);
$('#orderedByInput').val(resp[0].OrderedBy);
// How do I get at the History.UniqueID ?
$('#notesInput').val(resp[0].Notes);
$('#licenceInfoHeader').html('<strong>#' + uniqueID + '</strong> - ' + resp[0].LicenceName);
Assuming your JSON looks like:
{
"History": [
{
"UniqueId": "abc"
},
{
"UniqueId": "def"
},
{
"UniqueId": "ghi"
},
]
}
You can do this:
var ids = []; // Make an array to hold the IDs
// Iterate over History items
for (var i = 0; i < resp.History.length; i++) {
var item = resp.History[i];
ids.push(item.UniqueId); // Put each ID in the array
}
If that's not what your JSON object looks like, can you add a sample object to your question so it's clearer what you're asking?
Solved by using this:
$('#licenceHistoryText').val(resp[0].History[0].DateIssued);
Edit, final solution:
$.each(resp[0].History, function (i, obj) {
document.getElementById("licenceHistoryText").value += obj.DateIssued + ' - ' + obj.LicenceName + ' [' + obj.LicenceKey + ']\n';
});

Categories

Resources