Javascript - InnerHTML doesn't edit the DOM - javascript

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!

Related

How can I run a function on page load and then after click?

hi this is my very first time using jquery on any project at all. I am needing a little help if someone can
on my page i have some code to load a json file this file contains menu details for the main menu such as
name / action / poster
this is my code
var Items = "";
var flixAPI = "https://example.com/api.php?action=MAIN";
$.getJSON(flixAPI, function (data) {
$.each(data, function (i, item) {
Items += "<div class='img'>";
Items += "<a target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='"+ item.POSTER +"' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
i can get this code working when i place it into the document ready.
my issue is after the main menu is populated and added to the page i then need to stop the page redirecting when a href link is clicked and get the value of the href link to then send another get json request to load the next page
i have tried loading the main menu on the document ready and then sticking one call into a .click binding to load the next set of items based on the href link clicked but when i try do this inside or outside the document ready the .click binded function wont work
Put the code in a named function so you can call it from both places.
function getFlix(flixAPI) {
var Items = "";
$.getJSON(flixAPI, function(data) {
$.each(data, function(i, item) {
Items += "<div class='img'>";
Items += "<a class='menu-link' target='_blank' href='" + item.ACTION + "'>";
Items += "<img src='" + item.POSTER + "' alt='" + item.NAME + "'>";
Items += "</a>";
Items += "<div class='desc'>" + item.NAME.substr(0, 16) + "</div>";
Items += "</div>";
});
$('#content').html(Items);
});
}
$(document).ready(function() {
getFlix("https://example.com/api.php?action=MAIN");
$("#content").on("click", ".menu-link", function(e) {
e.preventDefault();
getFlix(this.href);
});
});
This uses event delegation because the menu links are added dynamically. See Event binding on dynamically created elements?
You would need to identify the menu items with either classes or id's.
Then you would have to define the onClick event for each one of those who you need to fetch the JSON for.
ON the onClick event, you need to use e.stoppropagation or e.preventdefault (check the usage online) and then use ajax to fetch the JSON and populate whatever you are populating.

Fix Youtube api data pagination v3

I got a so far as good working youtube api data v3 search script but i was so in trouble with this script since days i think im blind it works and paginates everytime 2 entries. But there must be a failure in the js or html code should be easy but i cant figure out please help me. Demo Link is aviable under
Artist search Battle Rap Net Youtube Search
This is the Code so far i used please take a look at the demo link to understand the problem.
The Js Code:
var nextPageToken, prevPageToken;
var firstPage=true;
$(document).ready(function()
{
$('#searchbutton').click(function()
{
// Called automatically when JavaScript client library is loaded.
// alert('i am clicked');
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
// Called automatically when YouTube API interface is loaded .
// Called automatically with the response of the YouTube API request.
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page"+nextPageToken+"</button></div>");
});
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page "+prevPageToken+"</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page "+nextPageToken+"</button></div>");
$('#nextPageButton').click(function()
{
// alert('i am clicked');
console.log(nextPageToken);
searchYouTubeApi(nextPageToken);
});
$('#prevPageButton').click(function()
{
// alert('i am clicked');
console.log(prevPageToken);
searchYouTubeApi(prevPageToken);
});
});
function onYouTubeApiLoad()
{
// See to get a key for your own applications.
gapi.client.setApiKey('MYAPICODE');
searchYouTubeApi();
}
function searchYouTubeApi(PageToken)
{
var searchText= $('#searchtext').val();
//$('#response').append("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
$('#response').replaceWith("<div id=\"searching\"><b>Searching for "+searchText+"</b></div>");
// Use the JavaScript client library to create a search.list() API call to Youtube's "Search" resource
var request = gapi.client.youtube.search.list(
{
part: 'snippet',
q:searchText,
maxResults:2,
pageToken:PageToken
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
// $('#response').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page return from request execute method is: "+nextPageToken+"</button></div>");
}
function onSearchResponse(response)
{
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken=response.nextPageToken;
prevPageToken=response.prevPageToken;
// document.getElementById('response').innerHTML += responseString;
//$('#response').append("<div id=count><b>Found "+resultCount+" Results.</b></div>");
$('#count').replaceWith("<div id=count><b>Found "+resultCount+" Results.</b></div>");
//$('#searching').append("<div id=length><b>Length "+response.items.length+" </b></div>");
for (var i=0; i<response.items.length;i++)
{
//store each JSON value in a variable
var publishedAt=response.items[i].snippet.publishedAt;
var channelId=response.items[i].snippet.channelId;
var title=response.items[i].snippet.title;
var description=response.items[i].snippet.description;
var thumbnails_default=response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium=response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high=response.items[i].snippet.thumbnails.high.url;
var channelTitle=response.items[i].snippet.channelTitle;
var liveBroadcastContent=response.items[i].snippet.liveBroadcastContent;
var videoID=response.items[i].id.videoId;
//var firstPage=true;
// console.log(thumbnails_default);
//A HTTP call to this URL with videoID will give all XML info of that video:
//http://gdata.youtube.com/feeds/api/videos?q=videoID
// console.log(videoID);
//replace the first search button with a 'more' button
//$('button').replaceWith("<button type='button' id=More"+i+">More...</button>");
if(firstPage===true)
{
//print the stored variables in a div element
$('#snipp').append("<div id=T><b>Title:</b> "+title+"</div><div id=C><b>Channel ID: </b>"+channelId+"</div><div id=D><b>Description </b>"+description+"</div><div id=P><b>Published on: </b>"+publishedAt+"</div><div id=CT><b>Channel Title: </b>"+channelTitle+"</div><a id=linktoVid href='http://www.youtube.com/watch?v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
else
{
$('#T').replaceWith("<div id=T><b>Title:</b> "+title+"</div>");
$('#C').replaceWith("<div id=C><b>Channel ID: </b>"+channelId+"</div>");
$('#D').replaceWith("<div id=D><b>Description </b>"+description+"</div>");
$('#P').replaceWith("<div id=P><b>Published on: </b>"+publishedAt+"</div>");
$('#CT').replaceWith("<div id=CT><b>Channel Title: </b>"+channelTitle+"</div>");
$('#linktoVid').replaceWith("<a id=linktoVid href='http://www.youtube.com/watch v="+videoID+"'><img id=imgTD src=\""+thumbnails_default+"\"/></a><br/><br/><a id=linktoVid1 href='http://www.youtube.com/watch?v="+videoID+"'><video id=vidTD width=\"320\" height=\"240\" controls poster="+thumbnails_default+"><source src='http://www.youtube.com/watch?v="+videoID+">Your browser does not support the video tag.</video></a><br/><br/>");
}
// $('#snipp').append("<div id=C"+i+">Channle ID: "+channelId+"</div><br/>");
//link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=76TlUlPZQfQ&feature=youtube_gdata'/>
}
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage=false;
}
The HTML:
<body>
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp">
<div id=T0
</div>
<br/><br/><br/>
</body>
After create a jsfiddle with your code, I could check the pagination is working correctly.
The problem you're facing lies in your HTML code (most specific: in how you're building your HTML code).
My humble advice is that "instead of using append", re-creates the HTML that renders the current page.
Also, just after all controls loaded in the screen, the "prevPageButton" and "nextPageButton" buttons shows undefined.
For this situation, change these lines:
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
For this:
if (prevPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"prevPageButton\">Prev Page " + prevPageToken + "</button></div>");
}
if (nextPageToken == undefined) {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page</button></div>");
} else {
$('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\">Next Page " + nextPageToken + "</button></div>");
}
After a few modifications, you can check here the updated and working jsfiddle.
The tl;dr version is as follows:
Logic for build the HTML code was replaced for set a variable that (in the for-loop) builds the HTML code.
At the end of the loop, the HTML is added directly to the div container called "snipp".
Removed other HTML unneccesary code.
This is the modified code:
HTML:
<div id="search">
<input type="text" value="eureka" id="searchtext"><button type="button" id="searchbutton">Find</button>
</div>
<button type="button">Search Me...</button>
<pre id="response">
</pre>
<pre id="count"></pre>
<pre class="vID"></pre>
<div id="snipp"></div>
JS:
function onSearchResponse(response) {
var responseString = JSON.stringify(response, '', 2);
var resultCount = response.pageInfo.totalResults;
nextPageToken = response.nextPageToken;
prevPageToken = response.prevPageToken;
$('#count').replaceWith("<div id=count><b>Found " + resultCount + " Results.</b></div>");
// This variable will save the HTML code in construction.
var HTML_CONTENT = "";
for (var i = 0; i < response.items.length; i++) {
//store each JSON value in a variable
var publishedAt = response.items[i].snippet.publishedAt;
var channelId = response.items[i].snippet.channelId;
var title = response.items[i].snippet.title;
var description = response.items[i].snippet.description;
var thumbnails_default = response.items[i].snippet.thumbnails.default.url;
var thumbnails_medium = response.items[i].snippet.thumbnails.medium.url;
var thumbnails_high = response.items[i].snippet.thumbnails.high.url;
var channelTitle = response.items[i].snippet.channelTitle;
var liveBroadcastContent = response.items[i].snippet.liveBroadcastContent;
var videoID = response.items[i].id.videoId;
// Buld the HTML to render at the current page.
HTML_CONTENT += "<div id='video_item'> " +
" <div id=T><b>Title:</b>" + title + "</div> " +
" <div id=C><b>Channel ID: </b>" + channelId + "</div> " +
" <div id=D><b>Description </b>" + description + "</div> " +
" <div id=P><b>Published on: </b>" + publishedAt + "</div> " +
" <div id=CT><b>Channel Title: </b>" + channelTitle + "</div> " +
" <a id='linktoVid' href='http://www.youtube.com/watch?v=" + videoID + "'><img id='imgTD' src='" + thumbnails_default + "' /></a><br/><br/><a id='linktoVid1' href='http://www.youtube.com/watch?v=" + videoID + "'><video id='vidTD' width=\"320\" height=\"240\" controls poster='" + thumbnails_default + "'><source src='http://www.youtube.com/watch?v=" + videoID + "'>Your browser does not support the video tag.</video></a><br/><br/> " +
"</div>";
}
// Post all HTML generated code (built in the previous for-loop).
document.getElementById('snipp').innerHTML = HTML_CONTENT;
// $('#search').append("<div id=\"page\"><button type=\"button\" id=\"nextPageButton\" onclick=\"alert('Hello world!')\">Next Page "+nextPageToken+"</button></div>");
// return nextPageToken;
firstPage = false;
}

Why does loading a new html page reset javascript variables? How do I save those variables?

So I have this piece of code in an html file called demo.html
<img class="card-img-top" src="src/San_Francisco_Opera_House.jpg"
onclick="buyFunction('src/San_Francisco_Opera_House.jpg',
'SF opera house', 'price: $360,000')" alt="Card image cap">
This runs this javascript function which loads a new HTML page. I want to display the image in the new page,
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
setPicturePriceAndAddress();
});
};
function setPicturePriceAndAddress() {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
But all the values gets reset. Or is there another way to send information to the new html file without having to save variables?
You could potentially store the variables in session storage on demo.html and then call them inside of buy.html
demo.html:
function buyFunction(housePhotoString, addressString, priceString) {
sessionStorage.setItem('housePhoto', housePhotoString);
sessionStorage.setItem('address', addressString);
sessionStorage.setItem('price', priceString);
$(location).attr('href', 'buy.html');
}
buy.html:
$(document).ready(function() {
var housePhotoString = sessionStorage.getItem('housePhoto');
var addressString = sessionStorage.getItem('address');
var priceString = sessionStorage.getItem('price');
setPicturePriceAndAddress(housePhotoString, addressString, priceString);
});
function setPicturePriceAndAddress(housePhotoString, addressString, priceString) {
let strHTML = "";
strHTML +=
+"<img class=\"card-img-top\" src=\"" + housePhotoString + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + addressString + "</h4>" +
"<p class=\"card-text\">" + priceString + "</p>" +
"</div>";
$("#housePhotoBuy").html(strHTML);
};
JavaScript is a client side language. Basically it is run on the web browser when it loads the page. Therefore, when a particular page is unloaded (moving away from the page, going to another page, closing the tab etc), the javascript values used in the page is flushed unless you take measures to save them.
For this, you can look into localStorage which saves the data in the browser and can be reused. Another method you can use is to set cookies which can also allow you to store and retrieve data from the user's browser between page loads.
You can store the variable in the localstorage and access the variables from anywhere under the same domain name , i.e you can use it another html file specified under same domain name
for example for your sample I created a little http server and then made a POC out of that
say your main script is contained in some index.html as your code block like this
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<script type="text/javascript">
function buyFunction(housePhotoString, addressString, priceString) {
$(location).attr('href', 'buy.html');
houseAttributes.housePhoto = housePhotoString;
houseAttributes.address = addressString;
houseAttributes.price = priceString;
$(document).ready(function() {
//pass the houseAttributes object to setPicturePriceandAddress for better use of functions in js
setPicturePriceAndAddress(houseAttributes);
});
};
function setPicturePriceAndAddress(houseAttributes) {
let strHTML = "";
strHTML =
"<img class=\"card-img-top\" src=\"" + houseAttributes.housePhoto + "alt=\"Card image cap\">" +
"<div class=\"card-block\">" +
"<h4 class=\"card-title\">" +
"</i>" + houseAttributes.address + "</h4>" +
"<p class=\"card-text\">" + houseAttributes.price + "</p>" +
"</div>";
console.log('data',strHTML);
//storing only for one time
var dataToSave = localStorage.setItem('strHtml',strHTML)
//storing for multiple time
var arr = [];
if(localStorage.getItem('arrOfStr')){
arr = JSON.parse(localStorage.getItem('arrOfStr'))
}
arr.push(strHTML);
localStorage.setItem('arrOfStr',JSON.stringify(arr))
$("#housePhotoBuy").html(strHTML);
};
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
</script>
</html>
Then you are accessing if in your file buy.html file
<html>
<head></head>
<body>
<h1>Buy</h1>
<script type="text/javascript">
function getSavedValue(){
var data = localStorage.getItem('strHtml')
var data2 = JSON.parse(localStorage.getItem('arrOfStr'))
console.log(data,data2);
}
getSavedValue()
</script>
</body>
</html>
and under the same domain name like for example if your index.html is in http://localhost:5000
and your buy.html is in http://localhost:5000/buy.html then you will be able to retrive all values stored in the buy.html in form of array if you want to store all the responses for a particular client or you can just access one single variable.I have made both the example you can use whatever you like according to your choice. If it's less than 5mb or something like that you can use localstorage and it is better to use than in cookie or session storage because they serve different purposes and they should be kept apart for saving extra data like this buy information for a particular client

Image tag won't accept src

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.

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