Why the array will not send through the ajax call? - ajax

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

Related

I want the returned data to be written to the div tag of the html

function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html(reponse);
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});
I am trying to pass variable q to a php file and get back the result . I am getting the result but I am getting an error paramete q is undefined .
You can use JSON.stringify:
function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html( JSON.stringify(reponse) );
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});

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)

MVC3 Ajax displayin all values in array

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);
}

How to Parse JSON Object/Array in Ajax

How will I be able to get the value of updated in this json that is from my web service:
{"listener":{"id":"1","updated":"false"}}
Here's what I've tried:
$.ajax({
...
success : function(data) {
console.log("received listener: " + data);
var received = JSON.parse(JSON.stringify(data));
var listener = received.listener;
var length = listener.length;
//alert('returned json' + data + ' no. of products received: ' + length);
console.log('returned json' + listener + ' no. of listener received: ' + length); //it says undefined for the length
var updated = listener[0].updated;
}
});
Thanks.
Firstly, this line doesn't make sense:
var received = JSON.parse(JSON.stringify(data));
JSON.stringify converts a JSON structure to a string, and JSON.parse does the opposite. In other words:
var received = data.listener; // is equivalent.
Secondly, received is an object:
{"id":"1","updated":"false"}
It's not an array, so it does not have a length property. If you were looking to get the id of the received object then you'd obviously use:
var updated = listener.id;
For your code to work data would have to look like this:
{"listener":[{"id":"1","updated":"false"}]}

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()

Resources