MVC3 Ajax displayin all values in array - asp.net-mvc-3

I get my values from my action control but i wanna show all my values. How to use for loop or foreach in ajax to show array all of elements ?
Here is my script
$.ajax({
type: "get", url: "Home/Oku", data: {}, dataType: "json",
success: function (data) {
for (var i = 0; i< data.length; i++) {
$("img#myimage").attr("src", data[i])
i++;
}

It is not very clear what you are trying to do. It is not clear what format your controller action uses to return the data. From the code you have shown I can assume that it returns an array of strings. And then I suppose that those strings represent urls to some images because you seem to be attempting to assign them to the src attribute of an img tag. Except that you are using an id selector and always overwriting the same img tag for each element.
If you want to have multiple images, then you could create them dynamically. Start by creating an empty placeholder:
<div id="images"></div>
and then:
$.ajax({
url: 'Home/Oku',
type: 'GET',
success: function (data) {
var images = '';
for (var i = 0; i < data.length; i++) {
images = images + '<div><img src="' + data[i] + '" /></div>';
}
$('#images').html(images);
}
});
This assumes that your controller action returns a JSON encoded array of strings representing urls for the images:
public ActionResult Oku()
{
var imageUrls = new[]
{
"http://example.com/foo.jpg",
"http://example.com/bar.jpg"
};
return Json(imageUrls, JsonRequestBehavior.AllowGet);
}

Related

Why the array will not send through the ajax call?

In my ajax code I'm sending an associative array to the go lang api but go lang would not receiving any array. Why?
for (var i = 1; i <= optionsArr; i++) {
span_arr.push({
day : valueSelected,
time_slug : i,
timing : $("#"+i).text(),
count : $('#select_count'+i).val()
});
}
console.log(span_arr[1].time_slug);
$.ajax({
url:"/api/v1/provider_spot",
type:"POST",
data:{span_arr:span_arr},
dataType:"json",
success:function(response){
console.log(response);
}
});
Why this ajax will not sending the array to the go api?
Here in go lang following mvc structure I want to receiving this data:
Route{"SaveProviderSpot", "POST", "/provider_spot", controller.SaveProviderSpot},
func SaveProviderSpot(c *gin.Context) {
fmt.Println(c.PostForm("span_arr"))
}
You can not send an array directly from client to server,due to the array definition may not be the same in both sides.
Two ways to solve it:
a. You can convert the array into a json string in the clinet,then send it to server as a string parameter,in the server side,you can parse it and convert it to array
b. Iterate the array,and convert it to a string using some special characters,also pass to server as string parameter,an example is as below:
var dataStr = "";
for (var i = 1; i <= optionsArr; i++) {
//each array element split with 3 semicolons,and each property in element split with 2 semicolons
dataStr += valueSelected + ";;" + i + ";;" + $("#"+i).text()
+ ";;" + $('#select_count'+i).val() + ";;;";
}
$.ajax({
url:"/api/v1/provider_spot",
type:"POST",
data:{dataStr:dataStr},
dataType:"json",
success:function(response){
console.log(response);
}
});
//now it is correct

Dragula not sending AJAX request

I am using the following code to sort the rows of a table based on Ids. I am using Dragula for drag and drop functionality. The Sorted Ids is presented in the variable sortedIDs. The alert present within if(sortedIDs) is showing an alert, but no request is being sent using AJAX.
var container = document.getElementById('tb');
var rows = container.children;
var nodeListForEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
var sortableTable = dragula([container]);
var pingu='';
sortableTable.on('dragend', function() {
nodeListForEach(rows, function (index, row) {
//alert(row.id);
pingu=pingu+','+row.id;
//alert(pingu);
// row.lastElementChild.textContent = index + 1;
// row.dataset.rowPosition = index + 1;
});
var sortedIDs=pingu;
pingu='';
// alert (sortedIDs);
if (sortedIDs) {
alert(sortedIDs);
$.ajax({
type: 'GET',
url: '<?php echo $site_url . 'index.php/API/p2376ghDSPOLWYBdhBT'?>',
data: 'lmqSPOEhyVt87H6tBYSfdreg=' + sortedIDs + '&hjhqweuty87685gh87GCfsc6HF=' + sbds98JWUDGHKJ98yujg,
success: function (tata) {
alert (tata);
if (tata == '1') {
$("#success").show();
$('#success').delay(2000).fadeOut('slow');
} else {
$("#failure").show();
$('#failure').delay(5000).fadeOut('slow');
}
}
});
} else {
//$('#ms').html('<option value="">Select Q level first</option>');
}
});
And when i am adding
error : function(jqXHR, textStatus, errorThrown){
}
for showing AJAX error, it starts throwing the alert too.
Any sort of help would be deeply appreciated.
Thanks
I solved the problem. I forgot to retrieve the value of an attribute and send it to the API.
var sbds98JWUDGHKJ98yujg = $('#p2JMopns3hfBubNNHJeer').val();

Insert json data into text input

I have a function that adds a new patient to the database, gets the json data back and then adds the new patient to the select menu. That works fine. I need to add that data into the corresponding text inputs i.e., input#patient_id, input#patient_firstname, etc. which should occur in the .ajax complete, but nothing happens.
Would appreciate any help!!
Ajax
$('#newpatient').click(function() {
var patientadd = $('#patientaddform').serializeArray();
$.ajax({
url: 'adam.php',
type: "POST",
data: patientadd,
dataType: 'json',
success: function(data){
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option selected="selected" value="' + data[i].patient_id + '">' + data[i].patient_firstname + ' ' + data[i].patient_lastname + ' : ' + data[i].patient_dob + '</option>';
}
alert(html);
$('#patientselect').prepend(html);
$('#patientselect').selectmenu('refresh', true);
},
complete: function (data) {
for(var id in data) {
$('input#' + id).val( data[id] );
}
}
});
});
json data returned
[{"patient_id":"22","patient_firstname":"","patient_lastname":"","patient_dob":"0000-00-00"}]
the corresponding text input fields are input#patient_id, input#patient_firstname, etc, that is why I'm trying to add the 'input#' to the id in the ajax complete and then add that val to the text input.
The params for the complete call back are jqXHR and textStatus. Not data. See http://api.jquery.com/jQuery.ajax/ for the correct definition of complete(jqXHR, textStatus)
Your json data is an array of objects, so you have to add take the first element of the array like this:
for(var id in data[0]) {
$('input#' + id).val( data[0][id] );
}
Or you have to adapt the server response.
Also consider #techfoobar's answer:
The params for the complete call back are jqXHR and textStatus. Not data. See http://api.jquery.com/jQuery.ajax/ for the correct definition of complete(jqXHR, textStatus)

Synchronised Ajax requests with JQuery in a loop

I have the following situation: I need to make synchronized Ajax requests within a loop and display the returned result after each iteration in a div-element (appended on top with the previous results at the bottom). The response time of each request can be different but the order in which it should be displayed should be the same as issued. Here is an example with 3 requests. Lets say request "A" needs 3 seconds, "B" needs 1 second and "C" needs 5 seconds. The order I want to display the result is A, B, C as the requests were issued but the code I use shows the results in B, A, C.
Here is the code (JQuery Ajax request):
$(document).ready(function(){
var json = document.getElementById("hCategories").value;
var categories = eval( '(' + json + ')' );
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
$("#content").append(data);
}
});
});
I thought it would work with "async:false" but then it waits until every Ajax call is finished and presents the results after the loop. I hope some of you can point out some different solutions, I am pretty much stuck.
Thanks in advance,
Cheers Chris
EDIT: Thanks for all the possible solutions, I will try these now one by one and come back with that one that fits my problem.
I have two solution proposals for this problem:
Populate generated divs
You could generate divs with ids in the loop and populate them when the request finishes:
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
for (curCat in categories) {
(function(curCat) {
var curCatKey = categories[curCat]['grKey'];
$('#content').append('<div id="category-"' + escape(curCat) + '/>');
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val()),
success: function(data) {
$("#category-" + escape(curCat)).html(data);
}
});
})(curCat);
}
});
Or use a deferred
You can store jqXHR objects in an array and use a deferred to call the success functions in order, when all calls have finished.
$(document).ready(function() {
var json = document.getElementById("hCategories").value;
var categories = eval('(' + json + ')');
var requests;
for (curCat in categories) {
var curCatKey = categories[curCat]['grKey'];
requests.push($.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) + "&search=" + escape($("#hQuery").val())
}));
}
$.when.apply(requests).done(function() {
for (i in requests) {
requests[i].success(function(data) {
$("#content").append(data);
});
}
});
});
The first method has the advantage that it populates the containers continuously. I have not tested either of these function, but the logic should work the way I described it.
This would do the trick
var results = [];
var idx = 0;
for(curCat in categories) {
curCatKey = categories[curCat]['grKey'];
(function( i ) {
$.ajax({
type: "POST",
url: "get_results.php",
data: "category=" + escape(curCatKey) +
"&search=" + escape($("#hQuery").val()),
timeout: 8000,
async: false,
success: function(data) {
results[i] = data;
if (i == idx - 1) { // last one
for (var j=0; j < results.length; j++) {
$("#content").append(results[j]);
}
}
}
});
})(idx++);
I think something like this is what you're looking for. Might need some tweaking, I'm a little rusty on Deferred. Read up on it though, mighty powerful
deferred = $.Deferred()
for(curCat in categories) {
deferred.pipe(
function(resp){
postData = {} // set up your data...
return $.post("get_results.php", {data: postData, timeout: 8000})
.done(function(content){ $("#content").append(content) })
})
)
}
// Trigger the whole chain of requests
deferred.resolve()

google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances.
Everything works great except that the distance is only returned for one of the routes.
I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below?
for (var i = 1; i <= numJourneys; i++) {
var mapContainer = 'directionsMap' + i;
var directionContainer = $('#getDistance' + i);
$.ajax({
async: false,
type: "POST",
url: "Journey/LoadWayPoints",
data: "{'args': '" + i + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var map = new GMap2(document.getElementById(mapContainer));
var distance = directionContainer;
var wp = new Array();
//routes
var counter = 0;
$.each(content, function () {
wp[counter] = new GLatLng(this['Lat'], this['Long']);
counter = counter + 1;
});
map.clearOverlays();
map.setCenter(wp[0], 14);
// load directions
directions = new GDirections(map);
GEvent.addListener(directions, "load", function () {
alert(directions.getDistance());
//directionContainer.html(directions.getDistance().html);
});
directions.loadFromWaypoints(wp, { getSteps: true });
}
}
});
}
The issue was down to a non declared variable. Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out.
var directions = new GDirections(map);
Doing the above worked for me.

Resources