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)
Related
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
I am using this timeline plug-in as a base for my own: http://www.jqueryscript.net/other/Create-A-Simple-Vertical-Timeline-with-jQuery-CSS.html
The code I'm trying to change is step 3. Create events for the timeline using Javascript array object.
My code:
(note that #events is my timeline container for all the data)
$(function() {
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
for (i = 0; i < data.timeline.length; i++) {
event = data.timeline[i];
numDate = event.shortdate;
txtTitle = event.longdate;
eventType = event.category;
eventDesc = event.description;
dataInfo = '{ date: new Date(' + numDate + '), type: "' + eventType + '", title: "' + txtTitle + '", description: "' + eventDesc + '" }';
dataArray.push(dataInfo);
}
}
});
$('#events').timeline({
data: dataArray,
height: 800 // in pixel
});
However, this is causing an error in the function that generates the timeline:
TypeError: firstDate is undefined
var tempDate = new Date(firstDate.getTime());
I'm thinking that perhaps something goofy is going on with my dataInfo variable. Any tips would be greatly appreciated!
Your biggest issue is that you're creating an array of strings, but the plugin expects an array of objects (not JSON, but an actual array of objects).
$(function () {
var dataArray = [];
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function (data) {
for (i = 0; i < data.timeline.length; i++) {
event = data.timeline[i];
dataArray.push({
date: new Date(event.shortdate),
type: event.category,
title: event.longdate,
description: event.description
});
}
}
});
$('#events').timeline({
data: dataArray,
height: 800 // in pixel
});
});
Again, even if the plugin did want JSON (which is a string) as opposed to an array of objects, you weren't providing it with that either--you were proving an array of strings, each of which were an attempt at JSON serializing some data.
Also, if you ever do need to produce JSON, don't do it manually with string concatenation. Create an actual data structure, then JSON.stringify() it.
Finally, you need to ensure that your shortdate property on the returned data is something which Date can use to accurately create the represented date.
Unfortunately the plug-in doesn't look to be all that well documented (as an aside, consider this one perhaps?) but based on just the article & your sample, the issue is likely in your dataInfo as you suspect.
You're not actually providing a valid Date object for the value of the date property; my guess is it should be this:
numDate = new Date(event.shortdate);
...
dataInfo = '{ date:' + numDate + ', type: "' + eventType + '", title: "' + txtTitle + '", description: "' + eventDesc + '" }';
EDIT: Look to JAAulde's answer for the correct way to do this.
I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});
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);
}
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()