acess variable url in ajax - javascript

guys i am trying to make variable url to pass it to ajax call ..i know it is dummy but i cant find a solution and it doesnt work .. here is my code
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
set_fileName: function(fileName){
this.fileName = fileName;
},
get_fileName: function(){
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url : get_fileName(),
error : function(that, e) {
console.log(e);
},
success : function(data) {
var table = "<table>";
$.each(data, function(index, MyList) {
table += '<tr><td>' + MyList.id + '</td><td>' + MyList.name
+ '</td><td>' + MyList.age + '</td><td>'
+ MyList.feedback + '</td><tr>';
});
table += '</table>';
$('body').append(table);
}
});
};

You can load a URL from an external source that is not your problem.
Use the 'this' keyword to fix your problem;
url : this.get_fileName()

get_fileName() is not a function because it's a property on GridLibrary.prototype
you have to use this.get_fileName()

Related

GET Method always receives null value

I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});

Jquery: Global variable or function not returning data

I am at my wits end here.
I am trying to build a report which retrieves data from a JSON array. Which is stored in a local stored file (using HTML5 FileAPI).
I have divided the build into two functions: Report and FileReader
I am able to read the file, and send the content to console.log inside the FileReader function. But I am NOT ABLE to send that data outside the function. I've tried so many different approaches that I've lost count on which and how many. I tried Global Variable, but that stays blank outside the FileReader Function. I tried Promise.deferred etc. etc.
Please help!
var JsData = '';
function fileReader(hente) {
var deferred = $.Deferred();
fs.root.getFile(hente, {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.readAsText(file, "utf-8");
reader.onloadend = function(e) {
JsData = this.result;
console.log('JsData: ' + JsData ); //Check that data has been read
// try this
//return JsData;
// Try Defferred
return deferred.promise(JsData);
};
}, errorHandler);
}, errorHandler);
};
function createDokument(dokName) {
var ClientTable = '';
var kake = Cookies.get(dokNavn);
var visits = JSON.parse(kake);
$.each(visits, function(index, value) {
var hente = value.dok + '_' + value.nr;
//Make sure the variable is blank, for no reason at all
JsData = '';
var promise = fetchVisitInfo(hente + '.oln');
promise.then(function(result) {
/// Test if variable has retrieved the data
console.log('JsData: ' + JsData );
$.each(JsData, function (i,v) {
ClientTable += ' <tr>';
ClientTable += ' <td colspan="3">' + v['orderSum'].Knr + ', ' + v['orderSum'].firma + '</td>';
ClientTable += ' <td width="3%">' + v['orderSum'].oldV + v['orderSum'].newV + '</td>';
ClientTable += ' <td width="15%">' + v['orderSum'].newS + '</td>';
ClientTable += ' <td width="15%">' + v['orderSum'].oldS + '</td>';
ClientTable += ' </tr>';
});
});
});
Any ideas ??

JQuery Ajax button isn't working

I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>

sometimes ajax works & sometime not & click on row function is also not working

can we write two ajax success function on same page because sometimes its work sometime not
doajaxpost function is to load data in 2nd dropdown list when 1st dropdown list onchange function call by using ajax
and searching function is to load data in table by using ajax
but it sometime get execute properly sometimes not showing any result
function doAjaxPost(instituteId) {
alert(instituteId);
// get the form values
/* var name = $('#name').val();
var education = $('#education').val(); */
$.ajax({
type : "POST",
url : "/paymentGateway/merchant",
dataType : "json",
data : "institutionId=" + instituteId,
success : function(data) {
// we have the response
alert(data + "hiee");
var $merchantId = $('#merchant');
$merchantId.find('option').remove();
$("#merchant").append("<option value='ALL'>ALL</option>");
$.each(data, function(key, value) {
$('<option>').val(value.merchantId).text(value.merchantId)
.appendTo($merchantId);
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
function searching() {
// get the form values
var institutionId = $('#instiuteId').val();
var merchantId = $('#merchant').val();
var userType = $('#userType').val();
var userStatus = $('#userStatus').val();
var userId = $('#userId').val();
alert("insti=" + institutionId + "mecrhant=" + merchantId + "usertyep="
+ userType + "users=" + userStatus + "userid=" + userId);
$.ajax({
type : "POST",
url : "/paymentGateway/searching",
dataType : "json",
data : {
institutionId : institutionId,
merchantId : merchantId,
userId : userId,
userStatus : userStatus,
userType : userType
},
success : function(data) {
// we have the response
alert(data);
/* var $merchantId = $('#dynamictable');
$merchantId.find('table').remove();
$('#dynamictable').append('<table></table>');
var table = $('#dynamictable').children(); */
$("#tablenew tbody tr:has(td)").remove();
$.each(data, function(key, value) {
/* alert(value.institutionId); */
$('#tablenew tbody:last').append(
"<tr><td>" + value.userId + "</td><td>"
+ value.firstName + "</td><td>"
+ value.userStatus + "</td><td>"
+ value.userType + "</td><td>"
+ value.userAddedBy + "</td><td>"
+ value.userRegisteredDateTime
+ "</td><td>" + value.recordLastUpdatedBy
+ "</td><td>" + value.recordLastUpdatedTime
+ "</td></tr>");
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
It could be a caching issue, try to setup
$.ajaxSetup({ cache: false });
See
How to prevent a jQuery Ajax request from caching in Internet Explorer?
I got the same problem. You'll have to use the class instead of ID to make it work. Use $(".merchant") to replace $("#merchant"), and update 'merchant' to be a class.

Use jquery to get jsondata

I want to use .getJSON to get data from server. The data can get, but it can not display in page.
js code:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});
});
html code:
<button id="jsondata" name="jsondata" accesskey="g">GetData</button>
<div id="datashow"></div>
The data I got from server display in fire bug:
{"name":"Tom","sex":"male","tel":"456","email":"sdfd#15.com"}
The json parameter for success function should already be parsed as JSON, so loop with a normal loop:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
for(var i in json) {
str += '<tr><td>' + i.name + '</td><td>' + i.sex + '</td><td>' + i.tel + '</td></tr>';
}
str += '</table>';
$("#datashow").append(str);
});
});
});
Try this: (There is no need to loop with $.each)
$(function () {
$("#jsondata").bind("click", function () {
var data = "action=getdata";
$.getJSON("Guess.php", data, function (json) {
var str = '<table><tr><td>日期</td><td>1#铸机产量</td><td>2#铸机产量</td></tr>';
str += '<tr><td>' + json.name + '</td><td>' + json.sex + '</td><td>' + json.tel + '</td></tr>';
str += '</table>';
$("#datashow").append(str);
});
});
});
Try the following code.
$.getJSON("Guess.php",data, function(json) {
// Convert json reponse object to array
json = $.makeArray(json);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});

Categories