Getting an image source from JSON data - javascript

I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.

You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.

Related

Suggest a way to store the value form csv into dropdown with javascript variable perform operations on it

<script> //script loading the csv and reading the files to out into an array of variables which are used in dropdown
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(","); //split to separate the column inside the csv
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
document.getElementById("try").innerHTML = "Value: "+ $colData; //just to check the value
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $values = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $values += $colNames[$b] + ': <input id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" value="' + $csvData[$a][$colNames[$b]] + '" /><br />';
}
document.getElementById("fields").innerHTML = $values;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
</script>
Currently I have two columns in csv and need to pick the value of one of the column item. Which is selected upon the dropdown selected by the user and then need to modify the value. The $values variable stores both the columns values.

Using PHP to populate Javascript Variables

I'm trying to populate a Drop-Down menu from a csv file located on a network share.
I've come as far to get the file to create all the options successfully when the file is in the wwwroot folder however, now I'm faced with the external url reference issue.
Ajax does not support local File:/// directories and when attempting to use the network share location it also fails: \\Server\Folder\File.csv
Is there any way to read the data from the csv file using php or other server-side language in order to perform my work on the data?
Code Below for your reference:
<script>
function SubmitBy(){
$.ajax({
url: encodeURI('./PrinterLookup.csv'),
success: function(data) {
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Looking for something like this,,, to bypass the ajax url limitation:
<script>
function SubmitBy(){
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = $Data;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Any assistance on this will be greatly appreciated.
Thank you in advance.
in this line var data = $Data; you need to print $Data see below
<script>
function SubmitBy(){
<?php
$Datapath = "file:///Server/Folder/Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = <?php echo $Data; ?> //correction here
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Please check first this is .php file .
If this is .php file.
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
<script>
function SubmitBy(){
var data = <?php print_r( $data ); ?>;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>

Displaying data stored in HTML session storage into page

I am trying to create a checkout page to send a confirmation to the customer of the products they want to buy. However, I am having trouble to display the data stored in the session storage into my checkout page. Whenever I click on the checkout button, the page only displays the title, and it doesn't display the data. Can somebody help me figure out this problem. I would really appreciate it.
HTML
<div id="show_checkout">
<h1 id="basket_header">- My Basket -</h1>
<!-- The items the user wants to buy, will be displayed on this table -->
<table id="basket_list"></table>
<!-- Displays the checkout and empty buttons -->
<div id="basketDiv"></div>
</div>
JavaScript
window.onload = loadBasket;
//Displays basket in page.
function loadBasket() {
//Get basket from local storage or create one if it does not exist
var basketArray;
if (sessionStorage.basket === undefined || sessionStorage.basket === "") {
basketArray = [];
} else {
basketArray = JSON.parse(sessionStorage.basket);
}
var tableBody;
var tableHeader = "<tr><th>Product Image</th><th>Product Name</th><th>Price</th></tr>\n";
//Build string with basket HTML
var htmlStr = "<p class='basket_items'>Number of items in basket: " + "<span style='color:red'>" + basketArray.length + "</span>" + "</p>";
var prodIDs = [];
for (var i = 0; i < basketArray.length; ++i) {
tableBody += "<tr><td>" + "<img class='basket_img' src='" + basketArray[i].image + "'>" + "</td><td>" + basketArray[i].name + "</td><td>£" + basketArray[i].price + "</td></tr>";
prodIDs.push({
id: basketArray[i].id,
count: 1
}); //Add to product array
}
//Add hidden field to form that contains stringified version of product ids.
htmlStr += "<input type='hidden' name='prodIDs' value='" + JSON.stringify(prodIDs) + "'>";
//Add checkout and empty basket buttons
htmlStr += "<input class='checkout_button' onclick='checkoutBasket()' type='submit' value='Checkout'>";
htmlStr += "<button class='empty_basket' onclick='emptyBasket()'>Empty Basket</button>";
//Display number of products in basket
document.getElementById("basketDiv").innerHTML = htmlStr;
document.getElementById("basket_list").innerHTML = tableHeader + tableBody;
}
//Deletes all products from basket
function emptyBasket() {
sessionStorage.clear();
loadBasket();
}
function checkoutBasket() {
// Create request object
var request = new XMLHttpRequest();
// Create event handler that specifies what should happen when server responds
request.onload = function() {
// Check HTTP status code
if (request.status == 200) {
var responseData = request.responseText;
document.getElementById("show_checkout").innerHTML = responseData;
} else
alert("Error communicating with server: " + request.status);
}
// Set up request with HTTP method and URL
request.open("POST", "php/checkout.php");
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Send request
request.send();
}
PHP
<?php
//Extract the product IDs that were sent to the server
$prodIDs = filter_input(INPUT_POST, 'prodIDs', FILTER_SANITIZE_STRING);
//Convert JSON string to PHP array
$productArray = json_decode($prodIDs, true);
//Output the IDs of the products that the customer has ordered
echo '<h1 id="basket_header">- My Order -</h1>';
for($i=0; $i<count($productArray); $i++) {
echo '<p>Product ID: ' . $productArray[$i]['id'] . '. Count: ' .
$productArray[$i]['count'] . '</p>';
}
?>

$.getJSON always failing

Apologies if this has been answered before but I couldn't find what I was looking for. So, I use $.getJSON to send some variables to a php file. The file returns success as true but for some reason always triggers the .fail function.
The weird thing is, it all works fine on my laptop, just not on the computer at university. Connection to the database is fine, like I said everything works and it returns all the correct data but doesn't trigger the success function.
JQuery:
function request_user_review() {
$.getJSON("user_review_list.php", success_user_review).fail(fail_user_review);
}
function success_user_review(response) {
if (response.success) {
var user_review_list = "";
$("#user_reviews .review_cafe").remove();
$("#user_reviews .review").remove();
$("#user_reviews .rating").remove();
$("#user_reviews .review_choice").remove();
for (var i = 0; i < response.rows.length; i++) {
var review_cafe = '<tr id="row_' + response.rows[i].id + '"><td class="review_cafe">'
+ response.rows[i].cafe + '</td>';
var review = '<td class="review">'
+ response.rows[i].review + '</br>Review left: ' + response.rows[i].date + '</td>';
var rating = '<td class="rating">'
+ response.rows[i].rating + '/5</td>';
var review_choice = '<input type="hidden" class="cafe_id" value="' + response.rows[i].cafe_id + '" /><td class="review_choice"><button onclick="request_edit(this.id)" id="edit_' + response.rows[i].id + '" class="btn_edit">Edit</button><button onclick="request_delete_review(this.id)" id="delete_' + response.rows[i].id + '" class="btn_delete">Delete</button></td></tr>';
user_review_list += review_cafe + review + rating + review_choice;
}
$("#user_reviews").html(user_review_list).trigger("create").trigger("refresh");
} else {
$("#review_message").html("Review failed to be loaded!").trigger("create").trigger("refresh");
}
}
function fail_user_review() {
$("#review_message").html("Connection down?").trigger("create").trigger("refresh");
}
PHP:
<?php //user_review_list.php
require_once "sql.php"; //connection to database and query is handled here
require_once "logged_in.php";
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors','On');
$session_id = $_SESSION['userid'][0];
$result = array();
$result['success'] = false;
$query = "SELECT * FROM reviews WHERE user = $session_id;";
if ($result_set = Sql::query($query)) {
$result['success'] = true;
$result['message'] = "Your Reviews" ;
$rows = mysqli_num_rows($result_set);
$result['rows'] = array();
for ($i = 0; $i<$rows; $i++) {
$tmpRow = mysqli_fetch_assoc($result_set);
$php_date = strtotime($tmpRow['date']);
$formatted_php_date = date('M d, Y', $php_date );
$tmpRow['date'] = $formatted_php_date;
$result['rows'][$i] = $tmpRow;
}
} else {
$result['message'] = "Failed to read Reviews" ;
}
print(json_encode($result));
Thanks
James
The messages you get mean you're trying to parse something that's already JSON. My earlier statement about parsing JSON is not going to be of much help here because you're not just getting back a string that needs to be converted to JSON -- which you really shouldn't be with $.getJSON().
You're getting back a JSON with an invalid encoding somewhere along the line, so trying to parse it won't help you. Validate your JSON first and foremost (the error could be due to your differing server settings between machines) using jsonlint, and continue from there.

XML or text declaration not at start of entity error - PHP and Javascript

Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.

Categories

Resources