Display JSON data on HTML page - javascript

This project is dealing with database of scientific papers and citations.
I correctly implemented some PHP to use a users input (DOI) and search our database and pass the data to javascript. The javascript gets the data like so:
function getMETA() {
var json = <?php echo json_encode($data); ?>;
}
Using an HTML form with an onClick="getMETA()" the variable is correctly filled with the data and here is an example:
var json = [{"doi":"10.1103\/PhysRevB.79.054101","pub_date":"2009-02-02","journal":"Phys. Rev. B","title":"Absence of superconductivity in the high-pressure polymorph of MgB_{2}","authors":"Y. Ma, Y. Wang, and A. R. Oganov","metainfo":"79, 054101 (2009)"}];
This database query just contains meta data of the paper selected, I want to just display it on the webpage. This is what I tried:
Title: <span id="title"></span><br />
Authors: <span id="authors"></span><br />
Publish Date: <span id="pubdate"></span><br />
Journal: <span id="journal"></span><br />
Then I used document.getElementById("journal").innerHTML but this is not working at all. I even tried to just set it to a string like so: document.getElementById("journal").innerHTML = "test"; and nothing is displayed on the webpage. I also tried this as a test:
HTML:
<span id="title">TEST</span>
JAVASCRIPT:
var val = document.getElementById("title").innerHTML.value
alert(val);
And I get an alert box that says "undefined"
How can I get this document.getElementById to work? Or do you recommend another way to parse and display the json data on the webpage? Maybe in a border-less table format?
Thanks!

You're likely trying to query #title before it's actually available. To ensure a reference to the DOM element you're after gets returned when you ask for it, execute your code inside a DOMContentLoaded handler:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('title').innerHTML = 'test';
});

Make sure you're running your Javascript after the DOM has been loaded:
$(document).ready(function() {
$("#title").text("test");
});
Plain JS:
window.onload = function() {
document.getElementById("title").innerHTML = "test";
};

This would be because document.getElementById("title").innerHTML is returning a string.
It does not have a value property.
http://jsfiddle.net/UAQFJ/1/

Try this:
$.each(json[0],function(f,v){
$("body").append("<div class='row'><span class='field'>"+f+": </span><span class='value'>"+v+"</span></div>");
})
DEMO here.

http://jsfiddle.net/KkgS7/
The jsfiddle shows what I currently have. Here is the full code in the order on my HTML page:
<script type="text/javascript">
function getMETA() {
var json = <?php echo json_encode($data); ?>;
}
document.addEventListener('DOMContentLoaded', function(json) {
document.getElementById("title").innerHTML = "test title";
document.getElementById("authors").innerHTML = json[0];
document.getElementById("pubdate").innerHTML = json[0];
document.getElementById("journal").innerHTML = json[0];
});
</script>
</head>
<body>
<h1>PRAEDICIT</h1>
<h2>How successful your paper will be?</h2>
<form name="inputdoi" id="doi_input" action="" method="post">
<input name="doi_input" id="searchfield" placeholder="Search by DOI" />
<input type="submit" id="button" name="submit" value="Look Up" onclick="getMETA()" />
</form><br><br>
Title: <span id="title">test title</span><br />
Authors: <span id="authors"></span><br />
Publish Date: <span id="pubdate"></span><br />
Journal: <span id="journal"></span><br />
The "test title" correctly writes to the HTML as you can see. I know that json[0] is not the correct way to get the object out of the json data, this is the last step I need that I can't figure out.
Am I able to pass the json variable like that from getMETA to the new function? Assume the json variable looks like the example in the first post:
var json = [{"doi":"10.1103\/PhysRevB.79.054101","pub_date":"2009-02-02","journal":"Phys. Rev. B","title":"Absence of superconductivity in the high-pressure polymorph of MgB_{2}","authors":"Y. Ma, Y. Wang, and A. R. Oganov","metainfo":"79, 054101 (2009)"}];
The Webpage Shows this after looking up a paper:
Title: test title
Authors: undefined
Publish Date: undefined
Journal: undefined

Related

Calculate input of html text fields with php

At the moment, I try to create a survey in a webpage. At the end of the survey, users are able to fill two text fields with values. With these values, my plan is to calculate an output, displayed for them at the same page. So:
Input: a
Input: b
Result: ab+b-ab (do not concentrate this please, its just an example)
My plan is that the user is able to fill the two input fields and by a buttonclick, a php function is calculating the result field (by my own algorithm depending on input - this is already working) and fills this field. Do i have to link to another webpage for this purpose?
And how is it possible to grab the two input values and give it to my php function?
And as last thing, how is it possible to start a php function either embedded in html or in an own file?
I tried your solution and some others as well (fetching inputA and inputB from the DOM with document.getElementById does not work. Below is my code
<form>
InputA:<br>
<input type="text" id="inputA"/></br>
InputB:<br>
<input type="text" id="inputB"/></br>
Output:<br>
<input type="text" id="output"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
<script type="text/javascript">
$("#calculate").click(function(){
$.get( "submit.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
</script>
submit.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$output = $value1 + $value2;
echo($output);
}
?>
When I check with firebug the error, i get a: no element found exception in both (html and php) files. Seems like the problem is, that with: value1: $("#inputA").val(); no value is givent to the server or it can not be handled there.
If i grab the value from the DOM, I can "bring" the value inside the .click function but there is still a "no element found exception" by calling the submit.php.
I have no idea what i am doing wrong, any suggestions? Do i need to install/bind anything in for using JQuery?
After some additional changes, it finally worked (one thing was the header line in the submit.php file):
<form>
WorkerID:<br>
<input type="text" id="workerId"/></br>
CampaignId:<br>
<input type="text" id="campaignId"/></br>
Payment Code:<br>
<input type="text" id="payCode"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript">
$("#calculate").click(function(){
$.get( 'submit.php', { wId: $('#workerId').val(), cId: $('#campaignId').val()} )
.done(function( data ) {
$('#payCode').val(data.payCode);
});
});
and submit.php:
<?php
header('Content-Type: text/json');
$workerId = $_GET['wId'];
$campaignId = $_GET['cId'];
$payCode = $campaignId . $workerId;
$result = array("status" => "success",
"payCode" => $payCode);
echo json_encode($result);
?>
To simplify, i am using jQuery, doing this in vanilla JS is a real pain in the a** in my opinion.
You can use .get(), which is the GET shorthand for .ajax().
With that code, you bind a handler on your submit button and make a AJAX request to your PHP and fill the result your PHP gives into your result field asynchronously.
$("#calculate").click(function(){
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
Also change your submit to something like this:
<input name="go" type="button" value="Calculate" id="calculate" >
Like that, your button won't submit a form and therefore synchronously load your PHP.
Since you seem new to JavaScript and you had this comment
my button, but here i got redirected to submit, no idea how i can go back to page before with filled textfield
in your question, i'll tell you, JavaScript works while the DOM (Document Object Model) is loaded, means you can access your elements when already loaded and alter them.
Getting the value of a input is as easy as that in jQuery:
$("#inputA").val();
With the AJAX you get what your php will return in data.
// the { value1: $("#inputA").val(), value2: $("#inputB").val() } object
// is what you send to your PHP and process it
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
// data is what your php function returned
});
Using JS you can now change your elements as just said, effectively meaning to change the value of your output here:
$("#output").val(data);
"Working" Example: JSFiddle (There is no PHP to access to, so it will not do anything actively)

How can I avoid using hidden fields to pass data from PHP to Javascript?

I am developping a website with some serious Javascript involved and I have to use generated data from PHP in my JS code.
For example, to be able to use my page ID in JS, I proceed like this:
<input type="hidden" id="pageId" value="<?php echo $page->getId() ?>" />
<button id="runJs">RUN</button>
And in my javascript (with jQuery):
$(function() {
$('#runJs').click(function() {
var id = $('#pageId').val();
});
});
It works, but is there a cleaner way to do it?
Since HTML5, one can now add user-made attributes to any HTML tag as long as it starts with data-.
In HTML5:
<button id="runJs" data-pageId="<?php echo $page->getId() ?>">RUN</button>
In JS:
$(function() {
$('#runJs').click(function() {
var id = $(this).attr('data-pageId');
});
});
Or, as said Eric Martinez in the comments, using jQuery:
var id = $(this).data('pageId');
Passing data this way is cleaner for two reasons:
It is not using a side tag that could be confusing.
The data you pass is included in the button, which means another button with its own data-XXX can use the same JS function, even on the same page.
Example
HTML:
<button data-value="5">Square it!</button>
<button data-value="7">Square it!</button>
<button data-value="12">Square it!</button>
JS:
$(function() {
$('button').click(function() {
var value = $(this).attr('data-value');
alert(value * value); // Shows 25, 49 or 144 depending of the button pressed.
});
});
The function doesn't know the button. The buttons don't even need an ID as long as JS is involved.
You can create variables inside the tag. Like this:
<script>
var pageId = '<?php echo $page->getId(); ?>';
</script>
Later in your script:
$(function() {
$('#runJs').click(function() {
var id = pageId;
});
});

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

reading a drag and drop ordered list via JavaScript

I have an application (drag and drop using JqueryUI.GridSort) that allows the user to upload photos, and then sort the photos in the order that they would like using drag and drop.
On page load, the user is prompted to upload photos which are posted to the next page. When they arrive on the next page my php script creates a <ul id="sortable"> containing <li> for each of the files they uploaded. For each picture that they have uploaded to the site, a new <li> is created. Inside of that <li> is a <img> that sets the picture for <li> with the image they have uploaded.
My goal is to be able to "save" the order of the pictures after they have arranged them in the drag and drop interface. For example, once they have finished arranging and sorting the pictures in the order they want them in, I would like to be able to send them another page that creates an xml file ( I don't need help with the XML, only saving the order) with using the list that they created in the correct order.
After hours of tinkering with PHP, I have come to realization that because PHP is a serverside language, it cannot see what is sorted post render. So my question is, is there a way to have JavaScript or Ajax read the current order of the list, and post it to the next page? If you do know how, could you please provide an example of both the POST from one page, and the post receiving on the other? I am not very familiar with Ajax.
Thank you greatly for any assistance you could provide.
Sample Code (The contents of the foreach statement that creates a LI for each file uploaded)
$imgID++;
echo '<li class="ui-state-default"><img id="'.$imgID.'"'.' src="user_files/'.$file_name.'" draggable="true" height="90" width="95"></li>';
EDIT
main page :
<script>
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
</script>
<div id="tesT">
<form id="my_form" action="update_data.php">
<!-- other fields -->
<input type="hidden" id="ordered_list_data"></input>
<input type="submit" value="Proceed to Step 2"></input>
</form>
</div>
update_data.php:
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
echo "1";
} else {
echo "nodata";
}
// do things with the data
?>
I built a JSFiddle doing basically the same thing that David posted.
I added a piece to write out the result to a div on the page, so you can see what's going on:
<input type="button" id="savebutton" value="save"/>
<div id="output"></div>
<form id="listsaveform" method="POST" action="script.php">
<input type="hidden" name="list" id="hiddenListInput" />
</form>
Javascript:
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
$( "#savebutton" ).click(function() { LISTOBJ.saveList(); });
});
var LISTOBJ = {
saveList: function() {
var listCSV = "";
$( "#sortable li" ).each(function() {
if (listCSV === "") {
listCSV = $(this).text();
} else {
listCSV += "," + $(this).text();
}
});
$("#output").text(listCSV);
$("#hiddenListInput").val(listCSV);
//$("#listsaveform").submit();
}
}
If you're using a <form> you can do something like this (assuming jQuery is being used):
$('#my_form').on('submit', function() {
var ordered_list = [];
$("#sortable li img").each(function() {
ordered_list.push($(this).attr('id'));
});
$("#ordered_list_data").val(JSON.stringify(ordered_list));
});
In essence, what you're doing is looping over the <ul>, fetching each <img> and appending the ids (in order of appearance) to an array. Arrays preserve ordering in JavaScript and JSON, so one can turn it into a JSON string using the JSON.stringify function, set it as the value of a <input type="hidden"> field and then submit the form.
If you want to use AJAX, the functionality is very similar. However, instead of using an onsubmit (or onclick) you'd use $.post.
Let's go with the <form> option since it's simpler. All told you'll have something similar to the above JS along with HTML like this:
<form id="my_form" method="post" action="./update_data.php">
<!-- other fields -->
<input type="hidden" name="ordered_list_data" id="ordered_list_data"></input>
<input type="submit" value="Submit"></input>
</form>
Then, in update_data.php (or whatever your script is named):
<?php
// process other fields as normal
if(isset($_POST['ordered_list_data'])) {
$img_ordering = json_decode($_POST['ordered_list_data']);
} else {
// handle case where there is no data
}
// do things with the data
?>

Sending form array values trought ajax

So my php needs 2 values, operation => string and data => array. The following is the form (dynamically generated inputs) :
<form method="post" action="/operations.php">
Title: <input type="text" value="valuehere" name="data[title]">
.
.
.
Description: <textarea name="data[description]"></textarea><br>
<button class="btn janitor_edit" type="submit">Edit Media</button>
<input type="hidden" value="operateMePls" name="operation">
<input type="hidden" value="254" name="data[id]">
</form>
And now I have to create an array from all data[xyz] in the form, but I'm having trouble finding a way to do so. The closest I've come to was doing like so: link
I must store the array as key/values, no other way, so I can ajax_request = { operation: operation_input, data : input_array_data };.
Oh, and the form works as expected when submiting "normaly" trought POST.
If the form works by itself, then let jQuery take care of it converting the data into a form suitable for XHR for you.
data: $('#your_form').serialize();
I've used an object instead of an array. When you json_decode in PHP, pass "true" as your second argument, and the data will come out as an array. I think this is what you wanted. Please comment if you were looking for something different.
$(".janitor_edit").click(function () {
var data = {};
data.operation = $("input[name='operation']").val();
data.data.id = $("input[name='data\\[id\\]']").val();
data.data.title = $("input[name='data\\[title\\]']").val();
data.data.description = $("input[name='data\\[description\\]']").val();
});

Categories

Resources