how to append multiple string to an HTML element in jquery? - javascript

Here, using ajax call I am getting the data as json object. For example, in userid, it returns some value. But in address value, it returns like addr1, addr2, addr3 (3 values). So how can I append these 3 values in html element and also it should be in String format tostring()
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "Controller?token=123",
dataType: 'json',
success: function(data){
$('#userid').html(data.userid.toString());
$('#addr').html(data.addr1.append(addr2));
},
error:function(){
alert("Sorry!");
}
});
});
</script>
Example strings:
addr1: 124, WELINGTONE STREET
addr2: NEWYORK
addr3: OH 12454-8787
These values are get from json object with the key names as addr1, addr2 and addr3
I need to append the key not values.

Something like this?
$('#addr').html([data.addr1,data.addr2,data.addr3].join("<br>"));

Related

$.each function is not iterating

I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});

How to send multiple javascript values to a C# action method?

Suppose I have some javascript like in the image. In the array
I put the (multiple) values in the variable array and send this
array to an action method in a controller. However, in the action method I will get this as an 'object'. How do I get the values out of this 'object'? I prefer to not use an ajax post. Is this possible? If yes, how do I 'catch' the values in the action method?
You should use the data property to send the array of integers
var array = [1, 2, 4];
$.ajax({
url: '/Home/Items',
type: 'POST',
data: { items: array },
success: function(data) {
console.log(data);
}
});
Assuming your have an action method like this to receive it
[HttpPost]
public ActionResult Items(int[] items)
{
// to do : do something with items
return Json(items);
}
Now i see you read the value of an input field and use that as the value of your array variable. I am not sure what format of value you have in your input field. If it is comma seperated list of int (Ex : "1,3,5"), you may use the split function to get an array from that.
var v = "2,5,78,8";
var array = v.split(',');
In Ajax call:
var items = ['USA', 'UK', 'Canada'];
$.ajax(
{
type: "POST",
url: "/Test/Details",
contentType: 'application/json',
data: JSON.stringify({ function_param: items })
});
In Controller:
public ActionResult Details(string[] function_param)
If you don't want to use Ajax call, then create an input type hidden control in html and put the javascript array to the hidden field and submit the form and get value in controller by using request.form["hiddencontrol"]
In JS:
$("#hiddenControl").val(JSON.stringify(items));

dynamically build data string for ajax call that contains html

For a long time I have been using the below code to dynamically build a string representing key value pairs to be used in an ajax call.
This has been working quite well for my originally simple needs.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// make an ajax call
$.ajax({
type: "POST",
url: "_php/feedback.php",
data: dataString, //pass in the built vars
success: function() {
// do stuff...
}
});
I now have the need to send html as values in the data string. First thing I notice is that html containing '&' is going to be an issue so I made a simple test using var2=<span> val2<span>:
// make any array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=<span> val2<span>', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// amke an ajax call
$.ajax({
type: "POST",
url: "feedback.php",
data: dataString, //pass in the built vars
success: function(info) {
$('#result').html(info);
}
});
Then in my php page:
<?php
$var1=$_POST['var1'];
$var2=$_POST['var2'];
$var3=$_POST['var3'];
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>';
?>
I want the script to return:
val1<br><span> val2<span><br>val3<br>
But, just as I suspected, the return output was:
val1<br><span><br>val3<br>
A quick look in the inspector shows:
How can I dynamically create a string to use with data: dataString, in an ajax call that may contain html?
I tried searching for this but all I can find is "how to send post data with an html form" which clearly doesnt help.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// to apply encodeURIComponent function for each cell
feedback = feedback.map(function (cell)
{
var res = cell.split('=');
return res[0] + '=' + encodeURIComponent (res[1]);
}) ;
// join each pair with "&" seperating them
var dataString = feedback.join('&');
$.ajax({
type : "POST",
url : "feedback.php",
data : dataString,
success: function(info) {
$('#result').html(info);
}
});

can somene explain me, why this code result is different?(javascript object and array)

i will ask about this:
i have an javascript object like this:
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
]
alert(stops);
in first code the alert result is
i have a data from ajax request, so i can make an object like that dynamic.. i call it from my database
var stops=new Array();
var myObject={};
$.ajax({
url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
//url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
async: false,
success: function(data, status){
i=0;
stops+="[";
$.each(data, function(i,item){
stops+="{\"Geometry\":{\"Latitude\":";
stops+=item.latitude;
stops+=",";
stops+="\"Longitude\":";
stops+=item.longitude;
stops+="}}";
stops+=",";
});
stops+=stops.substring(0,stops.length-1);
stops+="];";
alert(stops);
in second code the alert result is
i think the stops variable have same structure,but why the alert result is different?
can i convert second code to object like first code? thank you :)
any help will be appreciated
Your first object is an array the second you appear to be manually building a JSON string into an array?
As stops is an array just add objects to it:
success: function(data, status){
$.each(data, function(i,item){
var stop = {
Geometry: {
Latitude: item.latitude,
Longitude: item.longitude
}
};
stops.push(stop);
});
alert(stops);
}
The second one is a string. Yes, you can decode JSON.
To convert the first like the second use:
JSON.stringify(stops);
To convert the second like the first use:
JSON.parse(stops);
or
$.parseJSON(stops);
edit: As was recommended, since you are using jQuery you can use $.parseJSON(stops) in place of JSON.parse(). It will actually use the native parse if available. There is no equivalent (that I know of) for stringify.

assign object to array in javascript multidimensional array

Below i have given my code which is a javascript function which calls a php file and gets json data .... all things are perfect yet but i am getting problem when i want to adda data to a multidimensional array .. sorry for this noob question.. i don't know it can be done or not.
what i want to do
i want to retrieve data on ajax call and save this data to array
so i dont need to call again if i need data again
so i want to store data in multidimensional array which will have two keys
first key will be length iof array
and second will be dataType of my data which can be "name", "id", "description"
is this right way to do this
if it is not then what should i try ...? HELP ME...!!!
or can i assign full jsondata object data got from ajax call success to an array
Newly added requirements of my question
Its associative array like my php array of data is like
$data[0]["id"] = 1;
$data[0]["name"] = "spomething";
$data[0]["descriptoon"] = "spomething";
$data[0]["image"] = "spomething";
//for second item
$data[1]["id"] = 1;
$data[1]["name"] = "spomething";
$data[1]["descriptoon"] = "spomething";
$data[1]["image"] = "spomething";
so i want to create same array for javascript... for every item i fetch... from ajax../ and include into javascript array...
$('.searchButton').bind("mouseover", function() {
var data = $(this).parents('.item').attr('id');
var type = $(this).parents('.tab-pane').attr('id');
// dataArray will be global javascript variable because of its needdss... it will be outside the function
var dataArray = new Array();
$.ajax({
type: 'GET',
url: '<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success: function(data){
var dataArrayLength = dataArray.length;
dataArray.push({dataArrayLength:data});
console.log(dataArray[0]);
}
});
});
now i change my code on thebasis of your suggestion i can push data object in array via push fn ... now how do i call inside data from that object ....!
Object {dataArrayLength: Object}
dataArrayLength: Object
description: "World famous roasted Chicken, avacado, fresh mushrooms, red onions. Mozzarella cheese and our secret sauce."
id: "11"
images: "/htdocs/kiosk/images/dining/items/pizzas/11.jpg"
name: "Bella Notte Signature Pizza"
price: "4.50"
raters: "10"
ratings: "1"
__proto__: Object
__proto__: Object
this is the output of console.log(dataArray[0]) ... so now i want to get "id" , "name", "description" from it how can i do this...????/
MY SOLUTION TO PROBLEM
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push(data);
dataArray.forEach(function(object,index){
console.log(object.id);
console.log(object.name);
console.log(object.description);
console.log(object.image);
console.log(object.ratings);
});
and this is what i want to do ...
Try this:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
dataArray = []; // empty it before pushing data into it...
dataArray.push(data);
}
});
I believe you can directly push the data object into the dataArray.
and while you access this simple access it like dataArray[i].id, dataArray[i].name and so on for all the keys of data.
I'm not quite sure i understand, but cant you simply do:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push({'id':data.id,'name':data.name,'image':data.image,'description':data.description});
}
});
});
Or even:
dataArray.push(data);
I havent tested this so consider it pseudo code but i belive that the push method is what you are looking for?

Categories

Resources