How to call multiple ajax request using console log - ajax

How can i call multiple time ajax request using on console log.
i have Reply XHR to working fine but i need multiple request send using console log. any idea?

if you loop looks something like this:
for(var i=0; i<10; i++){
$.ajax({
//
success:function(data){
$("#p" + i + "_points").html(data);
}
});
}
it will not work as i will end up being the last i value in the loop; You need something like below
for(var i=0; i<10; i++){
(function(index){
$.ajax({
//
success:function(data){
$("#p" + index + "_points").html(data);
}
});
})(i);
}
The closure along with the passing of i will keep number value for that call.
of course there will need to exist elements with ids 1-10 or whatever number you use so:
<element id="p1_points">
<element id="p2_points">
<element id="p3_points">
...

Related

Shopify: How can I render the recommended products?

I am trying to use Shopify Ajax API to get recommended products inside the cart. I am able to get the recommended product's json but not the section rendering.
The script (note section_id):
jQuery.getJSON('/cart.js', function(cart) {
// first recommendation
jQuery.getJSON("/recommendations/products.json?product_id=" + cart.items[0].product_id + "&limit=6&section_id=recommended_first", function(
response
) {
var recommendedProducts = response.products;
}
});
})
The HTML:
<div id="recommended_first" class="upsell_product">
</div>
I get some messages in the console:
Error: ShopifyAnalytics.meta.page.pageType is empty: undefined
Fallback logic initiated
What am I missing? I didn't find any examples in the Shopify doc.
Thanks a lot!
Your code will not work because you have an extra } on line 7. Assuming the cart request returns valid data, the following code should work (also a good idea to check if the cart request returns any items before using the cart.items variable):
jQuery.getJSON('/cart.js', function(cart) {
jQuery.getJSON("/recommendations/products.json?product_id=" + cart?.items?[0]?.product_id + "&limit=6&section_id=recommended_first", function(response) {
var recommendedProducts = response.products;
var recommendedProductsHTML = "";
for (i = 0; i < recommendedProducts.length; i++) {
recommendedProductsHTML += `<div>${recommendedProducts[i].title}</div>`;
}
$("#recommended_first").html(recommendedProductsHTML);
});
});

For-in Loop through Tumblr posts with ajax

The expectation is that $(".post-title").append(postTitle); will return the title of that post, as will postBody. Yet when I console.log these variables > undefined is returned.
$.ajax({
url: "http://api.tumblr.com/v2/blog/ohc-gallery.tumblr.com/posts?api_key=***",
dataType: 'jsonp',
success: function(res){
var postings = res.response.posts;
var postTitle = "";
var postBody = "";
$(".post-title").append(postTitle);
$(".post-body").append(postBody);
for (var i in postings){
postTitle = postings[i].title;
postBody = postings[i].body;
}
console.log("postBody: " + postBody);
}
});
Am I missing something basic regarding Javascript closures... I really don't know right now. I simply want to loop through created post data for later display.
Github JS code- https://github.com/mrcn/ohc/blob/master/js/tumblr.js
Github HTML code- https://github.com/mrcn/ohc/blob/master/index-posting.html#L82-L89
I got it. The problem was with how I intended to display this information on the website, and I had to alter the code accordingly. The idea was to display paired blog post titles and entries. The problem was all titles were appearing together, and all bodies were appearing together- not paired off respectively.
The updated code is more along the lines of --
Javascript --
//use $.each() or Array.forEach
$.each(postings, function (i, post) {
$(".post ").append("<h3>" + post.title + "</h3>" + post.body + "<br><br>");
});
}
});
HTML --
<div class="post-wrap"><!--post-wrap-->
<div class="post">
</div>
</div><!--post-wrap-->
The for..in is used to iterate over an object... posts is an array for you can use the normal for (var i=0;i<x;i++) loop or any other iteration methods like $.each() or Array.forEach()
$.ajax({
url: 'http://api.tumblr.com/v2/blog/ohc-gallery.tumblr.com/posts?api_key=***',
dataType: 'jsonp',
success: function (res) {
var postings = res.response.posts;
var postTitle = '';
var postBody = '';
//use $.each() or Array.forEach
$.each(postings, function (i, post) {
$(".post-title ").append(post.title);
$(".post-body ").append(post.body);
})
}
});
Not every post type supports title or body. You currently have three posts, two text and one photo. The photo post type only support photos and caption, which is causing the undefined.
Check the API for more details: https://www.tumblr.com/docs/en/api/v2

Fill a SELECT with JSON from a PHP File (AJAX REQUEST)

I've been hours and hours (and time is running out to get this working) trying to figure out how to fill a select with the cities from a previously selected state using AJAX
the PHP file looks like this:
include_once("../models/class-Zone.php");
$state= $_GET["st"];
$cities= Zone::getCities($state);
echo json_encode($cities);
When I ALERT the result using ajax:
$.post(
'../ajax/getcities.php?st='+stateid,
function(data) {
alert(data);
}
);
//I GET THIS:
[{"id":"08078","titulo":"BARANOA"},
{"id":"08001","titulo":"BARRANQUILLA"},
{"id":"08137","titulo":"CAMPO DE LA CRUZ"},
{"id":"08141","titulo":"CANDELARIA"},
{"id":"08296","titulo":"GALAPA"},
{"id":"08132","titulo":"JUAN DE ACOSTA"},
{"id":"08421","titulo":"LURUACO"}]
I haven't found a way to Iterate and fill a SELECT with this data. The select should look like this
<select name="city" id="city">
<option value="ID FROM THE JSON">TITULO FROM THE JSON ARRAY</option>
... AND FOR THE REST OF THE RESULTS
</select>
Thank you beforehand! I am seriously confused.
Decode the JSON first, then add HTML to the select for each city.
function(data) {
var cities = JSON.parse(data);
for(var c in cities) {
document.getElementById('city').innerHTML += '<option value="' + cities[c].id +'">' + cities[c].titulo + '</option>';
}
}
it seems you are using jQuery, so I think you can easily iterate the JSON in your success callback
function(data){
var st=""
for(i in data){
st+="<option id='"+data[i].id+"'>"+data[i].titulo+"</option>"
}
//here st contains all the options
// you just have to append it in your select's html
// I don't know your DOM structure, so if you didn't have anything
// you can add the select, then display it
$("thePlaceWhereYouWantIt").html("<select>"+st+"</select>")
}
It should work, but it depends on your actual HTML
Good luck

How can i append partial view result in to div?

I have a div id="comments"
in this i am displaying 10 comments at a time.
when user want to view next comments, i have provided one button that will collect next 10 comments. for this next comment i have created partial view to display remaining 10 comments into another div morecomments.
My problem is when i am displaying next 10 comments its showing me all 20 comments but whole comments div is getting refreshed, how to prevent loading whole comment div.
My code is here:
<div id="comments">
// Display Comments
<div id="moreButton">
<input type="submit" id="more" class="morerecords" value="More Post" />
</div>
</div>
<div id="morecomments">
</div>
Jquery::
$('.morerecords').livequery("click", function (e) {
// alert("Showing more records...");
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
In above code i am getting 10 comments first time and when user click on More Post button it will show me above 10 comments plus next 10 comments. but whole div is getting refreshed.
What changes i have to do so that i can get user comments without affecting previous showing comments?
Suppose user having 50-60 post in his section then all comments should be display 10+ on More Post button click and so on...
How can i do that?
You need to filter your records and put it in comment div... Your code should like this:
$('.morerecords').livequery("click", function (e) {
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
var older_records = $("#morecomments").text();
$.("comments").append(older_records); //When you will get next record data, older data will be filled in comment div.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
The error is in:
$("#morecomments").html(result);
.html("somevalue") deletes the content, then fills it with whatever parameter you supplied.
Try doing this:
$("#morecomments").html($("#morecomments").html() + result);
or even easier:
$("#morecomments").append(result);
I know this works if you're passing strings, and a partial view is basically a html string. I don't know if there will be any conflict issues with the tags brought along by partial views.
Either way, this is the easiest way to add to an element rather than write over it.
If you are using Entity Framework (which you do), you need to use something like below:
public JsonResult Get(
//this is basically giving how many times you get the comments before
//for example, if you get only one portion of the comments, this should be 1
//if this is the first time, this should be 0
int pageIndex,
//how many entiries you are getting
int pageSize) {
IEnumerable<Foo> list = _context.Foos;
list.Skip(PageIndex * PageSize).Take(pageSize);
if(list.Count() < 1) {
//do something here, there is no source
}
return Json(list);
}
This is returning Json though but you will get the idea. you can modify this based on your needs.
You can use this way for pagination as well. Here is a helper for that:
https://bitbucket.org/tugberk/tugberkug.mvc/src/69ef9e1f1670/TugberkUg.MVC/Helpers/PaginatedList.cs

aggregate form elements into object ?

i am trying to aggregate form elements into object and then send it via ajax here is the code that i start using but i cant figure out how to do the rest
$('.jcart').live('submit', function() {
});
Update 1:
html form
http://pasite.org/code/572
Update 2:
I have successfully submit the form using ajax but it still refreshes the page after submiting
this what i did
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
jQuery has a method called .serialize() that can take all the form elements and put them into an array for just what you are trying to do. Without seeing your html, we really can't tell you much more though.
http://api.jquery.com/serialize/
Something like this might work:
$('.jcart').submit(function() {
$.ajax({
url : form.php,
type : "POST",
data : $(this).serialize(),
});
});
Obviously it would need a little more for full functionality, but that should get you started.
Depending on how many of the values you need (and whether you have things like radio buttons) you can start with the :input selector to grab the elements. Assuming .jcart is your form or container, something like this:
var data = {};
$('.jcart').find(':input').each(function (i, field) {
if ($(field).is('input:checkbox') {
if (field.checked) {
data[field.name] = true;
} else {
data[field.name] = false;
}
} else {
data[field.name] = $(field).val();
}
});
That should get you started.

Resources