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);
});
}
Related
I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}
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)
I have ajax in my cart page where i get destination info of the user and return shipping options to them in order to calculate their shipping cost.
So far everything works except I'm not sure how to loop returned data from my 3rd party website.
Here is what I need:
I need Loop trough this data and get marked information in drop-down.
Red: as my option group.
Orange - Green - Purple: as my option. LIKE:
OKE - 48.000 - 5-7 Days
network result
console result
Codes
This is my ajax code for that:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
// $('#des').empty();
// $('#des').append(
// '<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
// );
$.each(data.data, function(key, value) {
console.log(value);
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
Thanks.
SOLVED
I retrieved my data with code below:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<optgroup label="' + value['code'] + '" /><option id="postchoose" class="form-control" value="'+ value['code'] +'">'+ value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option></optgroup>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
there is only 1 issue i'm facing I would like to be done and that's grouping results with <optgroup> as you see in my screenshot below my <optgroup> in looping for each one of my options.
How can I fix this?
For example, I have a class:
classA.js
$(document).ready(function() {
select2_scroll('element_name_id')
});
calling a function from
classB.js
function select2_scroll(elementId, queryString) {
resource_url: 'something/';
$('#' + elementId).select2({
allowClear: true,
ajax: {
url: resource_url,
dataType: 'json',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
search_term: term,
page: page
};
},
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more };
}
},
formatResult: resourceName,
formatSelection: resourceName,
});
}
function resourceName(resource) {
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + elementId + '_id" value="' + resource.id + '"/>';
return format;
}
How do I avoid using a global variable to pass the elementId variable? I can't call resourceName directly and pass the elementId in by calling resourceName(resource, elementId).
Am I missing something from the Select2 component?
You could try something like :
formatResult: ()=>{
resourceName(resource, elementId);
},
formatSelection: ()=>{
resourceName(resource, elementId);
},
Add your element Id in your "results" return
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more, elementId: elementId };
}
And use it in your function:
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + resource.elementId + '_id" value="' + resource.id + '"/>';
Let me know, if this works for you. I didn't have tested it with your example
I found a solution to my problem. I can just do
...
formatResult: function(resource) {
return resourceName(resource, elementId)
},
formatSelection: function(resource) {
return resourceName(resource, elementId)
},
....
Thanks!
I'm trying to parse data returned from $.post().
[{"id":"1","text":"USD"},
{"id":"2","text":"CNY"},
{"id":"3","text":"PHP"},
{"id":"4","text":"AUD"},
{"id":"5","text":"SGD"},
{"id":"6","text":"JPY"}]
using this approach Jquery, looping over a json array
I did something like this:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$.each(data,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it gives me the error:
Uncaught TypeError: Cannot use 'in' operator to search for '120' in [{"id":"2","text":"CNY"},{"id":"3","text":"PHP"},{"id":"4","text":"AUD"},{"id":"5","text":"SGD"},{"id":"6","text":"JPY"}]
I also tried:
$.post(
base_url+'cgame/currency',
{ gameID: gameID },
function(data) {
$(this).html();
$(data).each(function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
);
but it also gives me the error:
Uncaught Error: Syntax error, unrecognized expression: [{"id":"1","text":"USD"},{"id":"6","text":"JPY"}]
How should I be doing this?
Your data comes in the form of array so you need to loop through each index and then fetch the values. So you can replace this :-
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
with :-
$.each( obj, function( key) {
console.log( obj[key].id + ':' + obj[key].text);
});
or you can do this :-
$.each( obj, function( key, value ) {
console.log( value.id + ':' + value.text);
});
key is the index of array. It will return 0,1,2..
I think the argument passed to your success callback function is of type string. Change it to:
function(data) {
var parsedData = JSON.parse(data);
$(this).html();
$.each(parsedData ,function(idx, obj) {
$(obj).each(function(key, value) {
console.log(key + ": " + value);
});
});
}
function(data) {
var value = JSON.parse(data);
$.each(value ,function(idx, obj) {
console.log("id : "+obj.id+" "+text:"+obj.text);
});
}
try this
$.post(base_url+'cgame/currency',{ gameID: gameID },
function(data) {
$(this).html(); //<-- becareful $(this) might not be the element you think it is
$.each(data,function(idx, obj) {
console.log( "id : " + obj.id);
console.log( "text: " + obj.text);
});
},'JSON');