Setting JSON Ajax string into variables with Jquery then append an <li> - javascript

I have an Ajax script that is currently receiving a JSON data string and appending the data to a <li> on the page, like this:
This is the Jquery script I am using to do this:
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
var li = $("<li>").text(JSON.stringify(response));
$("#response").append(li)
But I want to assign variables to the 5 field results and display them in spans so they look something like after I add css to them:
I have tried different things to get this to work, and read a lot of stack articles, One Stack article says to assign the string a variable like this var data = JSON.stringify(myObject, replacer);, but it has not worked. This is the last thing I have tried, but I know it is not right. Any help would be appreciated, thanks.
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
var data = JSON.stringify(myObject, replacer);
var content = "balance: " + data.balance + " account_number:" + data.account_number;
var li = $("<li><span>").text(content);
$("#response").parent().append(li);
Also this is the JSON string I receive to the page:
{"type":"success","message":"Your message has been sent, thank you.","record":{"id":108,"bank_name":"Jane Doe","balance":"200","account_number":"8765432187654321","customer_id":"250","monthly":"50"}}

Putting var data = JSON.stringify(myObject, replacer); there doesn't make sense because myObject and replacer are not defined. Don't just copy and paste code. The other answers just provided the general signature of JSON.stringify. You already know how to use it, because you used it in your first code snippet.
Anyways, JSON.stringify converts an existing object/array to a string containing JSON, which also means that response already is an object. So all you have to do is access its properties. In your case,
var data = response.record;
will set data to the correct value.
More info: Access / process (nested) objects, arrays or JSON

Assuming that your response is a JSON response, you would not need to do:
var data= JSON.stringify(myObject, replacer);
Besides, myObject and replacer seem to be undefined. Also, it looks like this line:
var content = "balance: " + data.balance + " account_number:" + data.account_number;
should be:
var content = "balance: " + data.record.balance + " account_number:" + data.record.account_number;
If this does not work then try the following:
var data = $.parseJSON(response);
var content = "balance: " + data.balance + " account_number:" + data.account_number;
This will actually parse the response variable to an object that you can then access through "data.record".

Related

method plugin doesn't work within Function Constructor

What I'm trying to achieve in JavaScript is to make a method of the plugin I'm working with (called "Plugin") flexible. The plugin runs in an iFrame and has cross-domain trust settings applied. I want to use variables to build the method parameter rather than hard code it.
The hardcoded version is shown below and I've double checked this works. I've used it in functions and in a Function constructor. Both work.
window.Plugin.Session.Tags({
TagName: 'SomeTagName',
TagValueTagging: 'sometagvalue; secondtagvalue',
TagValueTaggingReset: '*'
}).Update();
My objective is to replace the 'sometagvalue' with a variable, so I can set the tag dynamically. The help says the parameter is a constant JSON string.
I've tried the following things:
build the parameter as string. Result: Though myText holds the exact same string as in the hardcoded version, the method is not executed.
var myTag = '\\'DEELNEMER ; name\\' ';
var myText = "{TagName : 'Workflow'," +
" TagValueTagging : " + myTag +
", TagValueTaggingReset : '*'}";
alert("myText = " + myText);
x = window.Plugin.Session.Tags(myText);
x.Update();
2) using new Function constructor. I created a variable with the session object and inserted that as parameter. In order to proof myself that I working with the right object, I've put it's LID in an alert as well outside as inside the constructor. Result: the Session.LID was the same inside and outside the constructor, but tagging did not happen.
var myFunction = "alert(\"in constructor Session.LID = \" + prmSession.LID); window.addTag =
prmSession.Tags({TagName : \'Workflow\', TagValueTagging : \'DEELNEMER\' , TagValueTaggingReset :
\'*\'}); window.addTag.Update();"
var addTagFunction = new Function("prmSession", myFunction)
var prmSession = window.Plugin.Session;
alert("in main function Session.LID = " + prmSession.LID);
addTagFunction(prmSession);
3) using JSON stringify. Again Result: Tag was not set, in neither variant..
var myTag = 'DEELNEMER ; name ';
var obj = new Object();
obj.TagName = "Workflow";
obj.TagValueTagging = myTag;
obj.TagValueTaggingReset = "*";<br/>
var myJSON= JSON.stringify(obj);
Plugin.Session.Tags(myJSON).Update();<br/>
/*variant 2*/<br/>
var myObjParsed = JSON.parse(myJSON);
Plugin.Session.Tags(myObjParsed).Update();
I would be very greatful for a tip how to solve this issue.
Regards
Plugin appears to translate the javascript into backend data queries during the compilation of the solution.
The use of parameters is therefore not possible.

Is there a way to replace text from a JSON object after it has been stringified?

I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");

Inserting a string at a variable index

I have not been able to find a working example or a good explanation of how I can achieve the following: (I would appreciate if anyone can point me in the right direction.
I have a query string: **"/api/bla?sources=[1,2]&plans=[1,2]&codes=[1,2,3]"**
I will be updating the query string via either javascript or jquery when certain events occur on my page, doesnt matter which.
For example, there is a multi select dropdown on the page which houses [sources] and [plans] and [codes]... These dropdowns have IDs which i am to update my request url with upons selecting items in teh dropdowns.
When a source with ID "3" is selected from the dropdown (or checkbox, doesnt matter what page controls are being used) the query string parameter sources[1,2] will need a "3" appended. Likewise then if the item with an ID of "2" is unselected, it will likewise be removed from the query string leaving the new string as sources[1,3]
I am somewhat new to javascript/jquery and especially more advanced string manipulation. I have been attempting to recreate something to demonstrate this and have gotten to the following which is not fully working.
Basically my initial if statement works as intended, but the moment the else is hit (when another ID needs to be added to an existing model in the query string - like a second ID for [sources] or [codes]) it returns wonky output - seeng as I couldnt get the right formula to update everything correctly.
//TIMEMTABLE QUERY
function updateCalendar(filter_id, filter_element) {
//Run through the filter checks before making final call to query and update timetable?
//GET THE MODEL/OBJECT NAME
var queryName = filter_element.attr('data-owner');
//GET THE IDs //this is either an array of all selected IDs or a single id which is used in the else statement
var queryId = filter_element.attr('value');
var queryIds = $('#'+filter_id).val();
var modelCheckIndex = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//build a request string
if (modelCheckIndex < 0) {
console.info('ADD MODEL TO QUERY STRING');
requestString = requestString + "&" + (queryName.toLowerCase() + "[" + queryIds + "]");
console.log(requestString);
}
else{
console.info('UPDATE MODEL ON QUERY STRING');
var position = requestString.toLowerCase().indexOf(queryName.toLowerCase());
//requestString = requestString.substr(modelCheckIndex -1, requestString.length -1) + "," + queryId + "]";
requestString = requestString.slice(modelCheckIndex.indexOf("]"), modelCheckIndex) + "," + queryId;
console.log(requestString);
}
//MAKE THE API CALL USING CREATED QUERY STRING
}
If anyone has any examples or fiddles lying around I would also appreciate it.
Fiddle I am trying to get to work
It looks like you are just having trouble parsing and updating a query string. In which case, I have a function I've been using for that (thank you Google)
function getUriParams(string) {
var params = {},
queryString = string.slice(string.lastIndexOf('?')).substring(1),
regex = /([^&=]+)=([^&]*)/g,
m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return params;
}
The input is your requestString and the output is an object of key value pairs of the query string.
To make the object a string, jQuery makes it easy with $.param().
//get key value pairs
var obj = getUriParams(requestString);
//make query string
var str = $.param(obj);
I suggest to change the logic a bit. I would use some data storage for the wanted parameter and rebuild the request string every time when it's necessary, like the below example.
It is much more better, than rebuild the string each time when some value has changed.
var data = {
sources: [1, 2],
plans: [],
codes: [1, 3, 4]
};
function buildStr() {
function get(key) { return key + '=' + JSON.stringify(data[key]); }
return '/api/bla?' + ['sources', 'plans', 'codes'].map(get).join('&');
}
document.write('<pre>' + buildStr() + '</pre>');

Json string values in javascript

I have following JSON string in a global variable in Javascript
var domains = {
"DomID00001": {
"ID":"DomID00001",
"Name":"Testdomein1"
},
"DomID00002": {
"ID":"DomID00002",
"Name":"Testdomein2"
}
};
What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?
If I just alert the domains var it says = [object Object]
Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
Since the keys are variable, you should probably use a for..in loop:
for( domid in domains) if( domains.hasOwnProperty(domid)) {
console.log(domid,domains[domid].ID,domains[domid].Name);
}
Try this:
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
var strName1 = domains.DomID00001.Name;
var ID1 = domains.DomID00001.ID;
alert('Name: ' + strName1 + ' - ID: ' + ID1);

Outputting JSON object by key

I have a JSON string that looks like this:
{"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
In Javascript, I'm trying to output the strings by category (cat1-3), this is my code so far.
$.post(loadUrl, function(data){
$("#result").html("<p>Cat1: " + data.cat1 + "</p><p>Cat2: " + data.cat2 + "</p>");
});
I would normally not use JSON (Usually JSTL) but since I want to learn AJAX, I want to try output the cat1-3 values by the key, which I keep getting "undefined".
I was using this as a guide to get the values: http://www.skill-guru.com/blog/2010/01/27/json-javascript-tutorial/
Try below script
va response = {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
var obj = jQuery.parseJSON(response);
alert(obj.cat1);
it will return m1
var a = JSON.parse("{\"cat1\":\"m1\",\"cat2\":[\"d1\",\"d2\",\"d3\"],\"cat3\":[\"m1\",\"m2\",\"m3\",\"m4\"]}");
for(key in a)
{
alert(key);
alert(a[key]);
}

Categories

Resources