I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.
Related
I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>
I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.
In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.
I tried to delay it using an if condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.
Can anyone recommend JavaScript or jQuery code to fix this problem?
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview
You've almost got it!
The same way that you call getMovieInfo in the success callback of getMovieList, you should be calling countTheMovies in the success callback of getMovieInfo.
As Jacob said above, move the countTheMovies call inside the AJAX request.
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
if (isLast) countTheMovies();
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.
You can call your countTheMovies() function from inside the success field of your Ajax call. This way it will make the function call when you intend it to.
Try out this
$(function(){
getMovieList();
});
function getMovieList() {
$.when( $.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
}) ).then(function( data, textStatus, jqXHR ) {
countTheMovies();
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}
I ve a problem with the output:i want to fill the ouptput whit some data from an ajaxcall.
the call is successfull(the output inside the each is filled with data)
but the output inside the each issnt apended to the output outside .
i always geht "
<ul id="listname" data-inset=true></ul>
and not
<ul id="listname" data-inset=true><li>some data</li></ul>
$("div:jqmData(role='collapsible')").each(function(){
var id = $(this).data("id");
var idDate=id.slice(7,18);
var listapp="id_col_"+idDate;
var listname="id_col_"+idDate;
output='<ul id="listname" data-inset=true>';
$.ajax({
url: 'lomodata.php',
data: 'timestamp='+idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
}
}
});
output+='</ul>';
$(this).append(output).trigger("create");
$(this).listview();
$(this).listview('refresh');
});
Note that $.ajax is by default asynchronous, and by the time you reach $(this).append(output), output is not yet defined, since the .ajax() call hasn't finished yet. You need to move the append to the success handler, or add the async: false option, so that $.ajax becomes a blocking call (although this defeats the purpose of using ajax):
success: function(res) {
if (res !='') {
var output='<ul id="listname" data-inset=true>';
$.each(res, function(i, Object) {
output+='<li>'+Object.reg+'</li>';
console.log(output);
});
output+='</ul>';
$(this).append(output).trigger("create");
}
}
AJAX is Asynchronous. When you write $.ajax( ... ), an HTTP request will be sent to the server, which will then move on to the next operation, output += '</ul>'. The HTTP request will not have finished by this time, and so your callback will not yet have been executed by the time you append output to the document.
$("div:jqmData(role='collapsible')").each(function () {
var el = this;
var id = $(this).data("id");
var idDate = id.slice(7, 18);
var listapp = "id_col_" + idDate;
var listname = "id_col_" + idDate;
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
output = '<ul id="listname" data-inset=true>';
if (res != '') {
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
console.log(output);
});
}
output += '</ul>';
el.append(output).trigger("create");
el.listview();
el.listview('refresh');
}
});
});
If you move all lines of codes that use the output variable to the success function of the ajax call, you will see that it works. The problem is that you're using asynchronicity incorrectly.
Something like this:
$.ajax({
url: 'lomodata.php',
data: 'timestamp=' + idDate,
type: 'GET',
ContentType: "application/json",
dataType: "json",
success: function (res) {
if (res != '') {
var output = '<ul id="listname" data-inset=true>';
$.each(res, function (i, Object) {
output += '<li>' + Object.reg + '</li>';
});
output += '</ul>';
console.log(output);
$("#myObject").append(output).trigger("create");
$("#myObject").listview();
$("#myObject").listview('refresh');
}
}
});
for example i have a .ajax() function like below:
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
It works fine,but i'd like to add a if statement to detect whether the $(".numberOfProfile0").html() exist or not, and will only execute when the $(".numberOfProfile0").html()exist
I tried below but it doesn't seem right
if ($(".numberOfProfile0").length) {
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
- UPDATE:
Let's show the whole application
This is the function:
if($(".numberOfProfile0").html().length){
function trend1() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
$.when(trend1()).done(function(trend1_data) {
//do something
}
Please remember jQuery selector is not a string. Using jQuery, the correct way to do this is something like $('.selector').val().length , $('.selector').html().length
Use $(".numberOfProfile0").html().length > 0 in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="numberOfProfile0">lorem</div>
<script>
if ( $(".numberOfProfile0").html().length > 0 ) {
alert("success");
// your function:
//function trend() {
//return $.ajax({
// url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + //$(".numberOfProfile0").html(), //getting the api
// type: 'get',
//success: function(data) {
//}
// });
// }
}
</script>
I think it should be
function trend() {
if ( $(".numberOfProfile0").length ) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}//if()
else
{
return false; //or any other appropriate value
}
}//trend()
use ($(".numberOfProfile0").html() !== '') that mean if element with class .numberOfProfile0 is not empty
function trend() {
if ($(".numberOfProfile0").html().trim() !== '') {
$.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
You are doing it wrong! You are defining the function inside the if, where as you should be calling it inside if.
First define the function.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
Then call it.
if ($(".numberOfProfile0").length) {
trend();
}
OR
You can put the if check inside the function.
function trend() {
if ($(".numberOfProfile0").length) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
else{
return -1;
}
}
You can use .is() within $.when() at ternary to return trend() if element exists, else return null to $.when(); handle element not existing in DOM. Note, you can remove success option at $.ajax() if response is handled at .done()
function trend() {
return $.ajax({
url: "/dashboard/getTrend'"
+ "?period=30d"
+ "&profileId="
+ $(".numberOfProfile0").html(), //getting the api
type: "get"
});
}
$.when($(".numberOfProfile0").is("*") ? trend() : null)
.done(function(trend1_data) {
if (trend1_data === null) {
// handle `$(".numberOfProfile0")` not existing in `DOM`
} else {
// handle `trend1_data` not being `null`, element exists
// do something
}
})
You should check the existence of the element inside the before_send callback for aJax and cancel the aJax request if not.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(),
type: 'get',
before_send: : function( xhr ) {
if ($(".numberOfProfile0").length > 0 && $(".numberOfProfile0").html().trim() == ''){
return false;
}
}
success: function(data) {
}
});
}
The above code snippet should work in your case.