How to fill forms using an API having associative array? - javascript

I need to use Jquery and AJAX to access an API which has this associative array-
{"1":"alamiz builder","2":"souroy builder","3":"vin selv builder","4":"gol mat builder","5":"sm dev builder","6":"zahi builder"}*
Because this array has numbers as keys, I am having a hard time displaying each value in a form element.
I have tried using $(selector).html(data["1"]) but this is just displaying the first character of the data.
My current code is-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
success: function(data){
$("#b1").html(data["1"]);
}
});
</script>
</head>
<body>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>
</body>
</html>
I expect that the checkboxes display all the data from the API dynamically.
In such a way-
<div id="b1"><input type="checkbox">alamiz builder</div>

You need use console.log(data) for detail about data structure.
I tried to reproduce with your JSON object, it worked.
Also need add for ajax call
contentType: 'application/json',
dataType: "json",
Updated:
It will have issue with CORS when you use $.ajax()
Try use $.getJSON(), it worked
$.getJSON('https://interview.switchme.in/js/2019/builder_json.php',function(data){
//console.log(data);
$("#b1").html(data["1"]);
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.getJSON('https://interview.switchme.in/js/2019/builder_json.php',function(data){
//console.log(data);
$("#b1").html(data["1"]);
})
</script>
</head>
<body>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>
</body>
</html>

Your $.ajax is returning JSON, which is a string - you need to make the code treat it like a JavaScript object, so add dataType: "json" to the options object:
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
dataType: "json",
success: function(data) {
$("#b1").html(data["1"]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>

Try this way:
(And don't remember, javascript codes must be above of tag)
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox">
<span></span> </div>
<div id="b2"><input type="checkbox"> <span></span>
</div>
<div id="b3"><input type="checkbox"> <span></span>
</div>
<div id="b4"><input type="checkbox"checked>
<span></span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
success: function(value){
var data = JSON.parse(value);
$("#b1 span").text(data["1"]);
$("#b2 span").text(data["2"]);
$("#b3 span").text(data["3"]);
$("#b4 span").text(data["4"]);
}
});
</script>

Related

jQuery/JavaScript parse AJAX response

I am retrieving an AJAX response from a server (the server processed an update of a shoppingcart) that contains various elements. Here is an example of how it looks like:
<div id="blockcart-wrapper">
<div class="shoppingcart-background" id="bg-div"></div>
<div class="blockcart cart-preview" data-refresh-url="//localhost/backend/index.php?fc=module&module=shoppingcart&controller=ajax">
<div class="header">
<a rel="nofollow" href="#">
<img class="cart-icon" src="someImage"
onclick="toggleClass()">
</a>
</div>
<div class="body" id="shopping-cart-body">
<div class="close">
<a href="#" onclick="toggleClass()">
<img class="icon" height="20px" width="20px" src="someImage">
</a>
</div>
<h1 class="shopping-cart-header">Shoppingcart</h1>
<div class="products-container">
<div class="product">
<span class="product-image"><img src="someImage"></span>
<div class="product-details">
<h2 class="name-header">Name</h2>
<div class="product-quantity-details">
<span class="quantity">19</span>
-
<a id="link1" href="https://backend/decrease" class="js-increase-product-quantity" data-link-action="update-quantity">+</a>
<span class="color-circle">
</span>
</div>
<div class="price-open">
<span class="product-price">14,16 €</span>
<span class="product-link">öffnen</span>
</div>
<a
class="remove-from-cart"
data-link-action="remove-from-cart"
data-id-product="6"
data-id-product-attribute="0"
href="http://backend/remove"
rel="nofollow"
>
Remove
</a>
</div>
</div>
</div>
<div class="checkout">
<div class="meta-data-wrap">
<div class="cart-total label-row">
<span class="label">Total</span>
<span class="value">269,06 €</span>
</div>
</div>
<a href="/index.php?controller=order" class="checkout-step">
<button type="button" class="dark">Checkout</button>
</a>
</div>
</div>
The problem is, that the respone contains about 25000 LOC which are mostly irrelevant. So I want to parse this part of the response and insert it into the actual HTML. What I did so far:
document.getElementById('link1').addEventListener('click', function(ev){
ev.preventDefault();
console.log(ev);
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
console.log($(data).text());
}
});
});
This gives me the complete response. So from this on, I tried to find the div with the id blockcart-wrapper, which is my 'entry point' for replacing the old HTML, so I did:
document.getElementById('link1').addEventListener('click', function(ev){
ev.preventDefault();
console.log(ev);
$.ajax({
url: this.href,
type: "GET",
dataType: "html",
success: function(data) {
console.log($(data).find('#blockcart-wrapper'));
}
});
});
But this gives me a jQuery object and not The HTML content within this div.
Could someone help me to parse the mentioned div and replace the 'old' with the new parsed?
But this gives me a jQuery object and not the HTML content within this div.
You must use .html() to return the HTML code inside the div like :
console.log( $(data).find('#blockcart-wrapper').html() );
If you cannot get a smaller response, try getting a partial:
Note the space before the selector
url: this.href + ' #blockcart-wrapper'
or
$("#container").load(location.href + ' #blockcart-wrapper')

Using ajax for every div with class/id

So I have asp.net core 2 project where I have one master view with this html:
<div>
#foreach (var factory in Model.factoryList)
{
<div class="factory-panel-content">
<div class="factory-main-info">
#factory.Name
<div class="city-name">#factory.CityName</div>
<div class="factory-some-value">
#factory.someValue
</div>
</div>
<div id="factory-plot-content">
</div>
</div>
}
And one partial view with (html only)
<div class="row">
<div class="col-md-4">
<div id="flot-line-chart" style="height: 100px"></div>
</div>
<div class="col-md-2">
<div id="flot-pie-chart" style="height: 100px"></div>
</div>
<div class="col-md-2">
<div id="gauge"></div>
</div>
What I need is to get partial view for every #factory-plot-content in my master view for each of my factory.
Using ajax like below change only one of the #factory-plot-content - the first one (I understand why) but I don't know what is the best way to call ajax.get foreach of factory divs.
My ajax: (Which I call in master page. It will be great to call it while foreaching factories)
$(document).ready(function () {
$.ajax({
url: '/home/ShowShortFactoryInfo',
success: function (data) {
$("#factory-plot-content").html(data);
}
});
})
The first idea I had is to make custom ids like "factory-plot-content-#Model.FactoryName" but I'm kinda sure that this is an ugly way to reach result I need.
You can try with following code:
<div>
<script>
var factoryNumber = 0;
</script>
#foreach (var factory in Model.factoryList)
{
<div class="factory-panel-content">
<div class="factory-main-info">
#factory.Name
<div class="city-name">#factory.CityName</div>
<div class="factory-some-value">
#factory.someValue
</div>
</div>
<div class="partial-data" id="factory-plot-content">
<script>
getPartialData(function(data){
let partialData = $(".partialData")[factoryNumber];
partialData.html(data);
factoryNumber++;
});
</script>
</div>
</div>
}
<script>
function getPartialData(cb){
$.ajax({
url: '/home/ShowShortFactoryInfo',
success: function (data) {
cb(data);
}
});
}
</script>
Hope it helps :)

no output for .val() on a HTML selector

I am trying to parse the content/value of the class "links". Following is the code that I use:
function modifyDOM() {
return document.body.innerHTML;
}
function getAnswers() {
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();'
}, (results) => {
var myVar = $(results[0]).find('.links').val();
return console.log(myVar);
});
}
results[0] contains the following example:
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">Title</div>
<input type="hidden" name="_token" value="eJUTXXLfSGs5UsIwpWPcQxthzqN7nt5F0XdRZEoG">
<div class="links">
Test 1
Test 2
Test 3
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://test.com/js/app.js"></script>
The issue is that console.log(myVar); does not output anything.
Am I doing anything wrong here? Any help is highly appreciated.
You need to use .text() or .html() in your code:-
Simple example:-
var answers = [];
$('.links a').each(function(){
answers.push($(this).text()); // can use .html() also
});
console.log(answers);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">Title</div>
<input type="hidden" name="_token" value="eJUTXXLfSGs5UsIwpWPcQxthzqN7nt5F0XdRZEoG">
<div class="links">
Test 1
Test 2
Test 3
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://test.com/js/app.js"></script>
Note:- So change below line in your code. My be your code starts working:-
var myVar = $(results[0]).find('.links a').text(); //or use .html()

Display next div on click

Say I have the following HTML layout:
<div class="main">
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
</div>
... etc ...
How would I make it so that if you click the image in one of the comment classes, it shows HTML in the next open-me class?
Here's what I have so far:
$(document).ready(function() {
$(document).on("click", ".image-click", function() {
$.ajax({
url: 'show_html.php',
type: "POST",
success: function() {
$(this).find(".open-me").html(); /* this is where I'm stuck */
}
});
});
});
this inside your AJAX success method isn't referring to the clicked element anymore. For that, we can set a context variable of this:
$(document).on("click", ".image-click", function() {
var self = $(this);
$.ajax({
url: 'show_html.php',
type: "POST",
success: function(data) {
self.parents(".comment").next(".open-me").html(data);
}
});
});
You can use this to access the sibling open-me. Also, you should save a reference to $(this) outside of the .ajax().
// outside the ajax function
var that = $(this);
// inside the ajax function
that.parent(".comment").next("open-me").html();
jQuery's documentation about next() is relevant.

How to add form dynamically in JavaScript or jQuery?

In my application, I have JSPs: demo1.jsp, demo2.jsp
When the user clicks "Add" button (this is in demo1.jsp) then demo2.jsp should appear in the proper position.
If form is in the same JSP/HTML there is no problem. Using the form id we can create using jQuery.
But here we are handling two JSPs, so how to do this?
demo1.jsp
<div class="accordion">
<div class="question" id="que3">
<span class="heading">Form Details</span>
<span class="button2 white" >Add</span>
</div>
<div class="answer">
<jsp:include page="demo2.jsp">
<jsp:param value="counter_crt" name="counter_crt" />
</jsp:include>
</div>
</div>
How do we write a jQuery function to create demo2.jsp dynamically?
Use AJAX.
$("#addbutton").on("click", function(){
$.ajax({
url: "demo2.jsp",
success: function(response) {
$("#answer").html(response);
}
});
});

Categories

Resources