All that I am trying is to iterate the data I have in the database using the Jquery each method, but couldn't figure when I am losing it all. Can someone look through this piece of code and tell me what I am doing wrong ?
$(function(){
var output = $("#folderOne");
$.ajax({
url: 'http://......',
dataType: 'json',
// data: {action: 'output'},
success: function(data, status){
console.log(data);
$.each(data, function(index, value) {
if (value.f_id == 1) {
var cards = "<div class='thumb'>" + value.f_id +
"</div><br>" + "<p>" + value.title + "</p> ";
}
output.append(cards);
});
},
Related
I have been trying all the help available on different forums but now give up and posting my question here. Trying to populate dropdown using ajax call. Getting the data in json format successfully. But don't know to fill dropdown. code below:
Controller:
function getRegion()
{
$this->load->model('Settings_model');
$title = $this->input->get('title');
$result = array("region" => $this->Settings_model->getSelectedRegion($title));
echo json_encode($result);
}
View:
$(document).on('change', '#campaignSel', function() {
changecampaign();
});
function changecampaign(){
var title= "New Normal";//$('#campaignSel option:selected').text();//$('#campaignSel').text();
$regionSel = $("#regionSel");
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":"New Normal"},
datatype: "json",
success: function(result){
var appenddata;
$.each(result, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Response: {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY
ELEC"}]}
I want to fill dropdown with Regions.
you need to loop the region like this $.each(result.region, function (key, value) { instead of result
Update1:
added if condition if ($.isArray(result.region)){ ... }
result = {"region":[{"id":"1","region":"109 FEATHERSTON ST (ELEC)\r\n"},{"id":"2","region":"ASHBURTON/MID CANTERBURY ELEC"}]}
var appenddata='';
if ($.isArray(result.region)){
$.each(result.region, function (key, value) {
appenddata += "<option value = '" + value.id + " '>" + value.region + " </option>";
console.log(appenddata);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Finally I resolved the issues in my code. I like to share the changes I made to my code below:
added:
contentType: "application/json",
and
parsedobj = JSON.parse(result)
so the final ajax code is:
$.ajax({
type:"GET",
url: "<?php echo base_url('Pricecomparison/getRegion'); ?>",
data:{ "title":title},
contentType: "application/json",
datatype: "json",
success: function(result){
parsedobj = JSON.parse(result)
var appenddata='';
$.each(parsedobj.region, function(index, value)
{
appenddata += "<option value = '" + index + "'>" + value.region + " </option>";
});
$('#regionSel').html(appenddata);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.
I have sort of hacked this together:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
dataType: 'html',
success: function(html) {
alert(html);
},
});
return false;
});
The function appears to work ok, it gives me an alert with the correct data.
{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}
I need to be able output this to the user so that it is readable. A lot of guides I find describe replacing data but as it stands there is no data until a child_id is selected.. i then want it show the above data in a readable way.
I have no idea how to start working with the data in my view file(php).
Thanks
[EDIT]updated with working code:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var response = "";
var child_id = $('#child_id').val();
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
success: function(response) {
var json_obj = $.parseJSON(response);
var output = "<ul>";
for (i=0; i < json_obj.payments.length; i++)
{
var payment = json_obj.payments[i];
var date = moment(payment.pdate).format('Do MMM YYYY');
output += "<li>£" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
}
output += "</ul>";
$('.history-section').html(output);
},
dataType: "html"
});
});
Do like this.
var data = $.parseJSON("your_json");
var output= "<ul>";
for (i=0; i < data.payments.length; i++){
output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}
output += "</ul>";
use
dataType: 'json',
instead
dataType: 'html',
and then use each to fetch the record from response in success function
Use $.parseJSON() For Convert Json Format Data To Array
Right code at sucess of ajax..
Like,
var data = $.parseJSON(html);
data in you get array format of responce
You need to use json_encode() in your php file to send the data back as an array
For example;
$myarray = array("data1"=>"value1","data2"=>"value2");
echo json_encode($myarray);
You can then access the data separately in the js file like this;
success: function(html) {
alert(html.data1);
alert(html.data2);
},
You also need to change the dataType to 'json'
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
type: 'POST',
dataType: 'json',
data: 'filter_name=' + encodeURIComponent(request.term),
success: function(data) {
response($.map(data, function(item) {
return {
category: item.attribute_group,
label: item.name,
value: item.attribute_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
return false;
}
});
You Can map your json something like this
var a = $('.level').find(":selected").attr('value');
var b = $('.category').find(":selected").attr('value');
var c = $('.topic').find(":selected").attr('value');
var d = $('.question').val();
$.ajax({
url: "http://localhost/2016/2016_02_15_Quiz/index.php/Admin/getthecompr/" + a + "/" + b + "/" + c,
type: "GET",
dataType: 'json',
data: '',
success: function(data) {
var id = data;
$.ajax({
url: "http://localhost/2016/2016_02_15_Quiz/index.php/Admin/insert4/" + id[0]['id_comprehens'] + "/" + d,
type: "GET",
dataType: 'json',
data: '',
success: function(data) {
alert("Success");
},
error: function() {
alert("Fail")
}
});
},
error: function() {
console.log('Paastoge');
}
});
});
I got trouble making this nested-JQuery-Ajax. In the first Ajax, I take the value of compre_id that I want to use in second Ajax. In the second Ajax, I will insert the id_comprhensive and question in MySQL table. The Problem is, inserting data to SQL table is success. But, instead of displaying "success", fail alert does appear. Is there something problem with this code ?
I have a json API key & I am trying to convert the json data to display in unordered list in HTML or php.
This is the API key I have : http://kippamp.uservoice.com/api/v1/forums/1/suggestions.json?client=qikbghkQYRolFTMvEXg
I am able to parse the raw json data using the below code :
<script>
$.ajax({
type: 'GET',
url: 'http://kippamp.uservoice.com/api/v1/forums/1/suggestions.json?client=qikbghkQYRolFTMvEXg',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
console.log(json);
},
error: function(e)
{
alert(e.message);
}
});
</script>
but not able to parse the data to list in a formatted way.
Can someone here help me please.
Regards.
Just render your results in the loop. For example appending them into ul container:
success: function (data) {
var $ul = $('#results');
$.each(data.suggestions, function(i, el) {
$ul.append('<li>' + el.formatted_text + '</li>');
});
},
http://jsfiddle.net/zvBE3/
You just need to decide what data you need to present and what template you should use:
var row =
'<li>' +
'<h2>' + el.title + '</h2>' +
'<div>' + el.formatted_text + '</div>'+
'</li>';
$ul.append(row);
http://jsfiddle.net/zvBE3/3/
Ajax request returns an object, you have to loop over data.suggestions to create your list.
Something like:
$.each(data.suggestions, function(id, suggestion) {
$('ul.mylist').append($('<li>'+suggestion.title+'</li>'));
});
I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});