Fiddle Example
I have a php file to return json data for main content data as well as an additional property for pagaination data. I want to know if it's possible to exclude the property for the pagination data when reiterating over the data in a foreach loop to avoid the undefined warning.
var data = [{"larger_than_1":true,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"},
{"jao":"j","kal":"k"}];
The pagination data is always the first property, I tried if(item[i]!== 0) but it doesn't work.
Ajax:
$(document).ready(function(){
$.ajax({
url: "pagination.php",
type: "POST",
dataType: "json",
success:function(data) {
var item_html = "";
console.log(data[0]);
item_html += '<h3>'+data[0].larger_than_1+'</h3>';
$.each(data,function(index,item)
{
if(item[index]!== 0)
{
item_html += '<p>'+item.kal+'</p>';
}
});
$('#area').append(item_html);
}
});
});
Change item[i] to i in your if statement.
jsFiddle
You need to determine the data which need to be exclude. but as its coming as first value you can simply use index to filter out desired data. i.e. if(i!= 0):
var data = [{"larger_than_1":null,"current_page_no":110,"otherpageno":"100,101,102,103,104,105,106,107,108,109,111,112,113,114,115,116,117,118","current_not_equal_total":"true","nextpage":111,"website":"www.google.com"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"},{"jao":"j","kal":"k"}];
var item_html ="";
jQuery.each(data, function(i, item) {
if(i!= 0)
{
item_html += '<p style="margin:5px;background:beige">'+item.kal+'</p>';
}
$('#area').append(item_html);
});
Working Demo
Related
I am trying to display the result of my php in different <div>-s. My plan is that I make a query in my php and display the result in JSON format. Due to the JSON format my result can be displaying in different <div>. How can I reach that for example the "name" can be displayed between <div> tags?
The example result of php:
[
{
"id": 0,
"name": "example1",
"title": "example2"
},
{
"id": 0,
"name": "example1",
"title": "example2"
}
]
The attempt:
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
$('.result').html(data);
}
});
</script>
Hi try parsing the returned data into a JSON object :
<div class="result"></div>
<script>
$.ajax({
type:'GET',
url:'foo.php',
data:'json',
success: function(data){
// added JSON parse
var jsonData = JSON.parse(data);
// iterate through every object
$.each(jsonData, function(index, element) {
// do what you want with each JSON object
$('.result').append('<div>' + element.name + '</div>');
});
}
});
</script>
// PS code is untested.
// Regards
Do it like below:-
success: function(data){
var newhtml = ''; //newly created string variable
$.each(data, function(i, item) {//iterate over json data
newhtml +='<div>'+ item.name +'</div>'; // get name and wrapped inside div and append it to newly created string variable
});
$('.result').html(newhtml); // put value of newly created div into result element
}
You can create it like this:
for (var i = 0; i < res.length; i++) {
var id = $("<div></div>").html(data[i].id);
var name = $("<div></div>").html(data[i].name);
var title = $("<div></div>").html(data[i].title);
$('.result').append(id).append(name).append(title);
}
This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example
Cancel all Ajax Request if search field is empty and if the search character length is < 3
$('#search-box').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind
From your code it's OK to use but what happens when second request finish after first request? for example first send "ab" and send "abc" later, the second result will be replace with the first. You can use abort() to abort the first connection before start the second one.
if(ajaxRequest){ajaxRequest.abort();}
ajaxRequest = $.ajax({
url: '...',
success: function(){
/* ... */
}
});
Use keyup event of search inputbox instead of section element.
$('#search').keyup(function() { // bind the search data
var input = $('.search-input').val();
if (input.length >= 3) {
$.getJSON({ // get JSON data
url: 'example.com?keyword=' + input,
success: function(data) {
// do processing.
var output = "<ul class='search-lists'>"; //output search data list
$.each(data, function(key, val) {
output += '<li><a>' + val.term + '</a></li>';
});
output += '</ul>';
$('.search-results').html(output);
}
}); // JSON request
}
}); // data bind
I have a little problem here. ¿How i can manipulate a dynamically generated html, in Jquery?
I have a function like:
generatesomething : function(DestinationID,data){
result = $.DoSomething(data)
$('#'+Destinationid).html(data);
}
The script, in other point, receive through ajax an array. Naturally, I will iterate the array like:
$.each(response, function(key, value){
ThisHtml = '<div id="div'+key'"></div>';
$('#MyPlaceHolderDiv').html(ThisHTML)
//In this point, i really need to call my first function
$.generatesomething('div'+key',data)
//But not works!!!!
}
How i can manipulated the generated div using my function?
Thanks in advance!
Edit: in a try to clarify my question, i will paste the exact functions.
I made this function. Please do not laugh at my code, I am newbie in jquery.
jQuery.fn.extend({
/funciones Generales/
piegraph : function(GraficoDestino,tipo,arrayDatos,dato1,dato2,tooltiptemplate,labeltemplate){
var dataPoints = [];
$.each(arrayDatos, function(key, value){
var temporal = {};
temporal.label = value[dato1];
temporal.y = parseInt(value[dato2]);
dataPoints.push(temporal);
});
var opciones = {
animationEnabled : true,
data : [{
type : tipo,
startAngle : 0,
toolTipContent : tooltiptemplate,
indexLabel : labeltemplate,
dataPoints : dataPoints,
}]
};
$('#' + GraficoDestino).CanvasJSChart(opciones);
}
This function works pretty well... if i can give it the destination div to it.
In other part of my script, i have a ajax call:
Generadisco: function(){
var datos = {
"accion":"generadisco"
};
$.ajax({
type: "POST",
url: "blahblah.php",
data: datos,
dataType: "json",
success:function(response){
$.each(response, function(key, value){
esteHTML = '<div id="divdisco'+key+'"></div>
$('#discosplace').append(estehtml);
//the div is generated... but when i do...:
$(this).piegraph('divdisco'+key,'pie', response[3],0,1, "{label} #percent%","{label} ");
//nothing happens
});
}
});
}
I found some error in your code:
$('#MyPlaceHolderDiv').html(ThisHTML)
$.generatesomething('div'+ key ,data)
must to be:
$('#MyPlaceHolderDiv').html(ThisHTML);
$.generatesomething('div'+key',data);
Also try to add console.log(DestinationID) in first line of your function to see passed argument (DestinationID)
If you are generating the dynamic elements after your ajax call, try using async:false.
$.ajax({
url: "abcd.html",
async:false
}).then(function())
I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'¶1='+ para1 +
'¶2=' + para2+
'¶3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}