I tried out several ways to get .json file and data using $.getJSON and $.ajax() overthere
My JS code n⁰2 fails :
$.ajax({
type: "GET",
url: 'js/main.js',
data: data,
success: 1,
}).done(function ( data ) {
var items = [];
$.each(data.tata.entities.q142.labels.fr.value, function(key, val) {
items.push('<li id="' + key + '">Test 2:' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
In Chrome console, the message error is :
"Uncaught ReferenceError: data is not defined"
Refering to the line :
data: data,
What is going wrong ? What to do ?
Edit: all is done client side.
The problem is being caused because you didn't define the variable data, so try removing the data: data line, it looks like you're just getting a JavaScript file which wouldn't normally take a query string:
$.ajax({
type: "GET",
url: 'js/main.js',
success: success,
}).done(function ( data ) {
var items = [];
$.each(data.tata.entities.q142.labels.fr.value, function(key, val) {
items.push('<li id="' + key + '">Test 2:' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Related
Trying to figure out how to change the selected item of a select2 box after the page loads for the first time (and after it has loaded data from a ajax api call)
I tried using the below, but I cant get them to call after the ajax data has loaded?
$series2.val('2');
$series2.trigger('change');
The documentation says that it cannot be done using the val function (see here https://select2.org/programmatic-control/add-select-clear-items) and I do not want to do this with a custom API call that provides a "selected" value - as this does not work with templating.
This is NOT a duplicate of Select2 auto trigger event change
var $make2 = $(".make2");
var $series2 = $(".series2");
$make2.select2().on('change', function() {
$series2.empty();
if ($make2.val() !== null) {
$.ajax({
url: "{{ url('/') }}" + "/api/series/" + $make2.val(),
type: 'GET',
dataType: 'json',
async: true,
success: function(data) {
$series2.select2({
data: data,
templateSelection: function(result) {
return result['text'];
},
templateResult: function(result) {
if (!result['id']) {
return result['text'];
};
var final =
'<div>' +
'<strong>' + result['text'] + '</strong>' +
'<ul class="list-unstyled">' +
'<li><em>' + result['make'] + '</em></li>' +
'<li><em>' + result['category'] + '</em></li>' +
'</ul>' +
'</div>';
return final;
},
escapeMarkup: function(result) {
return result;
},
});
}
});
}
}).trigger('change');
});
It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
The JS is this
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var $select = $('#newStatus');
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
The JSON looks like this:
[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
I think you need something like this.
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var json = $.parseJSON(response);
var $select = $('#newStatus');
$.each(json ,function(index, object)
{
$select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.
Then you could use the $.each() function to loop through the data:
var json = $.parseJSON(response);
I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.
I am trying to parse some JSON and take the elements "startTime" and "endTime" and add them to a list. I am able to receive the JSON successfully, however I am having trouble properly parsing and then looping through to add each instance to the list. Inside of the UL, i would like to create lists for each, like i demo below:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
The HTML where I am trying to insert the LI inside of the UL:
<div data-role="main" class="ui-content" id="headerDate">
<ul data-role="listview" data-inset="true" id="appts">
</ul>
</div>
So basically for each appointment i get back in the JSON, I want to add a new LI with the startTime and endTime.
I am using JQM 1.3.2, and JQUERY 1.8.0.
Thank you
Change this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
var $calAppts = $('#appts');
$('<li data-role="list-divider">' + this.startTime
+ ' - ' + this.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
Into this:
$.ajax({
url: 'localhost:8080/sample?',
dataType: 'json',
success: function (data){
var json = $.parseJSON(data);
$.each( json, function( key, value ) {
var agrega = "<li data-role='list-divider'>";
if(key=='startTime')
{
agrega = agrega + value
}
if(key=='endTime')
{
agrega = agrega + ' - ' + value;
}
agrega = agrega + '<span class="ui-li-count"></span></li>';
$('#appts').append(agrega);
});
From your code sample, it seems your problem is that you're trying to look for the startTime property in the wrong place (on this). In your sample, the startTime property should be present on your parsed JSON, so accessing the key there should do the trick:
$('<li data-role="list-divider">' + json.startTime
+ ' - ' + json.endTime + '<span class="ui-li-count"></span></li>').appendTo($appts);
If the returned JSON is a series of times, then you'll also want to loop through the JSON object as well:
$.each(json, function(key, value) {
if (key === 'startTime') {
// append to the list
}
});
Additional note:
If JSON is what is being returned from the AJAX call, then you shouldn't need to use $.parseJSON on it. JSON objects are JavaScript objects, so you can simply use the returned value and access they keys on it (meaning you can use data.startTime directly instead of parsing it first).
Please find the response below
var ulObject = $("#appts");
var ajaxObject = $.ajax({
type:"POST",
dataType:"json",
url:"" //Provide the URL in the field to be processed.
});
ajaxObject.done(function(msg){
var jsonResponse = $.parseJSON(msg);
var listObjectStart = '<li data-role="list-divider">'
var listObjectEnd = '</li>';
$.each(jsonResponse,function(key,value){
if(key === "startTime")
{
listObjectStart += value;
}
else if(key === "endTime")
{
listObjectStart += '-'+value+'<span class="ui-li-count"></span>';
}
});
listObjectStart += listObjectEnd;
ulObject.append(listObjectStart);
});
Try the following if server send the data back to client in json format.
$.ajax({
url: 'localhost:8080/sample?',
dataType : 'json',
success: function(data){
$("#appts").append('<li data-role="list-divider">' + data.startTime
+ ' - ' + data.endTime + '<span class="ui-li-count"></span></li>');
},
error: function(){
alert('There was an error in communication.');
}
});
Can anyone tell me why I get an error on the 2nd line saying 'unexpected string' but works fine when I have it directly on my view (i'm using MVC 3, not that it makes a difference):
function getUsers(processId) {
$.ajax({
url: "#Url.Action('GetProcessApprovers', 'Risk')",
data: { processId: processId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "<option value=\"\">-- Please select --</option>"
if (data != "") {
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
}
$("#ProcessOwnerId").html(items);
}
});
};
Because your url: "#Url.Action('GetProcessApprovers', 'Risk')", only executes in the context of the view, not in an external JS file. It's razor code.
You need to pass the url to the Javascript in some other way, perhaps as a parameter of your function.
getUsers(processId, ajaxUrl)
Another way would be to write out the url from the HtmlHelper into a data attribute in your view and then pick it up in your Javascript.
HTML
<div id="someContainer" data-url="#Url.Action('GetProcessApprovers', 'Risk')">...
JS
var url = $("#someContainer").attr("data-url");
Your url parametre is has the issue.
please change it like this:
url: '#Url.Action("GetProcessApprovers", "Risk")',
Hope it works