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);
}
});
});
});
Related
I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code
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>
When I render my handlebars template in html, it looks like it's essentially skipping filling in the "handle bars" portion. I'm essentially printing messages with a title and content, and I'm using a "!each" helper to display all of my messages. I originally thought it was because it was because it was escaping the html around it, so I tried using a triple handle bar {{{ on each part however using the each helper with the triple stash gave me an error. Am I possibly using the handlebars incorrectly?
the typescript I used to render the HTML and my handlebars template is below:
public static refreshData(data: any) {
$("#indexMain").html(Handlebars.templates['main.hbs'](data));
//helper function for upvote button
Handlebars.registerHelper('getUButton', function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default up-button' id='u" + id + "'>Upvote</button>"
);
});
//helper function for downvote button
Handlebars.registerHelper("getDButton", function (id) {
id = Handlebars.escapeExpression(id);
return new Handlebars.SafeString(
"<button type='button' class='btn btn-default down-button' id='d" + id + "'>DownVote</button>"
);
});
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
}
console.log("context:")
console.log(context);
// Pass data to the template
var theCompiledHtml = theTemplate(context);
console.log(theCompiledHtml);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
//add all click handlers
//get all buttons with id starting with u and set the click listerer
$(".up-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.upvote(id)
});
//get all buttons with id starting with d and set the click listerer
$(".down-button").click((event) => {
var id = $(event.target).attr("id").substring(1);
main.downvote(id)
});
}
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
<div class="btn-group btn-group-xs" role="group" aria-label="upvote">
{{getUButton id}}
</div>
<div class="btn-group btn-group-xs" role="group" aria-label="downvote">
{{getDButton id}}
</div>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
Okay, then it is likely the data provided to your template is not in the correct form. Here's a working snippet (with non-essentials stripped out). The data passed to your refreshData template must be an array. Make sure it isn't an object containing an array.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
</head>
<body>
<script>
let refreshData = (data) => {
// Grab the template script
var theTemplateScript = $("#main-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
//get messages from server and add them to the context
// This is the default context, which is passed to the template
var context = {
messages: data
};
console.log("context:", context);
// Add the compiled html to the page
$("#messages-placeholder").html(theTemplate(context));
}
$(() => {
var data = [
{ likeCount: 3, title: 'My Title', content: 'Some content'},
{ likeCount: 0, title: 'My 2nd Title', content: 'Some other content'}
];
refreshData(data);
})
</script>
<script id="main-template" type="text/x-handlebars-template">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Current Messages</h3>
</div>
<div class="panel-body">
<div class="list-group" id="message-list">
<!-- for each message, create a post for it with title, content, upvote count, and upvote button -->
{{#each messages}}
<li class="list-group-item">
<span class="badge">Vote Count: {{likeCount}}</span>
<h4 class="list-group-item-heading">{{title}}</h4>
<p class="list-group-item-text">{{content}}</p>
</li>
{{/each}}
</div>
</div>
</div>
</script>
<div id="messages-placeholder"></div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Post New Message</h3>
</div>
<div class="input-group">
<span class="input-group-addon">Title</span>
<input id="newTitle" type="text" class="form-control" placeholder="Title" aria-describedby="newTitle">
</div>
<div class="input-group">
<span class="input-group-addon">Message</span>
<input id="newMessage" type="text" class="form-control" placeholder="Message" aria-describedby="newMessage">
</div>
<div class="btn-group" role="group" aria-label="create">
<button type="button" class="btn btn-default" id="postNewMessage">Post Message</button>
</div>
<span class="label label-danger" id="incompleteAcc"></span>
</div>
</body>
</html>
When I am faced with issues like this, I eliminate different things until I either get clarity or something I removed fixes the problem. Now I have isolated where the problem lies. In your situation, the issue is likely the data being passed so verify that. Then try stripping out your helpers to see if they are causing issues.
I've searched and tried for 2 days now, with no luck whatsoever.
What i'm trying:
I generate several div's through a foreach in xslt, that contains a hidden div where i store a code to match value out of an external xml file on. Something like this:
<div class="pakket_content">
<a href="http://">
<div class="waardering_wrapper col-xs-12">
<div class="sterwaardering col-xs-8">
<img src="http://">
</div>
<div class="CODE">CODE</div>
<div class="waardering col-xs-4">
<p>-</p>
</div>
<div class="waardering pull-right">
<b>-</b>
</div>
</div>
</a>
<a href="">
<button type="button" class="btn btn-default btn-md pull-right col-xs-12">
Nu boeken!
<span class="glyphicon glyphicon-arrow-right"></span>
</button>
</a>
</div>
Where the div class 'code' contains the code to match on.
The xml that comes out of this is:
<entities>
<accommodation cms-id="458245" external-id="CODE" name="Trip A">
<destination cms-id="45541" name="Paramaribo" level="destination"/>
<country cms-id="4545" name="Suriname" level="country"/>
<accommodation-type>Hotel</accommodation-type>
<testimonial-count>88</testimonial-count>
<average-testimonial-score>7.6</average-testimonial-score>
<deep-link>
http://link.com
</deep-link>
<testimonial-count-per-language>88</testimonial-count-per-language>
<testimonial-count-all>88</testimonial-count-all>
<average-testimonial-score-all>7.6</average-testimonial-score-all>
</accommodation>
</entities>
Now i wanted to append the average-testimonial-score to div "waardering" when the external-id attribute in equals the value in . But how would i go about that?
I tried with looping through the value of the div class and the attribute, like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('accommodation').each(function(index) {
var cijfer = $(this).find('average-testimonial-score-all').text();
$('.CODE').each(function(index) {
var divcode = $(this).text();
$.attr('external-id').each(function(index) {
var attrcode = $(this).text();
if (divcode == attrcode) {
$(".waardering").append(cijfer);
};
});
});
});
}
});
});
With no result.
Can someone push me in the right direction with this?
Fetching accommodation external-id in correct way (according to how .attr() is supposed to work), the code works as it should.
I omitted Ajax request for testing.
Fiddle.
$(document).ready(function()
{
var xml = '<entities><accommodation cms-id="458245" external-id="CODE" name="Trip A"> <destination cms-id="45541" name="Paramaribo" level="destination"/> <country cms-id="4545" name="Suriname" level="country"/> <accommodation-type>Hotel</accommodation-type> <testimonial-count>88</testimonial-count> <average-testimonial-score>7.6</average-testimonial-score> <deep-link>http://link.com</deep-link> <testimonial-count-per-language>88</testimonial-count-per-language> <testimonial-count-all>88</testimonial-count-all> <average-testimonial-score-all>7.6</average-testimonial-score-all> </accommodation></entities>';
$(xml).find('accommodation').each(function(index)
{
var cijfer = $(this).find('average-testimonial-score-all').text();
var externalId = $(this).attr("external-id");
$('.CODE').each(function(index)
{
var divcode = $(this).text();
if (divcode == externalId)
{
$(".waardering").append(cijfer);
};
});
});
});