possibility to use parse_str on variables - javascript

So I made a post related to me wanting to have my JSON file look like this:
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
instead of this:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
people recommended me to use parse_st to make my JSON look like the first piece of code, however my question (the reason I made a new post was because they gave a great tip, but never responded to it unfortunately and I wasn't really sure if I could edit my post regarding to a whole new subject basically), is it possible to use this directly on variables? they gave me this piece of code:
const result = "language=nl_NL&getExerciseTitle=test";
const parsed = queryString.parse(result);
as you can see it directly takes the variable + the value given to it, but I was wondering: I will always insert new data etc, so how can I apply it so it will always target the variable that could possibly change (instead of litterly writing language=nl_NL for example) I came to notice that whenever I insert the piece data: {id: getUrlParameter('id') in my ajax call, it will make my JSON look like the second one (but I do get my ID send), but whenever I take that piece out of it it will show up like the first one but it won't increment any longer. the complete ajax call looks like this:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {id: getUrlParameter('id'), formData: $('#my_form').serialize()},
dataType: 'json',
}).done(function (response) {
});
});
}
Cheers!

Related

$scope.someVariable can't be touched

I'm new to AngularJS so my mistake might be anywhere in my code and I can't find it. I'm using $HTTP GET method to retrieve data that's located in some server /page. After retrieving that data (which is JSON) I want to play with that string to retrieve the data properly, like name: number: and so on. But the thing is once I put that data into $scope.listOfCompanyUsers I can't touch it. If I try to $scope.listOfCompanyUsers.slice(..) or if I try any other string function on that object my entire webpage crashes. I "alert()"'d the $scope.listOfCompanyUsers and the result is:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
What I wanted to do is remove the pre and br tags from that string so I have a pure JSON string that I could play with but again any function I try on $scope.listOfCompanyUsers crashes my site. What do I do? I tried var someOtherVariable = $scope.listOfCompanyUsers but that variable doesn't work later. I'm adding parts of my code because my mistake might be somewhere else.
Controller:
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.listOfCompanyUsers = response.data;
},
function errorCallback(response) {
alert(response.status);
});
Later on the same controller:
.
.
$scope.someFunction = function () {
.
.
else {
alert("Maximum of 9 other passengers!");
alert($scope.listOfCompanyUsers);
// In this alert I could see the $scope.listOfCompanyUsers as mentioned above
}
};
My target right now is to have a var objectOfUsers = [{admin: true, id:123, username: "name", last_name: "test", name: "something"}, {next user.}, .] but because I can't touch the $scope.listOfCompanyUsers I'm stuck.
The problem is that the server is adding some extra tags to the response that shouldn't be in there:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
Edit your server-side code, to remove: <pre> and </pre><br>.
Then the call will work.
Is your response a string? If your response has HTML tags, then that is not valid JS object format. It looks like you have a Javascript array with one object, enclosed by some HTML tags.
Therefore you won't be able to access anything within this using the object reference notation (.) until you treat it like a string and use String.prototype.replace and replace the tags, and then do a JSON.parse on the remaining string to convert it into an object
Very strange server response, so possible solutions are:
Change server response to standard JSON without unwanted <pre>
If You can not change response remove not wanted part of response using regular expression in JS. Working example how do that:
var response='<pre>[{"admin": true, "id": 123, "username": "someName","last_name": "someLastName", "name": "John Doe"}]</pre><br>';
var goodResponse=response.match(/>([^<]*)</)[1];//remove not wanted signs
var parsedGoodResonse=JSON.parse(goodResponse);
console.log(parsedGoodResonse);//here we have parse js array
In parsedGoodResonse You have object which can be "touched" so exactly what You need.
The problem with the extra tags is not on your code, it's on the server-side. You should check the code on the server and find the reason for those extra tags. They can't be there because they are making the response an invalid JSON.

AJAX Get from a JSON Tree

I'm just starting out with AJAX, trying to use JQuery's $.getJSON function (or any related, ie $.load(), $.ajax(), etc). I have a JSON file with a structure something like this:
[
{
"id": 1,
"email": "user#domain.com",
"password": "password"
},
{
"id": 2,
"email": "one#two.com",
"password": "password"
}
]
How can I call a GET on this JSON file (let's call it users.json) for a user with a specific email? I thought it would be the second paramter in $.getJSON, but that seems to just return the whole tree.
Thanks!
Short answer - you can't do this directly with AJAX. jQuery can extract portions of HTML and XML documents, but not JSON.
Easiest answer - retrieve the entire object (you have to, anyway) and use jsonpath to get the structure you want
Longer answer - retrieve the entire object, and traverse it yourself to get the object you want
Best answer - make the email address a parameter to whatever script produces the json and have the server only return the data you want.
Once the JSON is parsed, you pass it to a callback function - then you can manipulate that array however you need.
You'll probably want some custom code:
$.getJSON(myURL, function(data) {
/* data is an array of objects */
for (var i=0, j=data.length; i<j; i++) {
if (data[i].email === some_value) {
/* do something with data[i] */
};
};
});
http://api.jquery.com/jQuery.getJSON/
You can 1 of 2 things, loop through the array on the client side, or dynamically have users.json generated on each call (this assumes a backend server language like php)
Using dynamically generated json file
JS
$.ajax({
url:"/users.json.php",
data:{
useremail:"someusersemail#here.com"
}
type:"POST",
dataType:"json",
success:function(userdata){
//users data will be in userdata
console.log(userdata.email);
}
})
Server Script (assumes PHP): users.json.php
$email = $_POST['useremail'];
//get user data based on email
...
echo json_encode($userdata);
die;
generated json file should end up outputing something like
{"id": 1,"email": "user#domain.com","password": "password"}
Loop Method: loop through the users array on client side
$.ajax({
url:"/users.json",
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++) {
var user = data[i];
if(user.email == "someemail#gmail.com") {
//do what you need to with user data
}
}
}
})

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

how to add json data to the server and display it in the jqgrid right after a button clicked

i have a running program that will display my data from a server to the jqgrid. what i want now is to save data to the server. here's my code:
function Add(){
var datas = {
"ID": "xyz",
"operation": "Add",
"fields": ["code", "desc", "type"],
"values": [$('#code').val(), $('#desc').val(), $('#type').val() ]
}
$('#tblData1').setGridParam({
url:'myni.php?path=' + encodeURI('this/update') + '&json=' +(JSON.stringify(datas)),
datatype: Settings.ajaxDataType,
});
$('#tblData1').trigger('reloadGrid');
}
this codes returns an error message "Exception error: Server Error: Parameter 'operation' is not specified." i already set an operation and i don't know what went wrong. can somebody help me fix this? please.
i want to know how to add data to the server after clicking the button and display it in the jqgrid right away. Please...
The function Add set local variable datas which exist only inside of the Add function. Probably what you want is to return the value from the function and set to the variable existing in the scope of usage the setGridParam call.
The next problem is that you should encode JSON.stringify(datas) with respect of encodeURIComponent before inserting it as the part of URL. You can also use jQuery.param function instead:
url:'myni.php?' + $.param({path:'this/update', json:JSON.stringify(datas)})
If you use HTTP GET (mtype:'GET') for requests to the server I would recommend you better to use postData parameter of jqGrid which contain functions:
$("list").jqGrid({
url:'myni.php',
postData: {
path: 'this/update',
json: function() {
return JSON.stringify({
ID: "xyz",
operation: "Add",
fields: ["code", "desc", "type"],
values: [$('#code').val(), $('#desc').val(), $('#type').val()]
});
}
},
// other parameters
});
The properties of postData parameter will be added to the URL ('?' and '&' will be inserted if needed) in case of the usage of mtype:'GET' or to the body of the posted data in case of mtype:'POST'.
The advantage of the usage functions inside of postData is that the corresponding values (like the value of json parameter) will be calculated on every ajax request. If the user changes the sort order or chooses another page the ajax request to the server will be send. So in the case the postData properties must be determined and the current values from $('#code').val(), $('#desc').val() and $('#type').val() will be inserted in the request.
If the value of path parameter should not be static you can make it also as the function.
In case of usage postData which includes functions you code could be reduced to $('#tblData1').setGridParam({datatype: Settings.ajaxDataType}).trigger('reloadGrid').
More about the usage of functions inside of postData you can read here.

jQuery and long int ids

I've faced with a next problem:
In our database we have objects with ids, like 4040956363970588323.
I'm writing some client-wizard on jQuery for interacting with such objects. Client receives base data about objects trough an Ajax request, like:
$.ajax({
url: "/api/pages/",
type: "get",
dataType: "json",
data: {"id": site_id},
success: function(data){
if (data.success){
for (var pidx in data.pages){
console.log(data.pages[pidx].id);
var li = $('<li class="ui-widget-content"></li>');
var idf = $('<input type="hidden" id="pid" value="{0}"/>'.format(data.pages[pidx].id))
var urlf = $('<input type="hidden" id="purl" value="{0}"/>'.format(data.pages[pidx].url))
li.text(data.pages[pidx].title);
li.append(idf);
li.append(urlf);
$("#selectable_pages_assign").append(li);
}
pages_was = $("#selectable_pages_assign>li");
}
else
updateTips(data.message);
},
error: function(){
updateTips("Internal erro!");
}
})
So, as you see I send data like JSON object (a bit of server code):
return HttpResponse(dumps({
"success": True,
"pages": [{"id": page.id, "title": page.title, "url": page.image} for page in Page.objects.filter(site = site)]
}))
According to Firebug, server send right ids in data, but console.log(..) instead of correct id (4040956363970588323), outputs id 4040956363970588000.
Why does this happen?
Without right ids, any chance, that my wizard will work correctly :)
My guess is something is going wrong in the conversion to JSON. When you write the value, you'll probably need to put quotes around it, to make sure it's treated as a string.
That looks like some kind of overflow problem to me.
According to this discussion here on SO, JavaScript can only handle INTs of size 2^64, which means the max INT is somewhere around
184467440737100000
which is much less than
4040956363970588323
EDIT: Sorry, the largest exact integer is 2^53, but the case is the same.

Categories