How to use pass ajax data that is displaying in html? - javascript

I have a question, that I can't seem to find the 'best' solution for my question.. I have an AJAX call that displays data in the DOM, via jQuery.
JSON
[{
"id":"123"
},
{ "id":"456"
}]
JS
$(document).ready(function() {
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
var html = '';
$.each(data, function(i) {
html += '<p>My ID: ' + data[i].id + '</p>';
}
$('#id').append(html);
},
error: function(err) {
console.log(err);
}
})
});
As you can see I am displaying that data here. I would like to pass that ID to another AJAX call by selecting a checkbox and pushing a button or perhaps clicking a link. Whats the best way to accomplish this?
EDIT: I apologize, my actual issue is related to array data. I have updated the code. I am displaying an JSON array in the html now, and I want to pass the id of the user/row that I click?
Thanks,
Andy

$(document).ready(function() {
var resid;
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
resid = data.id;
var html = '';
html += '<p>My ID: ' + data.id + '</p>'; $('#id').append(html);
},
error: function(err){
console.log(err);
}
});
$('link').click(function () {
// pass id to second ajax
});
});

try jquery-template
https://github.com/codepb/jquery-template
hope help you

Related

How to get variable from one Ajax function to work in another Ajax function

I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);

Trying to populate Select with JSON data using JQUERY

It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
The JS is this
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var $select = $('#newStatus');
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
The JSON looks like this:
[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
I think you need something like this.
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var json = $.parseJSON(response);
var $select = $('#newStatus');
$.each(json ,function(index, object)
{
$select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.
Then you could use the $.each() function to loop through the data:
var json = $.parseJSON(response);

What's the error in following function code of jQuery?

I've written one jQuery function to get the city and state code based upon the zip code value but facing some issue with some errors. Can someone please help me in correcting the mistakes I'm making here.
Following is my code :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {'request_type':'ajax', 'op':'get_test_category_list','zip_code =' + el.val()},
success: function(result, success) {
$("#city").val(result.city);
$("#state_code").val(result.state);
}
});
}
});
});
Thanks in advance.
The issue is in your data object, you have invalid syntax. Change this:
'zip_code =' + el.val()
To this:
'zip_code': el.val()
The full object should look something like this:
data: {
'request_type': 'ajax',
'op': 'get_test_category_list',
'zip_code': el.val()
},
I think the problem is with data part of the ajax
Change it like this
data: {request_type:"ajax", op:"get_test_category_list",zip_code : el.val()},

Javascript failing in external file only

Can anyone tell me why I get an error on the 2nd line saying 'unexpected string' but works fine when I have it directly on my view (i'm using MVC 3, not that it makes a difference):
function getUsers(processId) {
$.ajax({
url: "#Url.Action('GetProcessApprovers', 'Risk')",
data: { processId: processId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "<option value=\"\">-- Please select --</option>"
if (data != "") {
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
}
$("#ProcessOwnerId").html(items);
}
});
};
Because your url: "#Url.Action('GetProcessApprovers', 'Risk')", only executes in the context of the view, not in an external JS file. It's razor code.
You need to pass the url to the Javascript in some other way, perhaps as a parameter of your function.
getUsers(processId, ajaxUrl)
Another way would be to write out the url from the HtmlHelper into a data attribute in your view and then pick it up in your Javascript.
HTML
<div id="someContainer" data-url="#Url.Action('GetProcessApprovers', 'Risk')">...
JS
var url = $("#someContainer").attr("data-url");
Your url parametre is has the issue.
please change it like this:
url: '#Url.Action("GetProcessApprovers", "Risk")',
Hope it works

Drawind Dynamic series and points with Highchart and ajax

I try to get several series of data from employees and get them drawed through HighCharts.
I don't know the company till the user click, so then I get trough ajax all the employees and their data (points).
I have a select box where I choose the company. Once done, I call via AJAX/jQuery the server to get data added to HighChart:
$("#company").change(function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: xxxxx,
async: false,
data: { company: company},
success: function(data) {
$.each(data, function(val, text) {
alert (val);
alert (text);
chart2.addSeries({
name: val,
data: text
});
});
}
...
Data I get from the server trough Firebug is in this way:
{"Employee1":[["1356908400000","10.00"],["1359586800000","11.00"], ["1362006000000","12.00"],["1364684400000","13.45"]],"Employee2":[["1356908400000","10.00"],["1359586800000","11.00"],["1362006000000","12.00"],["1364684400000","13.45"]]}
Employee1 and Employee2 should be the series.
However when I call addseries method I get this error:
Uncaught Highcharts error #14: www.highcharts.com/errors/14
It seems data doesn't like to Highcharts.
When I debug through alerts, I get this:
alert (val)->Employee1
alert (text)=1356908400000,10.00,1359586800000,11.00,1362006000000,12.00,1364684400000,13.45
This example is working fine when I put data without ajax.
Any idea?
I've found the answer :-)
text is an array so I need another $.each to read it and format the result:
success: function(data) {
$("html").css('cursor','auto');
$.each(data, function(val, text) {
counter = 0;
$.each(text, function() {
if (counter==0) {
employee_data= "[" + this + "]";
}
else{
employee_data= employee_data + "," + "[" + this + "]";
}
counter=1
});
employee_data = "["+ + "]";
chart.addSeries({
name: val,
data: employee_data
});
});
},

Categories

Resources