Image tag won't accept src - javascript

I am trying to make an image take a value in as a source, after the image tag (and a related radio button) has been created using JavaScript. I have discerned the following from testing and alert outputs:
If the image src is provided at the creation of the image tag using an exact filepath, it will show the image correctly (e.g. src='images/0.jpg'). However, this is not helpful since I need it to work for any given image, not a specific one.
If the image src is provided at the creation of the image tag using a variable containing a filepath, it fails to generate the image tag or the radio button at all (e.g. src='" + result + '").
NOTE: The last example is not present in the code below. The result was found by moving the '$.post' section to the line directly under the 'out +=' line within the for loop.
If the image src is left blank at the creation of the image tag, the image tag and radio button are created, though the image is blank as expected. If I then try to use 'getElementByID(imgID).src' to change the image source after this, it fails to do anything. ('imgID' here is an example, not what the code says).
On top of the above, using alerts and dumping info into divs indicate that the comicID is being correctly posted, and the filepath of the image src is definitely being found, and is being copied into the variable 'result' correctly, even one line before the creation of the tag or the attempt to edit it using 'getElementById'.
At this point I'm stumped, I don't know what could logically be stopping the src from reading in.
--
Javascript:
<script>
// Loads the user's comic list 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)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
tempID = (arr[j].comicID);
$.post("getCover.php", {comicID:tempID}, function(result)
{
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
);
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print_r($row["pageLocation"]);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
To my knowledge, loadList.php is working perfectly, so I didn't list its code to keep things relevant.

I copied your code and tweaked it a little so I could run it without the web services and it works great. Here is the HTML page I created:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
// JSON parsing for 'loadComic'.
function loadComicJSON()
{
var arr = [{comicID: 1},{comicID: 2},{comicID: 3}];
var result = "monkey.jpeg";
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
var imgSrc;
tempID = (arr[j].comicID);
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
}
}
</script>
</head>
<body>
<div id="loadList"></div>
<button onclick="loadComicJSON()">Try it</button>
</body>
</html>
As you can see, I created an array of JSON objects that hold the comicID and am statically creating the image as 'monkey.jpeg'.
The code works so there is either an issue with the 'response' that you pass into your loadComicJSON method or the result from your POST method.
Add a couple of console.log statements and look at the two values I mentioned and you will likely see the issue.

Solved the issue myself. It turned out that the $.post needed to be $.get and that it needed to technically be outside of a loop (i.e. in its own function) to work properly. Works fine now after that and a couple minor tweaks.

Related

Passing generated id from one page to another

I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}

Javascript - InnerHTML doesn't edit the DOM

I'm working on a project with Laravel. Now I'm coding the feature which prints all activities responsible. Before I was using foreach loop in PHP to print all of my activities (from the DB).
But now I have to use JS to print these activities because I want to add a filter (and avoid page to reload).
I have created this script in my view :
<script>
containerE = document.getElementById("container");
var request = new XMLHttpRequest();
request.open("GET","{{route('APIManifs')}}", false);
request.send(null);
responses = JSON.parse(request.responseText);
function expandResults(value){
for (var i in responses){
if (responses[i].status === value) {
containerE.innerHTML = containerE.innerHTML +
"<div class=\'col-md-5 offset-1\' id=\'1\'>" +
"<div class=\'card\'>" +
"<a href='/manif/" + responses[i].id + "'"+" ><div class=\'card-header\' style=\'text-align: center\'>"+
"<img src='"+responses[i].image+"'><br>"+
responses[i].name+" | "+responses[i].date_add+"<br>"+
"</div> </a>"+
"<div class=\'card-body\'>"+
"Nom : "+responses[i].name+"<br>"+
"Description : "+responses[i].description+"<br>"+
"</div>"+
"</div>"+
"</div>";
containerE.innerHTML = containerE.innerHTML + "Arg";
console.log(responses[i].status+"=="+value);
}
else{
console.log(responses[i].status+"<>"+value);
}
}
}
</script>
I got the information but impossible to print my HTML in the DOM! When I copy paste the inner HTML code in the console it's work.
Do you have any ideas on how to accomplish this?
Thank's in advance!

I'm having issues with an API

I'm having issues with getting this API to work.
I have used the same code with Google Finance API and that works perfectly. The issue is that I can only get a small amount of stocks out, and in the long run, I need to run 12000 stocks through (if possible).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var temp = [];
$(document).ready(function(){
stockInformation();
setInterval(stockInformation, 5000);
});
function stockInformation()
{
$.ajax({
url:"https://api.website.com/public/user/token/stock/SDRL/quote",
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"quote"
});
var i = 0; var j = 0;var status = "";
quote = function(data){
var output = "<table>"
$.each(data, function(key, value){
if (value.l_cur > temp[j])
status = "<td style=color:green>Up</td>";
else if (value.l_cur < temp[j])
status = "<td style=color:red>Down</td>";
else
status = "<td>Same</td>";
j++;
output += "<tr><td>" + value.t + "</td><td>" + value.l_cur + "</td>" + status + "</tr>";
temp[i] = value.l_cur;i++;
})
output += "</table>";
$("#result").html(output);
}
}
</script>
<div id="result"></div>
This is what the API returns (not with the code above):
{"timestamp":"1503691321","datetime":"2017-08-25 16:02:01 (UTC)","price":"6.17","price change":"0.12","price pct change":"1.98","open":"6.09","volumn":"1852887","low":"6.00","high":"6.22","currency":"USD"}
Many of googles api's limit the number of requests you can make in a given amount of time. Sometimes even as low as 50 per month depending on the api and the type of request. Its doesn't look like there is anything wrong with the way you are using the api in your code.
You could get around that though potentially by paginating. Start with like 30 at a time then when your user clicks a next button or scrolls to the end of the page then go get the next 30.

Avoid duplicated function call in jquery?

I have build a function getuser() in which I recieve json data from php into javascript. I call this function when document gets ready. My problem is that I am also using jquery post for live updation of that record and for that reason I have to call that function getuser() again due to this it shows duplicate result. First when document gets ready socend on jquery post function.
HTML
<!--It has onclick event-->
<button type="submit" class="btn btn-primary modify" onclick="update_user()">UPDATE</button>
JQUERY
//This is function which gets json array from php
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
//This is jquery post. When I click button (in html section) it will get form values and sent to php page
//in return it will call getuser() function again which results of duplicate display of record
$(document).ready(function(){
$('.modify').click(function() {
var gender = '';
if($('.male').is(':checked')){
gender='Male';
}else{
gender='Female';
}
$.post("update.php",
{name: $('.name').val(),gender:gender,city:$('.city').val(),age:$('.age').val(),id:$('.id').val()},
function (data) {
//here is the function call again
getuser();
}
);
});
});
Kindy tell me that is there any way I avoid second call in post function and the record gets update without function call again.I need to avoid duplicate result. Thanks in advance!
First off, you need to read the docs on jquery document ready, and learn the difference between a function reference and actually calling a function. document.ready expects you to pass in a function definition to be called when the page is ready. It doesn't actively tell you if the page is ready, the first way you're calling it. The second way you're calling it is actually correct.
Second, replace $("#output").append with $("#output").html, which will update/replace the contents of that element every time, instead of just adding more and more.
Your if test will always return true because document.ready returns the JQuery object. So, you are always causing the call to getuser() to happen.
You can see the return value from document.ready() here:
console.log($(document).ready());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is an incorrect usage of document.ready(). You don't need to write a test for document.ready, just write a callback function for that event and let the browser do it correctly for you.
Read the docs on document.ready()
Solution:
This:
//when document gets ready it will show the record
if($(document).ready()) {
// getuser();
getuser();
}
Should be this:
//when document gets ready it will show the record
$( document ).ready(getuser);
Or even:
$(getuser);
As for you getting the results a second time, just overwrite the old results instead of appending them.
This: $("#output").append(...
Should be: $("#output").html(...
All of you thanks for your suggestions. I have found the solution here by just adding $("#tbody").html(''); in getuser() before loop. Here is the code which works fine for me
function getuser() {
$.get("getuser.php", function (data) {
var data = JSON.parse(data);
$("#tbody").html('');//newly added
for (var i = 0, len = data.length; i < len; ++i) {
var student = data[i];
var slash = " / ";
$("#output").append("<tr><td>" + student.name + "</td><td>" + student.gender + "</td><td>" + student.age + "</td>" +
"<td>" + student.city + "</td><td><a href='#' style='text-decoration: none' class='update' id='" + student.id + "' onclick='reply_click(this.id)'>Update</a>" + slash + "<a style='text-decoration: none' href='#'>Delete</a></td></tr>");
}
});
}
All of you thanks again!

Append image in function jquery

Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.

Categories