I'm working on a project for freeCodeCamp and I've been stuck on this part all day. I'm pulling data from the Wikipedia API and I'm able to work with it, yet I'm not sure how the syntax should look for what I'm trying to achieve. Here is a link to an example of the data I'm working with. Wikipedia API Search.
Now, in my HTML I have a bootstrap modal that appears after the user inputs something into a form, with a listed group inside with the returned data from the search.
This is the code I have so far.
$(document).ready(function () {
$('#searchForm').on('submit', function(e) {
e.preventDefault();
$('#wikiSearch').modal('show');
var usersearch = document.getElementById('userinput').value;
var apiURL = "https://en.wikipedia.org/w/api.php?
action=opensearch&search="
+ usersearch + "&format=json&callback=?";
$.ajax({
url: apiURL,
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'GET',
success: function (data) {
data[1].forEach(function(item) {
$('#results').append("<tr><td><a href='#'>"+item+"</a></td></tr>")
});
data[2].forEach(function(item) {
$('#brief').append("<tr><td>"+item+"</td></tr>")
})
}
});
});
});
For each group in my modal of my HTML I want to display 1 result from the search. I figured I would be able to use a nested forEach but it's not returning the results I wanted. I've tried using map, and also tried creating a long nested for loop and feel like I might be doing more harm than good when it comes to learning since I'm only getting confused now lol. Thanks for any input.
To show the first row from the search results use the first key of the nested array:
$('#results').append("<tr><td><a href='#'>" + data[1][0] + "</a></td></tr>")
$('#brief').append("<tr><td>" + data[2][0] + "</td></tr>")
Don't forget to add a check for the possible undefined value inside the data array.
Related
I have an issue which I don't quite know how to approach.
I need to extend the Sitecore Insert link functionality: when I insert a link to a Sitecore Item, a certain icon, based on some logic (I've already created the logic for another user story(*)), needs to appear in the front of the link after "Insert" button is pressed, and of course, finally on the UI.
I was thinking on the following approach: after the item is inserted, the item's ID is sent to the backend via an Ajax call and the response is a mark-up with the values returned by the service I told you above at (*).
The issue is that I don't know where to start on or if my idea is ok.
Any help is welcome.
I found the answer:
In the RichText Commands.js file, I have added the following script which sends the item Sitecore ID to the API:
function scInsertSitecoreLink(sender, returnValue) {
if (!returnValue) {
return;
}
var url = returnValue.url;
var itemId = url.substring(url.indexOf("=") + 1, url.lastIndexOf("&"));
var $ = jQuery.noConflict();
$.ajax({
async: true,
type: "GET",
url: '/sitecore/api/Test/ThisIsTheTestApiCall',
data: JSON.stringify(itemId),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result);
}
});
[...]
}
First I have added var $ = jQuery.noConflict(); before the ajax call;
More info here: https://api.jquery.com/jquery.noconflict/
Then I've checked if there are any changes over the routes: RegisterHttpRoutes;
Profit.
You might be better to modify the renderField pipeline, because if you ever need to change these icons later, you're going to have to process every single link on your site.
To do that, you'll want to create a processor and have it run before Sitecore.Pipelines.RenderField.ExpandLinks, Sitecore.Kernel in the renderField pipeline so that you can use the dynamic links (which contain IDs) to figure out what icons you need. From there you can use HtmlAgilityPack.HtmlDocument to find and update the markup when the link is rendered.
I've posted a few questions seeking clarity in small details about the do's and don't's of javascript, ajax and html. And here's one more. I'm creating a list with javascript by the usage of an api. When making the list I get the correct values for the text. When pressing the button in the row I'm getting the alert message. But the new entry is blank.
Can I add data this way (a for loop getting info and building a string with it baked in)?
OR is it the way I retrieve and store data that is wrong?
EDIT: My data is undefined. Don't I get a string from: data.items[i].Info.drivers?
Part of javascript that talks to an api and gives drivers and cars. This segment is part of a for loop.
...+'<h5><data-title="'
+data.items[i].Info.drivers+'">'
+data.items[i].Info.drivers
+'</data></h5>'
+'<p class="subtitle"><data-title="'
+data.items[i].Info.cars+'">'
+data.items[i].Info.cars
+'</data></p>'
+ '<input class="adding"type="button" name="vehicle" value="Add book">'...
My add code (javascript in html):
$(document).on('click', '.adding',function() {
window.alert("active");
var $this = $(this);
var drivers = $(this).data('drivers');
var cars = $(this).data('cars');
alert($(this).data('drivers')); //<----gives alert, says Undefined
$.ajax({
url: 'insert.php',
type: 'POST',
data: {
'driver': drivers,
'car': cars
},
success: function(msg) {
window.alert("success triggered");
}
});
});
This is referring to the button. By putting the data attributes in the button in the same way the problem is solved.
Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?
Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}
Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")