I'm trying to create a random quote generator and I've linked the GET request with the button. I'm kinda clueless with API's this is my first try and I'd like for someone to point out my mistake. Here is my code:
$("#randomQuote").on('click', function() {
$.ajaxSetup({
cache: false
});
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=", function(data) {
$(".messageQuote").html(data[0].content + " - " + data[0].title)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="text-center">random quotes</h1>
<div class="container">
<div class="well col-xs align-self-center messageQuote text-center">
<button id="randomQuote" type="button">random quote</button>
</div>
</div>
https://codepen.io/grodis/pen/ZXNZvz?editors=1011
Related
I'm building the feature to take notes on my web app. I'm running into two problems:
I can't figure out how to recognize line breaks. I can hardcore text with line breaks, but when user clicks Edit it shows on the text the <br> and if he saves it just shows <br> in plain text.
Also if the user deletes all the text and clicks save it doesn't work and just prints <textarea>.
Any help is greatly appreciated!
$('#edit').click(function() {
$('#edit').hide();
$('#note').each(function() {
var content = $(this).html();
$(this).html('<textarea style="width:inherit">' + content + '</textarea>');
});
$('#save').show();
});
$('#save').click(function() {
$('#save').hide();
$('textarea').each(function() {
var content = $(this).val(); //.replace(/\n/g,"<br>");
$(this).html(content);
$(this).contents().unwrap();
});
$('#edit').show();
});
#note {
word-wrap: break-word;
max-width: 40rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6">
<h5 class="card-tittle">Note</h5>
<hr>
<div class="container index">
<div class="row">
<div class="jumbotron col-md-12" id="note">
Test Text.
</div>
<div class="col-md-12">
<button class="btn btn-primary" id="edit"><span class="glyphicon glyphicon-edit"></span>Edit</button>
<button class="btn btn-primary" id="save"><span class="glyphicon glyphicon-save"></span>Save</button>
</div>
</div>
</div>
</div>
I think you want to do something like this...
$('#edit').click(function() {
$('#edit').hide();
$('#note').each(function() {
var content = $(this).html().replace(/<br>/g,"\n");
$(this).html('<textarea style="width:inherit">' + content + '</textarea>');
});
$('#save').show();
});
$('#save').click(function() {
$('#save').hide();
$('textarea').each(function() {
var content = $(this).val().replace(/\n/g,"<br>"); //.replace(/\n/g,"<br>");
$(this).html("");
$(this).append(content);
$(this).contents().unwrap();
});
$('#edit').show();
});
Demo: https://www.codeply.com/go/hAL9pWWUFk
Currently working on freeCodeCamp's random code generator project. I'm getting strange behavior with my "Tweet" button. If the class is "twitter-share-button", the button will display properly, but won't populate the quote in the pop-up box, but if I change the class to "button", the button has no styling but the pop-up Tweet box populates correctly with the quote and author.
Please see code below:
HTML:
<div id="quoteBox" class="col-md-6 col-md-offset-3 text-center">
<h2>“What a curious power words have.”</h2>
<p>- Tadeusz Borowski</p>
<div class="panel panel-default">
<div class="panel-body">
<p id="quote"></p>
<h4 id="author"></h4>
</div>
<div id="twitter">
<a class="twitter-share-button button" id="tweet-quote" data-show-count="false">Tweet</a>
</div>
</div>
<button id="getQuote" class="btn btn-primary btn-lg round btn-block">New Quote</button>
JS:
$(document).ready(function() {
// Loads quote on page load
getQuote();
$("#getQuote").click(getQuote);
});
function getQuote() {
$(document.body).css('background-color',
colors[Math.floor(Math.random() * colors.length)]);
$.ajax({
type: "POST",
url: "https://andruxnet-random-famous-quotes.p.mashape.com/?
cat=famous",
responseType: "json",
success: function(response) {
showQuote(response);
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?
text=' + encodeURIComponent('"' + response.quote + '" - ' +
response.author));
},
error: function() {
alert('Error retrieving quote');
},
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader("X-Mashape-Key",
"pmTSpn6I45mshpuPkHokTQ01lAo1p1ugEH1jsnoOS19Gk3KQvB");
xhr.setRequestHeader("Content-Type", "application/x-www-form-
urlencoded");
xhr.setRequestHeader("Accept", "application/json");
}
}
function showQuote(response) {
console.log(response);
$('#quote').text(response.quote);
$('#author').text(response.author);
}
I've spent hours on Twitter's dev page without any luck. Any help would be greatly appreciated, thanks.
How can I add an HTML element received via AJAX to another HTML element previously added via AJAX? I tried to use .append but not working:
Example:
$.ajax({ (...), success: function() { $('.padding').append('<div id="request">Foo</div>') } });
This above working well, because .padding is initially loaded on the page. But when I try
$.ajax({ (...), success: function(data) { $('#request').append('<div class="description">Bar</div>') } });
not working. Why and how can I do it the right way?
Below, my .padding content:
<div class="padding">
<!-- Below, HTML result from first AJAX -->
<div class="ui attached segments" id="request">
<div class="ui right center aligned segment" id="header">
<h4 class="ui gray header"> P2017003</h4>
</div>
<div class="ui stackable three item menu segment">
<div style="justify-content: flex-start" class="item">
<button class="ui button">
<i class="left chevron icon"></i>
Voltar
</button>
</div>
<div class="item">
<!--Buttons AJAX-->
<div class="two ui red inverted small buttons segment-controller">
<button id="detalhes" class="ui active button">
Detalhes
</button>
<button id="acompanhar" class="ui button">
Acompanhar
</button>
</div>
</div>
<div style="justify-content: flex-end" class="item">
<button class="ui button">Imprimir</button>
</div>
</div>
<div class="ui main segment">
P-2017-003
</div>
</div>
</div>
I've rigged up this setup to simulate your situation. I've never once encountered the situation where the div with id request is not present in the DOM.
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).then(result => {
$('.padding').append('<div id="request">Call A finished</div>');
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
}).then(result => {
if ($('#request').length === 0) {
console.log('no request element found');
}
$('#request').append('<div class="description">Call B finished</div>');
});
}
getDataA()
.then(getDataB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding"></div>
My guess is your second call is done before the first call. Perhaps your code is something like this:
getDataA();
getDataB();
Now you're depending on which call finishes first. When call B finishes first your code breaks and when call A finishes first you're in luck.
You could run both requests in parallel if you want, it will require using $.when().
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
});
}
$.when(getDataA(), getDataB())
.then(function(resultA, resultB) {
$('.padding').append('<div id="request">Call A finished</div>');
$('#request').append('<div class="description">Call B finished</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding"></div>
I've tried it with your provided HTML and I still am not able to reproduce the situation.
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).then(result => {
$('.padding').append(`
<!-- Below, HTML result from first AJAX -->
<div class="ui attached segments" id="request">
<div class="ui right center aligned segment" id="header">
<h4 class="ui gray header"> P2017003</h4>
</div>
<div class="ui stackable three item menu segment">
<div style="justify-content: flex-start" class="item">
<button class="ui button">
<i class="left chevron icon"></i>
Voltar
</button>
</div>
<div class="item">
<!--Buttons AJAX-->
<div class="two ui red inverted small buttons segment-controller">
<button id="detalhes" class="ui active button">
Detalhes
</button>
<button id="acompanhar" class="ui button">
Acompanhar
</button>
</div>
</div>
<div style="justify-content: flex-end" class="item">
<button class="ui button">Imprimir</button>
</div>
</div>
<div class="ui main segment">
P-2017-003
</div>
</div>
`);
const
trigger = document.getElementById('detalhes');
trigger.addEventListener('click', getDataB);
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
}).then(result => {
if ($('#request').length === 0) {
console.log('no request element found');
}
$('#request').append('<div class="description">Call B finished</div>');
});
}
const
trigger = document.getElementById('fill-padding');
trigger.addEventListener('click', getDataA);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="fill-padding" type="button">Fill padding</button>
<div class="padding">
</div>
So, the issue is that jQuery hasn't update it's internal structures yet.
Sometimes this happens when appending elements, and trying to find them right away.
Instead do one of the 3:
Use jQuery.find() instead (eg: $("body").find("#id"))
Store the element html as a jQuery object:
var html = 'Hi';
var elem = $(html);
"Accumulate' the html all at once, and append it all at once.
var html = '';
$.ajax({ (...), success: function() {
html += 'Foo';
$.ajax({ (...), success: function(data) {
html += 'Bar';
$('.padding').append(html);
}
});
}
});
When I run this script I am getting AjaxFunction is undefined. I have searched and know that it is not defined in proper scope but can anyone let me know what is the correct way to define it and what is the reason for the error.
<script type=”text/javascript”>
function(AjaxFunction) {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display = ”block”;
document.getElementById("loadingdiv").innerHTML = res;
}
});
};
</script>
<cfform id="PageloadAjax" name="PageloadAjax">
<div id="Displayingdiv" name="displayingdiv">
<cfinput id="CFQUERYbutton" name="CFQUERYbutton" type="button" value="Displaypage" onclick="AjaxFunction">
</div>
<div id="loadingdiv" name="loadingdiv"></div>
</cfform>
Right now you are defining an anonymous function with AjaxFunction as a parameter. Step one in getting this to works is to change
function(AjaxFunction) {...}
into
function AjaxFunction() {...}
Also, in the onClick attribute, you must call the function, not just name it. So change
onclick="AjaxFunction"
into
onclick="AjaxFunction()"
I recommend looking at some basic JavaScript material to more easily understand and solve these minor issues. You could start with W3 Schools for easily understandable tutorials, or You don't know JS if you want more in-depth JavaScript knowledge.
Try this
<script type=”text/javascript”>
function AjaxFunction() {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display=”block”;
document.getElementById("loadingdiv").innerHTML=res;
}
});
};
</script>
And call function in onclick = "AjaxFunction()".
the answer that perfectly worked for me is:
<script type="text/javascript">
function AjaxFunction(mode) {
var url="";
if ( mode =="contacts") url = "cfquery.cfm";
if ( mode =="tagsvsscripts") url = "cfqueryprogram.cfm";
if ( mode =="siteinfo") url = "CFtagsvsscripts.cfm";
if ( mode =="Jqueryhide") url = "dynamic.cfm";
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#results").addClass("loading");
document.getElementById("loadingdiv").style.display="block";
$("#results").html(res);
$("#results").removeClass("loading");
}
});
}
</script>
<div class="card mb-4">
<div class="card-header bg-secondary">
Ajax Page Load Example Using Bootstrap
</div>
<div class="card-block">
<div class="row">
<div class="col-lg-3 col-xl-2 col-form-label">
<input class="btn btn-primary" name="CFQUERYbutton"
type="button" value="Displaypage" onclick="AjaxFunction('Jqueryhide')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('contacts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('tagsvsscripts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('siteinfo')">
</div>
<div id="loadingdiv" name="loadingdiv">
</div>
<div id="results"></div>
</div>
</div>
</div>
I am having trouble formatting the JSON data into html I have tried various methods and would just like a bit of help or pointing in the right direction. The example I've been playing with is 'apple' and here is what I'm currently getting, this is the second element of the apiResult array (pic).
In my ajax call the action I'm using is opensearch as I was advised to do that but I have seen a lot of people using query. Here is my codepen if anyone needs to take a look for themselves. Thanks for any help, I appreciate it.
Here is my html:
<div id="main">
<div id="title">
<h1>Wikipedia searcher!</h1>
<hr />
</div>
<div id="content">
<h3 id="random">Click here for a random wikipedia page</h3>
<form>
<div class="row" id="searchDiv">
<div class="col-xs-4">
<h3>Search for a wikipedia article:</h3>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="search" name="search">
</div>
<div class="col-xs-4">
<button type="button" class="btn btn-default" id="searchBtn">Search</button>
</div>
</div>
</form>
<ul id="theData">
</ul>
</div>
</div>
</div>
Here is my JS:
$(document).ready(function() {
$("#searchBtn").click(function() {
var $theData = $("#theData");
var title;
$.ajax({
url: 'https://en.wikipedia.org/w/api.php',
data: {
action: 'opensearch',
limit: 10,
namespace: 0,
search: $("#search").val(),
format: 'json'
},
dataType: 'jsonp',
success: function processResult(apiResult) {
var html = "";
$theData.html("Displaying search results for " + apiResult[0]);
apiResult.shift();
console.log(apiResult[0].length);
$.each(apiResult, function(i, apiResult) {
for(var x = 0; x <= apiResult[0].length; x++)
{
html += "<div class='result'>";
html += apiResult[i][x] + "<br>";
html += "</div><br>";
}
});
$theData.append(html);
}
});
});
});