Error message on javascript after publishing azure website - javascript

I have a problem here whenever I debug my appication on localhost, it runs perfectly with no errors on the brower, but when I publish it on azure I get an error on the browser.
Here is the error i get:
/Service_Bind?depart_id=1:1 Failed to load resource: the server responded
with a status of 404 (Not Found)
Here is my source code on the view page for javascript:
<script>
$(document).ready(function () {
$('#depart').change(function () {
var id = $(this).val();
$('#Service').empty();
$.get('Service_Bind', { depart_id: id }, function (data) {
var v = '<option>---Select---</option>';
$.each(data, function (i, v1) {
v += '<option value=' + v1.Value + '>' + v1.Text + '</option>';
});
$('#Service').html(v).text();
});
});
$('#Gender').change(function () {
var id = $(this).val();
$('#Item').empty();
$.get('Item_Bind', { Gender_id: id }, function (data) {
var v = '<option>---Select---</option>';
$.each(data, function (i, v1) {
v += '<option value=' + v1.Value + '>' + v1.Text + '</option>';
});
$("#Item").html(v);
});
});
$('#Item').change(function () {
var id = $(this).val();
$('#price').empty();
$.get('Price_Bind', { Price_id: id }, function (data) {
var v = '<option>---Select---</option>';
$.each(data, function (i, v1) {
v += '<option value=' + v1.Value + '>' + v1.Text +
'</option>';
});
$('#price').html(v);
});
});
});
</script>

Here $.get('Service_Bind', { depart_id: id }, function (data) you are trying to call the api/method service_bind but you are not specifying the full url of that api.You need to add baseaddress as well.
For eg, my api is hosted on site www.contoso.com,then my url would be www.constoso.com/Service_Bind

This is what I was suppose to add on the script and it worked. The only problem was to fetch a page so the browser didn't know where was it fetching. Thanks for your help.
$.get('#Url.Action("Gender_Bind", "Request")', { Service_id: id }, function (data)

Related

Drop last query in client side

I have a dropdown who populate depending of selected radio button:
JS
$(function getJsonProveedores() {
var items = "";
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
});
It load correctly all JSON, but I have an issue removing last query, for example if i click Proveedor radio, it load:
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
and next if I click Sucursal radio, it load
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
The problem is I keep seeing first query result of
$.getJSON("#Url.Action("GetProveedores", "Agenda")"
instead getting only second one:
$.getJSON("#Url.Action("GetUnidades", "Agenda")"
Controller:
public ActionResult GetProveedores()
{
var listaProveedores = db.Proveedores.ToList();
return Json(listaProveedores, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUnidades()
{
var listaUnidades = db.Unidades.ToList();
return Json(listaUnidades, JsonRequestBehavior.AllowGet);
}
public ActionResult GetUsuario()
{
var listaUsuarios = db.Usuarios.ToList();
return Json(listaUsuarios, JsonRequestBehavior.AllowGet);
}
What can be the problem there? Regards
The way the functions/variables are structured, items never falls out of scope. So it never gets reset. Each subsequent AJAX call is simply appending to it.
Instead, get rid of the items variable from its current scope and use one local to each scope where you need it:
$(function getJsonProveedores() {
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
var items = ""; // <--- declare it here
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
}
else if (this.value == 'Sucursal') {
// ... and so on, declaring an "items" in each scope where you need it

JQuery Dynamic Objects load selectors

I've a form when I click one radio button to load a subform.
Ok this work perfectly, but has 3 selectors that I need external data when only this subform loaded.
So, I did in this way:
$(document).on('focus', '#reemb', function () {
$.getJSON("/banks.php", function (json) {
$('#bank').empty();
$.each(json, function (i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code));
});
});
$.getJSON('/statecity.json', function (data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function (key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options);
$("#state").change(function () {
var options_city = '';
var str = "";
$("#state option:selected").each(function () {
str += $(this).text();
});
$.each(data, function (key, val) {
if (val.name == str) {
$.each(val.city, function (key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city);
}).change();
});
});
This work fine, but everytime that I need to change one date the selectors clear and load again.
I tried to add tag onload to start the function to load selectors in this subform, but don't works. Also tried change events to .on, but also don't work.
How I need to do this?
Thx!!
Not knowing what #reemb is, I would empty the relevant sub selects:
If the container holding the selects is ALSO emptied, you need to delegate all even handlers of objects inside too - like $(document).on("change","#bank", function() {
$(document).on('click', '#reemb', function() {
$.getJSON("/banks.php", function(json) {
$('#bank').empty();
$.each(json, function(i, obj) {
$('#bank').append($('<option>').text(obj.name).attr('value', obj.code)).change();
});
});
$('#bank').on("change", function() {
$('#city').empty();
$.getJSON('/statecity.json', function(data) {
var items = [];
var options = '<option value="">State</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.name + '">' + val.name + '</option>';
});
$("#state").html(options).change(); // if needed
});
$("#state").on("change", function() {
var options_city = '';
var str = "";
$("#state option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.name == str) {
$.each(val.city, function(key_city, val_city) {
options_city += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#city ").html(options_city).change(); // if needed
});
});
});

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>

How to get json value from response ajax?

My json response is like this :
http://imgur.com/WRfauG9
http://www.jsoneditoronline.org/?id=c4ded7d2934f62fb68a276cfb118d52e
I want display HotelNo, RmGrade, Meal and TotalRate
I try like this :
...
success: function (response) {
console.log(response);
$.each(response, function() {
$.each(this, function(k, v) {
// console.log(k);
// console.log(v);
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
});
}
...
But it's not working
How to get json value from response ajax correctly?
Any solution to solve my problem
Thank you very much
It would be easy to help you if you give us a sample of your JSON, but in the meantime, I suggest to loop on response.SearchAvailResponse.Hotel instead of response:
success: function (response) {
$.each(response.SearchAvailResponse.Hotel, function() {
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
}
Waiting for your JSON.
As I mentionned before, you will not have access to things like HotelNo by looping only through response. Here is a working solution:
`
for(i=0; i<response.SearchAvailResponse.Hotel.length; i++){
console.log(js.SearchAvailResponse.Hotel[i].HotelNo);
}
response.SearchAvailResponse.Hotel is an array of objects.
Assumption is that you are getting an array.
You dont have to have loop inside loop.
success: function (response) {
console.log(response);
$.each(response, function(index, v) {
setTimeout(function () {
$parent.find('.loading').html(v.HotelNo + '<br>' + v.RmGrade + '<br>' + v.Meal + '<br>' + v.TotalRate);
}, 2000);
});
}

JS Error with JSON Response Nodes

I have a page that generates a dropdown of options based on a prior selection. Once the parent dropdown is selected, that triggers a AJAX call which returns a JSON response of the child options.
function fetchLines(line) {
// Define vars we will use in this function
var dropdown = '';
// AJAX call to lines/sublines
$.ajax({
url: baseURL + "index.php/Project/fetchLines",
type: 'POST',
cache: false,
dataType: "json",
data: {
lineType: line
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
dropdown += '<option></option>';
$(data.lines).each(function() {
dropdown += '<optgroup label="' + this.line + '">';
if (this.sublines.options) {
$(this.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
dropdown += '</optgroup>';
});
$('[name=line]').empty().append(dropdown).select2("enable", true).trigger('change');
}
});
}
The issue I am running into is that there are some times no sublines in the JSON response which is causing the function to error out and not show results at all.
TypeError: this.sublines is undefined
JSON Response:
[
{
"line":"Business",
"sublines":{
"options":[
{
"subLine":"Accounts"
}
]
}
},
{
"line":"Consumer",
"sublines":{
"options":[
{
"subLine":"Cause"
},
{
"subLine":"Financial Services"
}
]
}
},
{
"line":"Risk"
}
]
Is there a way I can prevent a missing node subLines from breaking the function?
Ok, don't take it wrong, but it looks like you have no idea what you're doing. Just trying to use variables like they would be magically there.
I think this is what you're trying to do:
var dropdown = '<option></option>';
// iterate over your lines
$.each(data, function(i, line) {
// check id there's sublines (may be needed to check if there's options too)
if (line.sublines) {
// start an opt group only if there's sublines
dropdown += '<optgroup label="' + line + '">';
// iterate over it's options
$.each(line.sublines.options, function(j, option) {
// add the option to the html
dropdown += '<option value="' + option + '">' + option + '</option>';
});
// close the opt group
dropdown += '</optgroup>';
}
});
// replace the select content and trigger a change
$('[name="line"]').html(dropdown).select2('enable', true).trigger('change');
Check if subLine exists previously:
if (this.sublines.options) {
$(this.sublines.options).each(function() {
if (this.subLine)
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
Clearly in your JSON response not all objects from the array have the property sublines. And this is the line which is make the code to fail.
if (this.sublines.options) {
I'd suggest improving it to the following by checking if it has the property or not:
if (this.sublines && this.sublines.options) {
Check for sublines first...
if (this.sublines) {
if (this.sublines.options) {
$(this.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
}
I think you want to achieve something like this:
Fiddle: https://jsfiddle.net/a3bx77vm/3/
var dropdown = '';
for(var i = 0; i < data.length; i ++)
{
dropdown += '<option></option>';
var eachdata = data[i];
dropdown += '<optgroup label="' + eachdata.line + '">';
if(eachdata.sublines)
{
if (eachdata.sublines.options) {
$(eachdata.sublines.options).each(function() {
dropdown += '<option value="' + this.subLine + '">' + this.subLine + '</option>';
});
}
}
dropdown += '</optgroup>';
}
$("#dropdown").append($(dropdown));
The parsing was wrong because the data you get is an array, and it doesn't have property called lines.

Categories