JQuery text change in h3 tag - javascript

I am using ajax to call a page which looks like:
<div class="ui-block-a">
<div class="jqm-block-content invoicehomepage">
<h3>Invoices</h3>
<p>Pages</p>
<p>Navigation</p>
<p>Loader</p>
<p>Transitions</p>
</div>
</div>
and my ajax call is:
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
success: function(html_data) {
//var result = $('</div>').append(html_data).find('h3').html();
//$('h3').html(v.portletName);
pageContent += html_data;
//console.log(pageContent);
}
});
console.log(pageContent+'sssss');
});
}
});
I want to change text within h3 tag with the value i got from my second ajax call.
Thanks for help.

You need to change the HTML element h3 by finding it in the content that you have got in your Ajax Call something like this:
pageContent = $(html_data).find("h3:first").html(" YOUR-TEXT-YOU-WANNA-PUT ").parent();
Update:
I think you should use async: false in your second ajax call. And secondly, I don't think so that you needs to store/update html into some Variable as you have used pageContent. You should use JQuery .append() method:
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async: false,
success: function(html_data) {
var new_html_data = $(html_data).find("h3:first").html(v.portletName).parent();
$('.ui-grid-a').append(pageContent);
}
});
});
}
});

use: $('h3').text(v.portletName);

It seems your AJAX request is asynchronous..
You can add async : false, option in ajax request, so when the request end, second request begin and at success of second ajax request you can change text of H3 tag.
var pageContent = '';
$.ajax({
url: 'jsp/home/home.jsp',
type: 'POST',
dataType:'json',
async:false,// add this line so the success callback execute after response receive.
success:function(data) {
$.each(data, function(i, v) {
$.ajax({
url: 'tmpl/homePortlet/'+v.link+'.html',
dataType : "html",
async:false,// add this line so the success callback execute after response receive.
success: function(html_data) {
$('h3').html(v.portletName);
pageContent += html_data;
}
});
console.log(pageContent+'sssss');
});
}
);

Related

How to write dynamic text between div tags?

I am typing with the div on the login screen. I want this article to be dynamic. That's why I am using ajax jQuery to pull data. I want it to be written in the div. How do you do that?
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title = obj[0].Write;
}
});
You can use either text() or html() to set the content of the required div element. Try this:
<div class="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
dataType: 'json',
success: function(msg) {
$('.bas').text(msg[0].Write);
}
});
Note that by using dataType: 'json' jQuery will deserialise the response for you, so you don't need to call JSON.parse manually.
Use .text() function
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$(".bas").text(title);
}
});
You can do it by html() or text() depends on what object contains. If containing data includes html tags such as <strong> or .. use html() but if it's plain text use text() instead.
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$('.bas').html(title); // this line
}
});
if only remote read text file
<div class="bas">Write here (title)</div>
jQuery.get(myURL, /*ifMyParams,*/ function(data){
jQuery('.bas').text(data);
})
Use hanlderbars.js or <div class ="bas">Write here<span class="title"></span></div>

jQuery selector to handle click function inside a loop result

Sorry for asking this again but code won't execute. The problem is that I have a php loop that produces a html like below
<a class="js-delete-comment1" data-url="http://localhost/project/document_items/delete_item_comment/1">link</a>
<a class="js-delete-comment2" data-url="http://localhost/project/document_items/delete_item_comment/2">link</a>
<a class="js-delete-comment3" data-url="http://localhost/project/document_items/delete_item_comment/3">link</a>
Now, I want to select specific class to use as a jQuery selector but won't work. See below code
$("[id*=js-delete-comment]").each(function(){
$(this).click(function(){
var url = $('.js-delete-comment').attr('data-url');
// var id = $('.js-delete-comment').attr('data-id');
$.ajax({
url : url,
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});
});
Any help would be much appreciated!
There is no ID on the elements, use class^= selector. There is no need of iterating over the elements and then bind the event, the event can be bind directly on the selector itself.
$("[class^='js-delete-comment']").click(function() {
Also, use $(this).data('url') to get the data-url attribute of the element that is clicked.
Code:
$("[class^='js-delete-comment']").click(function (e) {
e.preventDefault(); // To stop page redirection
var url = $(this).data('url');
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
});
You can use,
$("[class^=js-delete-comment]").click(function() {
var url = $(this).data("url");
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(result) {
console.log(result);
}
});
});
^ is the attribute starts with selector. you can use that for selecting the class
Use data() method for getting the data-url
Just use click event like this:
$("[class^=js-delete-comment]").click(function(){
var url = $(this).attr('data-url');
$.ajax({
url : url,
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});
I am not getting why you want to select these <a> links using class name.
Just put your code inside parent <div>
<div id="js-delete-comment">
<a class="js-delete-comment1" data-url="http://localhost/project/document_items/delete_item_comment/1">link</a>
<a class="js-delete-comment2" data-url="http://localhost/project/document_items/delete_item_comment/2">link</a>
<a class="js-delete-comment3" data-url="http://localhost/project/document_items/delete_item_comment/3">link</a>
</div>
And your JQuery code will be
$('#js-delete-comment > a').click(function(){
$.ajax({
url : $(this).data('url'),
type : 'POST',
dataType : 'json',
success : function(result) {
console.log(result);
}
});
});

append ajax result to div

I'm making an ajax call to the IMDb API to get the movie data for 'The Shawshank Redemption'. I want this data to be put in the div I created.
<div id="movie-data"></div>
My js code currently:
$(init);
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
It doesn't give any response. However, I can see the data in my console. When I append <p>Test</p> instead of data it does return 'Test' to the screen.
This is what I did. It seems to be working now. Thanks everyone.
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(JSON.stringify(data));
The following should work
$("#movie-data").html(data.Title);
because data will be in json format, like this:
{"Title":"Titanic","Year":"1997","Rated":"PG-13","Released":"19 Dec 1997","Runtime":"3 h 14 min","Genre":"Drama, Romance","Director":"James Cameron","Writer":"James Cameron","Actors":"Leonardo DiCaprio, Kate Winslet, Billy Zane, Kathy Bates","Plot":"A seventeen-year-old aristocrat, expecting to be married to a rich claimant by her mother, falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjExNzM0NDM0N15BMl5BanBnXkFtZTcwMzkxOTUwNw##._V1_SX300.jpg","imdbRating":"7.6","imdbVotes":"449,162","imdbID":"tt0120338","Type":"movie","Response":"True"}
Check these resources:
Using AJAX to Extract Data from IMDB API
http://99webtools.com/blog/php-get-movie-information-from-imdb/
Try like this. API is returning JSON values you need to get the values like mentioned below. Hope this helps you.
var content = 'Title : '+data.Title ;
content += ' Year : '+data.Year ;
content += ' Rated : '+data.Rated ;
content += ' Released : '+data.Released ;
$("#movie-data").append(content);
<div id="movie-data"></div>
function init() {
var html='';
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#movie-data").append(html);
}
});
}
init();
working demo
the answer is:
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").html($(data).append(data));
}
});
You could try to delete dataType: "json" from your ajax call
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
You can try with JSON.stringify(data)
The code would be the following:
$(document).ready(function(){
$.ajax({
method:"get",
url:'{{ route('getnotificationcount') }}',
success:function(data){
console.log(data);
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#notifyy").append(html);
}
});
});

JavaScript - Results Displaying in IE but not Chrome or FF

So, i'm new to Javascript, let's get that out of the way.
Anyway, I have the following code that works in IE, but not in Chrome or FF. It's supposed to grab the data from the Reddit RSS, then just output it, that's it. It only is working in IE. Can anyone explain what I'm doing wrong here?
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
document.write(result);
</script>
</head>
</body>
</html>
yes, this code doesn't look right. it's a race condition. document.write executes immediately. the ajax may or may not have set the result in time. you need to add the result to the page in the success event...something like:
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get', dataType: 'html',
async: false,
success: function(data) {
$("#some-div").html(data);
} });
You have race condition due to $.ajax being asynchronous. Display the result in the success handler instead, so that the request is guaranteed to have finished.
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
document.write(data);
}
});
Update
Since you set async to false, the above statement isn't applicable. However, I haven't ever found a good reason to use document.write(), which might be part of your issue. Try using another method to inject the data into your page such as .html(), .append(), alert(), etc. And it wouldn't hurt to do this inside document.ready either.
$(document).ready(function() {
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
alert(result);
$("body").append(result);
});
What about processing in this manner:
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.reddit.com/.rss', function(feed) {
var entries = feed.entries,
feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList += '<li>' + entries[i].title + '</li>';
}
jQuery('.rssfeed > ul').append(feedList);
});
HTML:
<div class="rssfeed">
<h4>RSS News</h4>
<ul></ul>
</div>
sample: http://jsfiddle.net/QusQC/

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources