I have the below file that passes variables in query string.
What I am able to do
Get document.getElementById("getthis").innerHTML and save it in
var getthis.
Get value selected $('#first').val(); and save it in var from
What I am not able to do
Get this values document.getElementById("list1").innerHTML, document.getElementById("list2").innerHTML, document.getElementById("list3").innerHTML and save the it in var data in this format var data = { seats_booked: [ 'B2', 'B5', 'A20' ] };.
I would like to know how to do this, since in query string I can then be able to get the variables using PHP.
I hope my question is clear and help will be appreciated. Thank you in advance.
Here is the code:
<?php
$str = $_SERVER['QUERY_STRING'];
parse_str($str);
echo $seats_booked[0];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<body>
<ul>
<li id="getthis">list</li>
</ul>
<select id="first" name="first">
<option value="10">First</option>
<option value="11">Second</option>
<option value="12">Third</option>
<option value="13">Forth></option>
</select>
<ul>
<li id="list1">B2</li>
<li id="list2">B5</li>
<li id="list3">A20</li>
</ul>
<button id="next" name="next">Next Step</button>
<script type="text/javascript">
$(document).ready(function(){
$("#next").click(function() {
var data = { seats_booked: [ 'B2', 'B5', 'A20' ] };
var result = $.param(data);
var first = $('#first').val();
var getthis = document.getElementById("getthis").innerHTML;
window.location = '?first='+first+'&getthis='+getthis+'&result='+result;
});
});
</script>
</body>
</html>
jQuery.param converts a data structure to the format used for query strings. Whole query strings. Not bits of query string*.
Put all your data in a query string, then use param on it.
var result = { seats_booked: [ 'B2', 'B5', 'A20' ] };
var first = $('#first').val();
var getthis = document.getElementById("getthis").innerHTML;
var data = {
result: result,
first: first,
getthis: getthis
};
var query = jQuery.param(data);
window.location = "?" + query;
* more precisely, it converts to a set of key=value pairs suitable for a query string, so you can join them up yourself. Your problem is that you are taking the key=value pairs and then trying to use them as a single query string value. But you're also failing to encode the rest of the data properly, and using param for the whole thing is much cleaner and more maintainable.
You can do it this way
<ul class="seats_booked">
<li id="list1">B2</li>
<li id="list2">B5</li>
<li id="list3">A20</li>
</ul>
var seats_booked = [];
$("ul.seats_booked li").each(function() { seats_booked.push($(this).text()) });
var data = {};
data["seats_booked"]=seats_booked;
Did you mean something like this?
https://jsfiddle.net/5p6k11ny/
I have only changed window.location to console.log
var data = { seats_booked: [] };
data.seats_booked.push(document.getElementById("list1").innerHTML);
data.seats_booked.push(document.getElementById("list2").innerHTML);
data.seats_booked.push(document.getElementById("list3").innerHTML);
Ofc, you could do it in some loop like
"list" + i
Related
I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>
I am pulling data via a CRM API and successfully rendering that data in the front end of my Google Script web app. But manipulating or formatting this data for the front end is a challenge for me.
In the code below, the Potential Name on the second line is rendering the correct data to the page. But the first line called Quote is showing undefined. This data is the data I am trying to format so that only the last six characters or the string are printed to the page.
Clearly, I must be trying to access the data from the API incorrectly. Could someone please provide me with the correct way to manipulate this data in Google Scripts?
Code.gs
function doGet() {
var templ = HtmlService.createTemplateFromFile('Allied-po');
templ.data = requestRecordFromCRM();
return templ.evaluate()
.setTitle('Purchase Order')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/*Fetch record data from CRM*/
function requestRecordFromCRM() {
requestedId = '1234';
var authToken = 'XXXX';
var zohoRequestUrl = 'https://crm.zoho.com/crm/private/json/Potentials/getRecordById?&authtoken=' + authToken + '&scope=crmapi&id=' + requestedId;
var response = UrlFetchApp.fetch(zohoRequestUrl);
var sanitizedResponse = (response.getContentText());
/*Sanitize json*/
var output = JSON.parse(sanitizedResponse);
Logger.log(output);
/*Declare the variables you want to print*/
var parsedOutput = output.response.result.Potentials.row.FL;
var recordObj = {}
Logger.log(typeof output)
Logger.log(output.response.result.Potentials.row.FL.length)
for (var i = 0; i < output.response.result.Potentials.row.FL.length; i++) {
if (output.response.result.Potentials.row.FL[i].val == 'Potential Name') {
recordObj.potentialName = output.response.result.Potentials.row.FL[i].content
}
}
return (recordObj);
}
Index.html
<html>
<head>
<base target="_blank">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Purchase Order</title>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<div>
Quote: <span id="job-number"><?= data.potentialName ?></span>
</div>
<div>
Potential Name: <?= data.potentialName ?>
</div>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<!-- Load jQuery, jQuery UI, and Bootstrap libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.split(":");
var thePart = selectedPart[0];
return (thePart);
}());
</script>
This particular code retrieves the HTML element but not the innerHTML text
var parts = document.getElementById('job-number');
Instead do this to get the embedded HTML which can used to split the string like so:
var parts = document.getElementById('job-number').innerHTML;
The final code will look like this:
<script>
//Format Job Numbers - return only last six characters in potentialName string
(function() {
var parts = document.getElementById('job-number');
var selectedPart = parts.innerHTML.split(":");
console.log(parts)
console.log(selectedPart)
var thePart = selectedPart[1];
parts.innerHTML = thePart
return (thePart);
}());
</script>
There is limited information on how the object structure looks like? The assumption here is there is six character before ":" in the data.potentialName value. if you rather want exactly six characters you can do this:
var selectedPart = parts.subString(0,6)
Hope that helps!
NOTE: Need to implement this without the use of jQuery or any other open source code.
Here is what I have
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Model</title>
<script src="js.js"></script>
</head>
<body>
<h1>Browse all our products below:</h1>
Name: <span id="name"></span><br>
Desc: <span id="desc"></span><br>
Cost: <span id="cost"></span><br>
Stock: <span id="stock"></span>
</body>
</html>
js.js is below
var getProducts = function(){
console.log("Getting Products...");
var success = function() {
var product = JSON.parse(xhr.responseText);
console.log(product);
document.getElementById("name").innerHTML = product.name;
document.getElementById("desc").innerHTML = product.desc;
document.getElementById("cost").innerHTML = product.cost;
document.getElementById("stock").innerHTML = product.stock;
}
};
xhr = new XMLHttpRequest();
xhr.open("GET", "back.php");
xhr.addEventListener("load", success);
xhr.send();
};
window.addEventListener("load", getProducts);
back.php returns the following from a database. They have been json_encoded:
{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"}
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"}
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}
I need to display these objects onto the html page. I know I need to implement a for loop however, no matter whatever I try, a parse error for JSON comes up.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at
line 1 column 86 of the JSON data
var product = JSON.parse(xhr.responseText);
Would much appreciate it if someone could help me understand how to display all the JSON objects onto the html page.
Your JSON is invalid. You need to put the objects in an array, and separate them by commas.
[{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"},
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"},
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}]
Here is an example using open source project jinqJs
Also the example is using jQuery.
Fiddle Example
//data can also be a string to a url that returns JSON
jinqJs().from(data).select(function(row) {
$('#items')
.append($("<option></option>")
.attr("value",row.nam)
.text(row.desc));
}
);
So I have a very simple HTML page called Terms.html. Here is the output:
Museums, Parks, Railroads and Trains, Shopping, Theatres
and here is the code:
<!DOCTYPE html>
<html>
<body> Museums, Parks, Railroads and Trains, Shopping, Theatres </body>
</html>
Now, I am using jQuery $.get method to retrieve this html page:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<script>
var tags = [ "String1", "String2"];
$.get("Terms.html", function(data, status) {
<!-- -->
$(result).html( data );
alert("Status: " + status);
});
</script>
<p>Search terms are: <span id="displayterms"></span></p>
<div id="result"><div>
</body>
</html>
What I want to do is be able to parse Museums, Parks, Railroads and Trains, Shopping, Theatres into individual strings and add them to my var tags array. Any ideas on how I can do this? Thanks
Try:
var tags = ["String1", "String2"];
var str = "Museums, Parks, Railroads and Trains, Shopping, Theatres";
arr = $.map( tags.concat(str.split(',')), function( n ) { return $.trim(n) });
console.log(arr); // Outputs the array ["String1", "String2", "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
jsFiddle example
The third line splits the str on the commas and then uses jQuery's .map() function to trim the whitespace.
With the split function: http://www.w3schools.com/jsref/jsref_split.asp
This will split on any character you choose, in this case ","
tags = data.split(",");
If you don't need to support versions of IE older than 9, you could do something like this:
var tags = document.body.textContent.split(',').map(
function (s) {
return s.trim();
}
);
document.body.textContent gets the text in the body tag. This restricts your browser support, as IE didn't have this until version 9.
.split(',') takes the string and splits it into its component parts, returning an array.
.map() applies a function to everything in the array returned by .split(','), and returns an array of the results. In this case, we use it to call trim() on each string in the array, to strip leading and trailing whitespace. IE didn't have the Array.prototype.map or String.prototype.trim methods until version 9, but they're easy to polyfill. It's the textContent thing above that's trickier.
The array returned from map() is then put into your tags variable.
Instead of storing the contents as HTML, you could store them in a JSON data file.
An example JSON data file (places.json):
{
"Names": [ "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
}
Then, you can change your page code to:
<script>
var tags = [ "String1", "String2"];
$.getJSON("/places.json", function(data) {
$(result).html(data);
console.log(data.Names[0]); // Outputs Museums
$.each(data.Names, function(index, value) {
tags.push(value); // add the tag to your tags list for each item in Names
});
});
</script>
This way you can store just the data you need and you won't need to parse the HTML manually.
I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?
I've tried this in my .twig template:
<script>
$(document).ready(function(){
var test = {{ testArray }};
});
</script>
but that only works if it's a string.
You might have to json_encode the array, try this:
<script>
$(document).ready(function(){
var test = {{ testArray|json_encode(constant('JSON_HEX_TAG'))|raw }};
});
</script>
First, send the data json encoded from controller and
then in javascript,
var context= JSON.parse('{{ YourArrayFromController|raw}}');
I do it this way:
Return of the controller test.data then
$test = array('data' => array('one','two'))
Twig:
<div id="test" data-is-test="{{ test.data|json_encode }}"></div>
Js:
$(document).ready(function() {
var test = $('#test').data("isTest");
console.log(test);
});
Output:
["one", "two"]
documentation here
json_encode works well, in combination with the raw filter.
<script>
$(document).ready(function(){
let test = {{ testArray | json_encode(constant('JSON_HEX_TAG')) | raw }};
});
</script>
Don't forget the JSON_HEX_TAG flag.
Otherwise, you can get broken HTML. A string containing <!--<script> is a good way to test that.
In My Controller I Install SerializerBundle
$serializer = $this->get('serializer');
$countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
$jsonCountries = $serializer->serialize($countries, 'json');
return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));
And In My File Twig
<script type="text/javascript" >
var obj = {{ countries|json_encode|raw }};
var myObject = eval('(' + obj + ')');
console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
</script>