I'm working on a news mobile app and so far I've been able to pull the JSON string and display on my page however I'm not sure how to open each individual news item on a new jquery mobile page.
Here's my code below.
Thanks for your help.
$.getJSON("http://kyivcool.veedoogroup.com/?json=11", function(data){
$(data.posts)
$('#cont').append("<div>");
$(data.posts).each(function(key, post){
$('#cont').append( "<div class='img-thumb'><a href='#fullText'><img src='" + post.thumbnail+ "'></a></div>" );
$('#cont').append( "<div class='title-post'><a href='"+ post.url+ "'><h4>" + post.title + "</h4></a></div>" );
$('#cont').append( "<div class='author-post'>" + post.author.name + "</div>" );
$('#cont').append( "<div class='excerpt-post'>" + post.excerpt + "</div>" );
$('#cont').append( "<hr>" );
alert(data.posts[0].title_plain)});
})
You could save the json array of posts to a global javascript variable.
Then put the post id in the link as a data-attribute.
Then handle the click event of the links, get the post id, and find the content in the global array. finlly put the content in a DIV in the separate page.
var thePosts;
$(document).on("pagecreate","#page1", function(){
$.ajax({
url: 'http://kyivcool.veedoogroup.com/?json=11',
dataType : 'jsonp',
success : function (data) {
thePosts = data.posts; //SAVE TO GLOBAL VARIABLE
$('#cont').append("<div>");
$(data.posts).each(function(key, post){
$('#cont').append( "<div class='img-thumb'><a data-postid='"+ post.id+ "' href='#fullText' class='fullTextLink'><img src='" + post.thumbnail+ "'></a></div>" );
$('#cont').append( "<div class='title-post'><a href='"+ post.url+ "'><h4>" + post.title + "</h4></a></div>" );
$('#cont').append( "<div class='author-post'>" + post.author.name + "</div>" );
$('#cont').append( "<div class='excerpt-post'>" + post.excerpt + "</div>" );
$('#cont').append( "<hr>" );
});
}
});
$(document).on("click", ".fullTextLink", function(){
var id = $(this).data("postid");
for (var i=0; i<thePosts.length; i++){
if (thePosts[i].id == id) {
$("#fullTextDiv").html(thePosts[i].content);
break;
}
}
});
});
DEMO
Related
Hi People i try to do a small jquery/php/mysql chat! What i need to do ist following:
My Html
<div id="loader"></div>
My Php
$myArray = array();
if ($result = $mysqli->Query("SELECT * FROM chat AS CHA LIMIT 3 ")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
My Json Output
[
{
"CHA_id": "594",
"CHA_to": null,
"CHA_from": "1000",
"CHA_time": "2019-11-18 00:02:13",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 1"
},
{
"CHA_id": "593",
"CHA_to": null,
"CHA_from": "1004",
"CHA_time": "2019-11-17 23:56:47",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 2 "
},
{
"CHA_id": "592",
"CHA_to": null,
"CHA_from": "1004",
"CHA_time": "2019-11-17 23:56:47",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 3 "
}
]
My Jquery
I try this
$.getJSON( "https://example.com/JSON.CHAT.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
But i get only this response
[object Object]
[object Object]
[object Object]
What i need to do ist
1. Load the content into loader div from json output
2. Update div appending new content based on "CHA_time"
Every help ist wellcome im totaly blocked.
As 04FS metioned, Your JS isn't right. It should be something like this:
$.getJSON( "https://example.com/JSON.CHAT.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.CHA_message + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
All "rows" are objects, so each individual value must be used properly while trying to add it to string.
This output:
[object Object]
Is the result of what you're doing here:
items.push( "<li id='" + key + "'>" + val + "</li>" );
In this case val is one of your returned objects:
{
"CHA_id": "594",
"CHA_to": null,
"CHA_from": "1000",
"CHA_time": "2019-11-18 00:02:13",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 1"
}
But the system has no way to know how to meaningfully display that object as a simple string. Did you want to display all properties? With or without keys? A specific property? In a specific format? JavaScript doesn't/can't know. So you need to specify how to format it. For example, if you just want to display one field:
items.push( "<li id='" + key + "'>" + val.CHA_id + "</li>" );
// ^--- here
Or if you want to format two fields, separated by a hyphen:
items.push( "<li id='" + key + "'>" + val.CHA_id + " - " + val.CHA_message + "</li>" );
Basically, however you want to format it, you'd need to provide the formatting logic to do that.
This one is making me sick.because i cant find where i am going wrong.I will
appreciate any help or hint from you. below is my javascript code.so far the server side is fine but display the actual comment on the client side is the problem. please help me.
$(document).ready(function () {
// process the form
$('form.comments_form').each(function () {
var form_to_submit = $(this);
form_to_submit.submit(function (event) {
event.preventDefault();
var posta_id = form_to_submit.find("input[type=hidden].UNIQUE_ID").val();
var tetxarea1 = form_to_submit.find("textarea.target").val();
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(jQuery.parseJSON(response));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>'" + response.f_name + "'</span>";
comment_string += "<div class='my_msg'>'" + esponse.my_comment + "'</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>'" + response.my_comment_date + "'</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
});
});
});
i am trying to display the list to unordered lis with the class "comenting2"
change your code from
$("ul.comenting2").prepend(comment_string);
to
$("ul.comenting2").prepend($(comment_string));
Your response value already is an object since jquery parses it automatically (you put json as datatype). You are trying to json-parse an object, of course that has illegal characters.
Yes. To make it easier to understand the problem. I believe it would be great if you also supplied the sample of your JSON response. It is usually caused by bad JSON format.
Okay. Got your sample JSON response.
Try to change your code into:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'http://localhost/Forepost/php/real_time_comment.php', // the url where we want to POST
data: {
posta_id: posta_id,
tetxarea1: tetxarea1
}, // our data object
dataType: 'json', // what type of data do we expect back from the server
success: (function (response) {
display_the_comment(eval('('+response+')'));
console.log(response);
}),
error: function () {
alert("oops something went wrong");
// oops something went wrong
}
});
//FUNCTION TO DISPLAY COMMENT FROM DATABASE
function display_the_comment(response) {
var comment_string = " ";
comment_string += "<li class='indiv_cmnts'>";
comment_string += "<span class='user_fname2'>‘" + response.f_name + "’</span>";
comment_string += "<div class='my_msg'>‘" + esponse.my_comment + "’</div>";
comment_string += "<img class='user_proff' src='" + response.profile_img + "'/>";
comment_string += "<span class='time_cmnts'>‘" + response.my_comment_date + "’</span>";
//comment_string += "<span class='fa_reply'><i class='fa fa-reply' aria-hidden='true'></i> reply</span>";
comment_string += "</li>";
$("ul.comenting2").prepend(comment_string);
}
Please noted the changes at ajax success and function display_the_comment(response)
I am trying to dynamically build up HTML using JQuery in ASP.NET MVC5. I have so far had success, but the URL cannot be resolved in the JQuery Code.
My code looks something like this:
$.ajax({
type: 'POST',
url: '#Url.Action("QuerySearch")',
dataType: 'json',
data: {
queryName: $("#queryText").val()
},
success: function (data) {
// var items = '';
$.each(data, function (i, item) {
var resource_Url = item.ResourceURL;
// var resource_url = item.ResourceURL;
var append_data = $('<div class="row">'
+ '<h3>' + item.ResourceTitle + '</h3>'
+ '</div>'
+ '<div class="row">'
+ '<span class="label label-primary" style="margin:3px;font-size:small;">'
+ item.ResourceEducation
+ '</span>'
+ '<span class="label label-warning" style="margin:3px;font-size:small;">'
+ item.ResourceGrades
+ '</span>'
+ '<span class="label label-info" style="margin:3px;font-size:small;">'
+ item.ResourceSubject
+ '</span>'
+ '<a href="#Url.Content("' + item.ResourceURL + '")">'
+ '<img src="#Url.Content("~/Content/Resources/download_icon.png")" alt="Download Resource" style="height:24px;width:24px;"/>'
+ '</a>'
Although this code is able to retrieve the image for the download_icon defined in my project, it is not able to display / embed the URL fetched from the server by my function which I am trying to display in the <a href> tag.
Any help is greatly appreciated.
You will need to pass the complete url value from the server as a property of the data received. Or have it stored locally
ASP code doesn't run in the browser, only on server
The trick was simple, the href tag had to be changed to:
'<a href="' + item.ResourceURL + '">'
It worked like a charm
Im trying to load article from json (its works) and add it link to fucntion, but when I add the a href tag with onclick function (for example - alert), the function doesn't work.
what am I missing?
$.getJSON(categoryAddr,function(data){
json=data;
jQuery(function ($) {
$.each(json, function (i, value) {
var list ="<a href='#' onclick='alert('hey!');'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
});
you need to escapq quotes inside the alert
change this line
var list ="<a href='#' onclick='alert('hey!');'>"
to
var list ="<a href='#' onclick='alert(\'hey!\');'>"
Use escaped double quotes around your JS
var list ="<a href='#' onclick=\"alert('hey!');\">"
Define onclick event outside instead of defining it inline as shown below
jQuery(function ($) {
var json={title:'title1'};
$.each(json, function (i, value) {
var list ="<a href='#' onclick=\"alert('hey!');\">"
+"<h1>" + value + "</h1>" ;
$('.hold').append(list);
});
});
Fiidle : https://jsfiddle.net/9qes9u8u/
Updated Fiddle based upon #rzr answer
https://jsfiddle.net/t8o56g28/
I would go for delegated events:
var list ="<a href='#' class='link'>"
Now you can use this script, and you don't need to have a nested doc ready block:
$.getJSON(categoryAddr,function(data){
json=data;
$.each(json, function (i, value) {
var list ="<a href='#' data-id='" + value.id +"' class='link'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
This is delegated event on newly created anchor:
$('.hold').on('click', '.link', function(){
alert($(this).data("id"));
});
i have a div id.i have to append a table with values to the div.
<div id="testResult" style="padding-left: 120px; "></div>
am doing follwing steps but it is not working.
$.ajax({
url: '/getReports',
cache: false
}).done(function (html) {
if (html != "") {
$('#testResult').show();
var htm = "";
var string1 = '<table border="1"><tr><td>No</td><td>Testcase</td> <td>OS</td> <td>Browser</td> <td>Result</td></tr></table>';
$.each(html, function (i, data) {
string1 + = '<tr><td rowspan="3">1</td><td rowspan="3">' + data.status.test + '</td><td rowspan="3"><!--OS--></td><td>' + data.status.bwser + '</td> <td> ' + data.status.report + ' </td></tr>';
});
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
}).fail(function () {
$("#testResult").html("Failed to run the test");
$('#edit ').removeAttr("disabled");
});
$("#testResult").html("<br/><br/>") and $("#testResult").html("<p>" + htm + "</p>") will overwrite contents of your "testResult" DIV. So, replace this
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
with
$('#testResult ').append(string1);
$("#testResult").append("<br/><br/>");
$("#testResult").append("<p>" + htm + "</p>");
}
.append(): Will add or append extra strings to the existing contents of the DIV
where as
.html(): Will removes or overwrite the existing contents of the DIV with newer one.
This is the main difference between .append() and .html().
edit this part
$("#testResult").append("<br/><br/>");
Remove this part-->
$("#testResult").html("<p>" + htm + "</p>");
htm is empty string, as you never concatenate any string to it