This is a live link from a web API want to use:
http://gmgapi.azurewebsites.net/SystemParameters/Hotels/GetAll?langId=en
This is my first time to call data from API so maybe I missed some setting
In html page I put some code like this to test the connection with API or not
<div id="result"></div>
<script>
(function() {
var myAPI = "http://gmgapi.azurewebsites.net/SystemParameters/Hotels/GetAll?langId=en";
$.getJSON(myAPI, {
format: "json"
})
.done(function (data) {
$("#result").html(data);
alert("Load was performed.");
});
})();
</script>
the array contained hotel data like hotel name , description and images
i just need to call them using jquery
new edits
this code is working properly to get the data from Api
(function() {
var myAPI = "https://gmgapi.azurewebsites.net/SystemParameters/Hotels/GetAll?langId=en";
$.getJSON(myAPI, {
format: "json"
})
.done(function(data) {
doSomething(data);
console.log("Load was performed.");
});
})();
function doSomething(data) {
for (var i = 0; i < data.length; i++) {
var div = $("<div>");
var label = $("<label>").text(data[i].DisplayValue);
$(div).append(label);
$('#result').append(div);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"> </div>
I need to make a href and user select the name hotel and retrieve the other data related to this hotel only
something like hotel 1 any user click on ot to get the all hotel data
If I understand you correctly, you want the data receiving from the API to be used to show as result as html?
(function() {
var myAPI = "http://gmgapi.azurewebsites.net/SystemParameters/Hotels/GetAll?langId=en";
$.getJSON(myAPI, {
format: "json"
})
.done(function(data) {
doSomething(data);
alert("Load was performed.");
});
})();
function doSomething(data) {
for (var i = 0; i < data.length; i++) {
var div = $("<div>");
var label = $("<label>").text(data[i].DisplayValue);
$(div).append(label);
$('#result').append(div);
}
}
http://jsfiddle.net/trf432xm/
Related
I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});
I have to pass some result string to the view after sucessful ajax post. At the moment my js is placed in the view and the callback function creates a resultstring and then posts it to the results div. Since I have some blade syntax in the string that is being generated by the callback function it works until I leave the js in the blade.php view file, if I put the javascript in public/js/some.js blade doesn't parse that syntax and the result is the view is rendered with the syntax instead of data. So I was thinking: Can I put the sting in a separate view/js/result.blade.php and in the jquery function do somtehing like:
var resultStr = (content of view/js/result.blade.php)
for(var i=0; i<obj.length; i++){
resultStr
};
$("#results").html(resultStr);
If so, how do I load the external file into partialstring?
My guess is that as it's a blade file it will be parsed.
#c-smile tried this code but is not working, the file is opened but then the view doesn't get the data
jQuery(function ($) {
$(document).ready(function () {
var form = $('form');
form.submit(function (e) {
e.preventDefault();
$.get("js/blade/filler.blade.php", function (data) {
var resultStr = data;
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function (data) {
var obj = (data);
for (var i = 0; i < obj.length; i++) {
resultStr;
}
$("#results").html(resultStr);
}
});
});
});
});
});
That's subject of AJAX functionality.
With jQuery you would do it as:
$.get( "view/js/result.blade.php", function( data ) {
var resultStr = data;
...
});
I am writing a simple app that loads movie info from an API. After this loading, I am attempting to use Angular to display the movies in a simple list view. I am correctly loading the movies, but it seems like the angular controller is created and sends the movie array to the view before the movie array is populated. I am unsure how to get around this.
var movieList = [];
var app = angular.module('top250', []);
// immediately make a call to the server to get data (array of movies from text file)
$.post('/', {}, function(data) {
init(data);
});
app.controller('MovieController', function() {
// should be setting this.movies to an array of 250 movies
this.movies = movieList;
});
function init(data) {
// cycle through array, use title to retrieve movie object, add to array to be sent to view
$.each(data, function(index, value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
$.getJSON(url, function(data) {
console.log('in get json', data);
var movieObj = data;
storeMovie(movieObj);
});
});
}
function storeMovie(movieObj) {
movieList.push(movieObj);
}
And my HTML (although I'm certain this isn't the problem:
<body ng-controller="MovieController as MovieDB">
<div class="row">
<div class="large-12 columns">
<h1>IMDB Top 250 List</h1>
</div>
</div>
<div class="row">
<div class="large-12 columns" id="movie-list">
<div class="list-group-item" ng-repeat="movie in MovieDB.movies">
<h3>{{movie.Title}} <em class="pull-right">{{movie.Plot}}</em></h3>
</div>
</div>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
First I transformed your ajax calls to an angular factory:
app.factory('MoviesService', function($http, $q) {
function getMovie(value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
return $http.get(url).then(function(res){ return res.data; });
}
return $http.post('/').then(function(res) {
return $q.all(res.data.map(getMovie));
});
});
Then I can consume it like so:
app.controller('MovieController', function(MoviesService) {
var self = this;
MoviesService.then(function(movies) {
self.movies = movies;
});
});
don't use jquery
use angular $http or $resource
using $http, you set scope var to the data inside promise, and life will be good
You need to wait for you init method to complete:
function init(data, complete) {
$.each(data, function(index, value) {
var title = value.split(' (')[0];
title = title.split(' ').join('+');
var url = 'http://www.omdbapi.com/?t=' + title + '&y=&plot=short&r=json';
$.getJSON(url, function(data) {
console.log('in get json', data);
var movieObj = data;
storeMovie(movieObj);
}).always(function(){ // count competed ajax calls,
// regardless if they succeed or fail
if(index === data.length -1)
complete(); // call callback when all calls are done
});
});
}
Now you can do this:
app.controller('MovieController', function() {
$.post('/', {}, function(data) {
init(data, function(){
this.movies = movieList;
});
});
});
Personally I would just keep the movieList inside of the init method and send it with the callback when you're done, but that's just a preference.
I'm writing a script to parse a JSON file, and I seem to have got myself into a tricky situation. Can I append half of the returned items in one div element and the other half in another div elemet?
Here is the original markup:
<div class="feed"><div class="displayfeed main"></div></div>
<div class="feed"><div class="displayfeed second"></div></div>
I want the page to display like this after appending the returned data:
<div class="feed">
<div class="displayfeed main">
<h3>item1's title</h3> //Half of the items in "div.main"
.......
</div>
</div>
<div class="feed">
<div class="displayfeed second">
<h3>item2's title</h3> //Half of the items in "div.second"
...........
</div>
</div>
JS Code:
$.ajax({
url: source,
success: function (data) {
var item_html =
$(data.items).each(function (index, item) {
'<h3>'+item.title+'</h3>';
});
//Any way to append some of them in ('.main') and the rest in ('.second')?
$('.displayfeed').append(item_html);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I'm looking for any possible suggestions, otherwise I have no choice but to parse the same feed twice. Any help would be appreciated.
Updated:
I've set up a FIDDLE using Gogole news feed in JSON format converted by YQL as an example
Use multiply selector.
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
I don't know what structure you have but you can try this:
$.ajax({
url: source,
success: function (data) {
var item_html_main = "";
var item_html_second = "";
// assign values to item_html_main and item_html_second variables
var count = data.count;
var half = count/2;
var counter = 0;
for(item in data) {
if(counter < half) {
item_html_main += item;
} else {
item_html_secodn += item;
}
counter++;
}
$('.displayfeed.main').append(item_html_main);
$('.displayfeed.second').append(item_html_second);
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
You can try something like this. if it does not matter which posts is displayed in which container
$.ajax({
url: "<your-URL>",
success: function (data) {
var length = 0;
var items = data.query.results.item;
items = items.map(function(item){
return '<h3>'+item.title+'</h3>';
});
var half = items.length/2;
for(var i = 0; i < items.length; i++)
if(i < half)
$('.main').append(items[i]);
else
$('.second').append(items[i]);
length++;
},
error: function () {$searcharea.append("<b>No Results Returned</b>");}
});
Of course, but you need some separator or something
You can append all to your first div and then copy the part you want in the second div out of the first.
Example
item_html
<h2>Headline</h2>
<span>
News Text
</span>
js
$('.displayfeed').append(item_html);
sec = $('.displayfeed').find('span').html();
$('.displayfeed').find('span').remove();
$('.displayfeed second').append(sec);
In MVC 4 application I want when click a link, to show some related Products list in lightbox. I have method returns products I need:
public ActionResult GetRelatedProducts(int id)
{
var realProducts = GetRelatedProducts(id);
List<object> productsObjectList = new List<object>();
foreach (var item in realProducts)
{
productsObjectList .Add(new
{
id = item.Id,
fullname = item.Name
});
}
return Json(productsObjectList , JsonRequestBehavior.AllowGet);
}
HTML is:
<a class="show" id="show">Show</a>
<div id="productBox" style="display: none;">
// Product list will get here
</div>
And script:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) {
$('#productBox').lightbox_me({
onLoad: function () {
//How to send returned product list to light box, to show them by foreach loop
}
});
e.preventDefault();
});
});
How can I send product list to productBox to show products?
You code:
$('#show').click(function (e) {
url = '#Url.Action("GetRelatedProducts", "Product")';
var data = { id: '#Model.Id' };
$.post(url, data, function (result) { // <- "result" will contain array
$('#productBox').lightbox_me({
onLoad: function () { ... }
});
e.preventDefault(); // <- this must prevent "a" tag, put it outside
});
});
You could use your list on client side like this:
$.post(url, data, function (result) {
var list = '<ul>';
for(var i = 0; i < result.length; i++)
{
list += '<li>' + result[i].fullname + '</li>';
}
list += '</ul>';
$('#productBox').html(list).lightbox_me();
});
OR as Vladimir Bozic wrote, just use PartialViewResult, from controller return PartialView, it is like normal view, but without layout, just html block and you can use it like:
$.post(url, data, function (result) {
$('#productBox').html(result).lightbox_me();
});