Put AJAX Response in HTML format - javascript

I've AJAX response which needs to be rendered in HTML setup in PHP file. I'm confused regarding how to render it as there are multiple data in AJAX response and each of them must be put in specific places in html
for example AJAX response has two(or n) objects like this:
0:Object
id: "111"
Name: "abc"
1:Object
id: "112"
Name: "xyz"
Then, There already would be two(or n) divs with user class in HTML
<div class='user'>
<div class='userId'>
<div class='usernm'> </div>
</div>
</div>
<div class='user'>
<div class='userId'>
<div class='usernm'> </div>
</div>
</div>
What I need is put those response values in this divs like this:
<div class='user'>
<div class='userId'> 111
<div class='usernm'> abc </div>
</div>
</div>
<div class='user'>
<div class='userId'> 112
<div class='usernm'> xyz</div>
</div>
</div>
I'm lost as to how can I achieve that on AJAX Success here using jQuery:
$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$.each(data, function(key, value){
console.log(value); //this outputs response as Objects shown above
});
}
});

Use the append function in your loop to add the elements to the page
$('body').append('<div class="user">
<div class="userId"> '+value.id+'
<div class="usernm">'+value.name+'</div>
</div>
</div>');//note change the body element to your desired parent element
if you only need to put the data do the following:
success: function(data) {
$('.userId').each(function(key, value){
$(value).prepend(data[key].id);
$(value).find('.usernm').text(data[key].name);
});
}
demo:https://jsfiddle.net/gf32wd7L/1/

Can you please try
$.ajax({
type: 'GET',
url: '/url/goes/here',
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
$('<div/>', {
'class': 'user'
}).append(
$('<div/>', {
'class': 'userId'
}).text(this.id).append(
$('<div/>', {
text: 'usernme'
}).text(this.Name)
});
});
}
});

This is another way, Use if it is convenient,
Let us say ur HTML,
<div class="append-div"></div>
Your JSON,
{
"Objects":[
{
"id": "111",
"name": "abc"
},
{
"id": "112",
"name": "xyz"
}
]
}
The JS,
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'json.js',
dataType: "json",
success: function(data) {
var userDiv = "";
$.each(data.Objects, function(key, value){
console.log(value); //this outputs response as Objects shown above
userDiv += '<div class="user"><div class="userId">' + value.id + '</div>' + value.name + '</div>';
});
$(".append-div").append(userDiv); // Append the results
}
});
});

Related

How to print json console.log data in browser?

I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.
script.js
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
index.php
<input id="movie" type="text" /><button>Search</button>
This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.
Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value
$(document).ready(function() {
var url = 'https://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
$("#title").text(json.title);
//$("#movTitle").prop('src'); // add image path here
$("#overview").text(json.overview) //overview is a key
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
<img id="movTitle" src="" alt="">
</div>
<div id="overview">
</div>
To output your JSON data to the browser, you need to modify the HTML of the page.
First, add a few elements to your index.php like so:
index.php
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>
Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
$("#movie-title").text(json.title);
$("#movie-budget").text(json.budget);
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});

Displaying all data from loop

I am able to fetch all my data from database successfully but only the last item in the array displays. What am I doing wrong?
HTML
#foreach($groups as $group)
<button type ="button" value="{!! $group->id !!}" id="btn" name="btn">{!!$group->name!!}</button>
<div class="panel">
<label for="myvalue"><input type="checkbox" id="myvalue" /> <span>Label text x</span></label>
</div>
#endforeach
JavaScript
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data: {
id: $(this).val(),
access_token: $("#access_token").val()
},
success: function (result) {
$.each(result, function (i, fb) {
$("label[for='myvalue']").text(fb.name);
});
}
);
This way you are replacing the label text, not creating labels. What you are looking for would be something like:
<div class="panel" id="labels_cotainer">
<label for="myvalue">
<input type="checkbox" id="myvalue" />
<span>Label text x</span></label>
</div>
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data:{
id: $(this).val(),
access_token: $("#access_token").val()
},
success:function(result) {
$.each(result, function (i, fb) {
$("#labels_cotainer").append('<label>'+fb.name+'</label>');
}
}
});
This code will append every label to your panel
You have to dynamically create new labels and add fb.name to it otherwise you will replace all values until the last value
success:function(result) {
$.each(result, function (i, fb) {
$("#outerDiv").append('<label>'+fb.name+'</label>');
});
}

I'm trying to load the ajax into two different divs

I'm trying to load the ajax into two different divs, however I inspect the console and the web page is still putting the data into one div, even though it is called within the ajax code to two different divs.
<script>$(document).ready(function(){
$.ajax({
url: "http://developer.api.cnet.com/rest/v1.0/techProductSearch",
type: "get",
data: { viewType:"json", iod: "none", callback: "phone", partKey:"2nnae6wsj2w72yqhcwu4v7sg", partTag:"2nnae6wsj2w72yqhcwu4v7sg", query: "iphone 5", productId:"31303113" },
dataType: "jsonp",
success: ipod
});
});
function ipod(data) {
var count = 0;
console.log(data);
$.each(data.CNETResponse.TechProducts.TechProduct, function(index,value) {
console.log("Name: "+data.CNETResponse.TechProducts.TechProduct[count].Name.$);
var datastring = '<tr>'+'<td class="searchItem">'+data.CNETResponse.TechProducts.TechProduct[count].Name.$+'</td> </tr>';
$('#tabs-1').append(datastring);
console.log("$('#tabs-1').append(datastring)");
count ++;
});
}</script>
<script>$(document).ready(function(){
$.ajax({
url: "http://developer.api.cnet.com/rest/v1.0/techProductSearch",
type: "get",
data: { viewType:"json", iod: "none", callback: "phone", partKey:"2nnae6wsj2w72yqhcwu4v7sg", partTag:"2nnae6wsj2w72yqhcwu4v7sg", query: "Samsung Note 3", productId:"31303113" },
dataType: "jsonp",
success: ipod
});
});
function ipod(data) {
var count = 0;
console.log(data);
$.each(data.CNETResponse.TechProducts.TechProduct, function(index,value) {
console.log("Name: "+data.CNETResponse.TechProducts.TechProduct[count].Name.$);
var datastring = '<tr>'+'<td class="searchItem">'+data.CNETResponse.TechProducts.TechProduct[count].Name.$+'</td> </tr>';
$('#tabs-2').append(datastring);
console.log("$('#tabs-2').append(datastring)");
count ++;
});
}</script>
HTML
<div id="tabs-1">
<p></p>
</div>
<div id="tabs-2">
<p></p>
</div>
You have two functions both called ipod. You need to give them a unique name, otherwise one will override the other. Call the second one 'ipod2', then set you second ajax call to use ipod2 as the success callback.
<script>
$(document).ready(function(){
$.ajax({
url: "http://developer.api.cnet.com/rest/v1.0/techProductSearch",
type: "get",
data: { viewType:"json", iod: "none", callback: "phone", partKey:"2nnae6wsj2w72yqhcwu4v7sg", partTag:"2nnae6wsj2w72yqhcwu4v7sg", query: "iphone 5", productId:"31303113" },
dataType: "jsonp",
success: ipod
});
});
function ipod(data) {
$.each(data.CNETResponse.TechProducts.TechProduct, function(i,v) {
var datastring = '<div class="searchItem">'+v[i].Name + '</div>';
$('#tabs-'+ i).append(datastring);
});
};
</script>

Not able to submit field value with Ajax

I know that there was a similar questions to this, but I tried everything and nothing seems to work. I'm not that good with ajax thats why i posted this question.
$("#buttons_holder").find("#add_users").click(function() {
var ob = document.getElementById('all_users[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].selected) {
selected.push(ob.options[i].value);
}// if
}// for
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data: {
s : selected_users
},
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});
And I always get fail alerted. I try to alert all parametes(selected_users, link) before function and everything seems ok. Can anyone tell me what could be a problem? Thanks you all very much for your answers.
EDIT: Here's my HTML Code:
<div class="main_content">
<div id="users_holder">
<div class="div_grids">
<div class="inline_wrapper">
<h4>Users that belong to selected company:</h4>
<label for="company_users">
<select multiple="" name="company_users[]" id="company_users[]">
<option value="1">admin#sms.com</option>
<option value="3">b#bba.com</option>
<option value="5">dfsdf#dmfkdmf.com</option>
</select>
</label>
</div>
<div style="margin-top:2%; margin-left:5%; margin-right:5%" id="buttons_holder" class="inline_wrapper">
<div class="common_add_button">
<a id="remove_users" name="remove_users" href="http://localhost/cake/crawler/companies/1/manage-agents/remove"> >> </a>
</div>
<div class="common_add_button">
<a id="add_users" name="add_users" href="http://localhost/cake/crawler/companies/1/manage-agents/add"> << </a>
</div>
</div>
<div class="inline_wrapper">
<h4>All users:</h4>
<label for="all_users">
<select multiple="" name="all_users[]" id="all_users[]">
<option value="4">11111#qweqwe.com</option>
</select>
</label>
</div>
</div>
SOLUTION:
$("#buttons_holder").find("#add_users").click(function() {
var selected_users = $('#all_users option:selected').map(function() {
return this.value
}).get();
var link = '{$add_users_link}';
$.ajax({
url: link,
type: 'POST',
data: {
'new_users' : selected_users
},
'success': function(data) {
App.Messages.showOkFlashMessage(data);
},
'error': function(data) {
App.Messages.showErrorFlashMessage(data.responseText);
}
});
return false;
});
When I use Ajax and arrays, I always pass the data as string and deserialize on the server.
Since the parameters seem to be ok to you, maybe you can try this:
$.ajax({
url: link,
type: 'POST',
data: { s : JSON.stringify(selected_users) },
'success': function(data) { alert ('success'); },
'error': function(data) { alert ('fail'); }
});
#Marko Vasic Ajax require Json format data so you have to send data in json format like
JSON.stringify({ s: selected_users })
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data:
JSON.stringify({ s: selected_users }),
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});

Using Query string in MVC 3.0

I am having some anchor tags in the page and I have to set them all a value in query string and then
trying to send it in controller can this be possible.Actually I have a hidden field on the page and that hidden field is set to a value
when somebody selects a user from auto complete of jquery. Now my Question is that I am able to set hidden field a value but how can I assign value of hidden
field to query string in an anchor tag. Please help me. I am trying in this way.
<div id="page">
<div class="note-row2">
<div class="form-left">
<input type="text" id="txt_Autocomplete" />
<input type="hidden" id="hdnPkClientId" />
</div>
<div class="form-right">
</div>
<div class="right-row">
<h3><a href="/GoToPage/Index?Client_ID="+"'$('#hdnPkClientId').val()'" >My Page</a></h3>
</div>
</div>
</div>
Here I am setting the value in hidden field
<script>
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/ClientHome/SearchClientDetail",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id,
data: item
};
}));
},
error: function (xhr)
{ }
});
},
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
</script>
I
in your html:
<a id="YOUR_A" href="/GoToPage/Index?Client_ID=" >My Page</a>
in your js:
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
$("#YOUR_A").attr("href", "/GoToPage/Index?Client_ID="+ui.item.data.Id);
}

Categories