Simple ajax request - javascript

I am new to ajax and am trying to get the following script working. I just want to take info from a json object and print it to the document.
Here is the JSON file called companyinfo.json:
{
'id':1,
'name':'Stack'
}
The Ajax request looks like this:
ar xhr = false;
var xPos, yPos;
$(function(){
var submitButton = $("#dostuff");
submitButton.onclick = sendInfoRequest;
});
function sendInfoRequest (evt) {
if (evt) {
var company1 = $("#companyInput1").val;
var company2 = $("#companyInput2").val;
}
else {
evt = window.event;
var company = evt.srcElement;
}
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
data: company1,
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});
return false;
}
console.log(data.id);
To start simple. I just console.log the data.id to see if the script returned a value from the json file.
To write it to the document I would do something like this, calling the showContents function in the callback function above:
function showContents(companyNumber) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseXML;
$("." + data.companyName.toLowerCase + companyNumber).innerHTML(data.companyName)
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
}
}
I'm pretty new to Ajax, but hopefully that makes some sense. Thanks

if you are trying to get something i think you should add
type:"GET"
on your $.ajax it should look like this.
$.ajax({
url : 'companyinfo.json',
dataType: 'json',
type:"GET",
contentType: "application/json; charset=utf-8",
data: company1, //What is your purpose for adding this?
success: function(data) {
console.log(data);
var items = new Array ();
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
}
});

Im not sure about this in your code:
var company1 = $("#companyInput1").val; //should it be with ()??
var company2 = $("#companyInput2").val; //should it be with ()??
should it be with () like this one:
var company1 = $("#companyInput1").val();
var company2 = $("#companyInput2").val();

The easiest way to get and parse JSON is to use $.getJSON
// you need to use a map as your data => {key : value}
$.getJSON("companyinfo.json", {company : company1}, function(data){
console.log(data);
var items = []; // new Array();
$.each(data, function(key, val){
items.push('<li id="' + key + '">' + val + '</li>');
});
// do something with items
});

you can do like this:
$.getJSON("getJson.ashx", { Index: 1 }, function (d) {
alert(d);
});

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 not working while process dynamically

The below code works for me
function gethotelsbydestination(dest_id) {
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
$("#divid").html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
$("#divid").append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
But when i use below code not returns anything.divv is the id of an dropdown passed from php page
function gethotelsbydestination(dest_id, divv) {
var divdrp = "$('#" + divv + "')";
$.ajax({
url: "controller/gethotels.php",
dataType: "json",
data: "id=" + dest_id,
success: function(data) {
divdrp.html("");
$.each(data, function(index, item) {
var val = item.id;
var text = item.name;
divdrp.append(
$('<option></option>').val(val).html(text)
);
})
}
});
}
The problem is var divdrp="$('#"+divv+"')";
Any Solution please
You can't concatenate directly. Use this:
divdrp = $('#' + divv);
instead of this:
var divdrp = "$('#" + divv + "')"; // it is not a jquery object

Append returned data to different elements based on objects names

How do you append json returned objects to different elements based on the object's name? My JSON data is bigger than the following example so I wonder if it's a good idea to use if statement in .ajax for each object:
JSON Example Data
[{"name":"Europe","year":"2000"},{"name":"Asia","year":"2001"},{"name":"Africa","year":"2002"}]
HTML
<div class="Europe"></div>
<div class="Asia"></div>
<div class="Africa"></div>
JS
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
item_html='<h3>'+name+'</h3><div>'+item.year+'</div>';
});
if (name == Africa){
$('.Africa').append(item_html);
}
if (name == Europe){
$('.Europe').append(item_html);
}
if (name == Asia){
$('.Asia').append(item_html);
}
},
error: function () {$('.Europe').append("<b>No Results Returned</b>");}
});
Move your if block in each
$(data).each(function (index, item) {
var name = item.name;
item_html = '<h3>' + name + '</h3><div>' + item.year + '</div>';
if(name == 'Africa') {
$('.Africa').append(item_html);
}
if(name == 'Europe') {
$('.Europe').append(item_html);
}
if(name == 'Asia') {
$('.Asia').append(item_html);
}
});
I think since the name and class names are the same you can use it to find the target element within the .each() loop and set its content like
$.ajax({
url: "text.json",
success: function (data) {
var item_html;
$(data).each(function (index, item) {
var name = item.name;
$('.' + name).html('<h3>' + name + '</h3><div>' + item.year + '</div>')
});
},
error: function () {
$('.Europe').append("<b>No Results Returned</b>");
}
});

Jquery ajax Check if there results are empty

I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}

what is [object Object]?

why instead giving data(value) of database give me the [object Object]?
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
$(".list_name").append('<p>' + data + '</p>');
$('.list_name p a').click( function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
});
results url is:(json_encode()) :
[{"name":"333333"},{"name":"\u0633\u0644"},{"name":"\u0633\u0644\u0627\u0633\u06cc"},{"name":"\u0633\u0644\u0627\u0633\u0633"},{"name":"\u0633\u0644\u0627\u0645"}]
update: full code:
$('.auto_complete').keyup(function () {
var id = '#' + this.id;
var alt = $(id).attr('alt'); var id = $(this).attr('id'); var name = $(this).attr('name');
var url = alt + id + '/' + name;
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
data is not a string, but a JSON object, which is basically a Javascript Object. You access it as you would any JS object/array (looks like your result string is an array)
So you can do something like this: data[1].name
data is a list (It is javascript object).
toString( list ) in javascript gives "object Object"
data[0].name will return "333333"
To make a string from a complex object write your own function.
It looks like your Ajax call is returning an array of structures. Each element in the array is a name-value pair. Given that data is an array, the first element is data[0] so you might do something like:
var firstElem = data[0];
var firstName = firstElem.name;
alert("The first name is: " + firstName);
If you want to add all of the names into your html, you would need to loop through the array, each time appending the current element.
If you wanted to show all names, you could do
var names = "";
for (var i=0; i<data.length; i++) {
var elem = data[i];
names = names + elem.name + ", ";
}
I would rewrite it in the following way
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: url,
data: dataObj,
cache: false,
dataType: 'json',
success: function (data) {
$(".list_name").show().html('');
for (i in data) {
var obj = $('' + data[i].name + '');
obj.click(function(e) {
e.preventDefault();
$('<b>' + b + '، </b><input type="text" name="hotel[]" value="' + b + '" style="border: none; display: none;" />').appendTo($('.auto_box span'));
$(this).remove();
return false;
});
var p = $('p');
p.append(obj);
$(".list_name").append(p);
}
}
});

Categories