I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});
Related
I am working on dynamic j query data table where i want to show data from 3 tables.
It should be expandable.I am done to achieve with 1 table. but after joins another 2 tables its not working.
I am attaching my tables format and all pictures how should be my data look.
I have total 4 tables. employee_master,uk_slip,germany_slip,poland_slip.
each user have his pay_slips for each country for each month.
For eg. XYZ is employee.
he will get his 3 salary_slips for 2018-FEBRUARY.I want to show one datatable where first user will see his name then on expand datatable he will get in below format his all slips.
My current code is is showing only data from uk_slip. after UK another tables data should be display.
My model:
public function get_all_payslips()
{
$empid = $this->session->userdata('EMPLOYEE_ID');
$orgid = $this->session->userdata('CURRENT_ORG_ID');
$where = "EMPLOYEE_ID ='".$empid."' ";
$response = array();
$queryString = "SELECT
em.EMPLOYEE_ID,
em.EMPLOYEE_NAME
FROM
uk_slip assd,
employee_master em
WHERE
em.".$where."
GROUP BY em.EMPLOYEE_ID
order by em.EMPLOYEE_NAME asc";
$query = $this->db->query($queryString);
foreach ($query->result() as $data)
{
$result = array();
$result['EMPLOYEE_NAME'] = $data-> EMPLOYEE_NAME;
$queryString = "SELECT
mo.months,
MONTH((assd.pay_period)) as monthss,
YEAR((assd.pay_period)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(assd.id)) as action,
CONCAT(assd.ORG_ID,',',germany.ORG_ID,',',poland.ORG_ID) as org
FROM
uk_new_salary_slip assd,
employee_master em,
months mo,
germany_slip germany,
poland_slip poland
WHERE
assd.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((assd.pay_period))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$query1 = $this->db->query($queryString);
$children = array();
foreach ($query1->result() as $data1)
{
$yearArray = array();
$yearArray['month'] = $data1->months;
$yearArray['year'] = $data1->PAY_YEAR;
$yearArray['org'] = $data1->org;
$yearArray['action'] = $data1->action;
array_push($children, $yearArray);
}
$result['children'] = $children;
array_push($response, $result);
}
return $response;
}
My View with jquery datatable:
$(document).ready(function()
{
var table = null;
$.ajax({
url:"<?php echo base_url('responsible/get_all_payslips'); ?>",
datatype:'json',
success: function(response)
{
var response1 = $.parseJSON(response);
console.log(JSON.stringify(response1['pay_slips']));
var data = response1['pay_slips'];
table = $('.datatables').DataTable({
columns : [
{
className : 'details-control',
defaultContent : '',
data : null,
orderable : false
},
{data : 'EMPLOYEE_NAME'},
],
data : data,
pagingType : 'full_numbers',
});
}
});
function format(data)
{
return '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
+'</tbody>'+
'</table>'+
'</div>';
};
$('.datatables tbody').on('click', 'td.details-control', function ()
{
var tr = $(this).closest('tr');
var row = table.row( tr );
console.log(row.data()['children']);
var childrenArray = row.data()['children'];
var check = '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>';
for(var i=0;i<childrenArray.length;i++)
{
check +='<tr>'+
'<td>'+childrenArray[i].year+'</td>'+
'<td>'+childrenArray[i].month+'</td>';
var orgid = childrenArray[i].org.split(",");
var action = childrenArray[i].action.split(",");
var obj = {};
for (var k = 0; k < orgid.length; k++)
{
obj[orgid[k]] = action[k];
}
var arrayData = sortObject(action);
check +='<td>';
for(var j=0;j<arrayData.length;j++)
{
var country = "";
var color = "";
if(arrayData[j].key=="40")
{
country = "1";
color = "INDIANRED";
}
else if(arrayData[j].key=="41")
{
country = "2";
color = "LIGHTPINK";
}
else if(arrayData[j].key=="47")
{
country = "3";
color = "LIGHTSALMON";
}
else
{
country = "UK";
color = "DARKKHAKI";
}
check+='<a class="btn btn-success" style="background-color : ' + color + ';" href="<?php echo base_url()?>responsible/uk_pdf/'+arrayData[j].value+'">'+country+
'</a>|';
}
check +='</td></tr>';
}
check += '</tbody>'+
'</table>'+
'</div>';
if (row.child.isShown())
{
tr.next('tr').removeClass('details-row');
row.child.hide();
tr.removeClass('shown');
}
else
{
row.child(check).show();
tr.next('tr').addClass('details-row');
tr.addClass('shown');
}
});
});
function sortObject(obj)
{
var arr = [];
console.log(arr);
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
{
arr.push({
'key': prop,
'value': obj[prop]
});
}
}
arr.sort(function(a, b) { return a.value - b.value; });
return arr;
}
In all 3 slip_tables emp_id is common. then in each table having ORG_ID column. for UK having ORG_ID = 40, for GERMANY = 57, for POLAND = 47. In uk_slip having column pay_period for getting MONTH and YEAR with mysql functions MONTH and YEAR. and in germany and poland having pay_from to get the same.
i have a live searcher thats when its data its shows
i need to alert if the data is empty
this is the jquery:
$(document).ready(function() {
$('#q').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function(data) {
$('ul#content').show();
$('ul#content').empty()
$.each(data, function() {
if ( data.length == 0 ) {
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
}else{
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">' + this.title + '</font></li>');
}
});
}, "json");
}
});
});
and the php:
$conexion = mysqli_connect($serv,$user,$pass,$base);
$arr = array();
if (!empty($_POST['q'])) {
$keywords = $Main->limpiar($_POST['q']);
$mysqli = $conexion;
$result = $mysqli->query("SELECT cat, titulo FROM pinturas WHERE titulo LIKE '%".$keywords."%' OR cat LIKE '%".$keywords."%'");
if ($result->num_rows > 0) {
while ($obj = $result->fetch_array()) {
$seo = str_replace(" ","_",$obj['titulo']);
$arr[] = array('id' => $obj['cat'], 'title' => $obj['titulo'], 'seo' => $seo);
}
}else{
$arr[] = array('id' => '', 'title' => '', 'seo' => '');
}
}
echo json_encode($arr);
i want to if the data is empty shows the append empty
but it dont work
Assuming the data is a JSON parsed object you can:
Object.keys(data).length === 0
Or
JSON.stingify(data) === '{}'
Check length of the records before iteration (using $.each in jquery API)
<script>
$(document).ready(function () {
$('#q').on('input', function () {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function (data) {
console.log(data);
$('ul#content').show();
$('ul#content').empty()
if (data.length == 0) {
$('ul#content').empty().append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
}
else {
$.each(data, function () {
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">' + this.title + '</font></li>');
});
}
});
}
});
});
</script>
Worked for me.
Hope this helps.
I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);
I am using a jQuery plugin called Stepy, which is based of the FormToWizard plugin, to allow users to complete a 10-step form.
Using the next/back attributes, I've added a function to post data between steps so the user can save their work and come back at a later day if they'd like.
One of my steps allows the user to add items to a form within an iframe (to post data to a separate table). I'd like it to function so that when the user moves between steps, the items in the iframe post to their separate table as well. Is there a way to submit the form within the iframe between steps (i.e. submit iframe sub-form when main form submits)?
I am using PHP and MySQL.
Any help you could provide would be amazing!
Javascript:
$(function() {
$('#custom').stepy({
backLabel: 'Back',
block: true,
errorImage: true,
nextLabel: 'Next',
titleClick: true,
validate: false,
legend: false,
back: function(index) {
$.post('../../process.php')
}
next: function(index) {
$.post('../../process.php')
}
});
});
HTML:
<html>
<body>
<form id="custom" name="custom">
<fieldset title="Thread 1">
<legend>description one</legend>
<label>Question A:</label>
<input type="text" id="question_a" name="question_a" class="required">
<label>Question B:</label>
<input type="text" id="question_b" name="question_b">
</fieldset>
<fieldset title="Thread 2">
<legend>description two</legend>
<iframe src="../../list_form.php" width="100%" height="300"></iframe>
</fieldset>
<fieldset title="Thread 3">
<legend>description three</legend>
<label>Question C:</label>
<input type="text" id="question_c" name="question_c" class="required">
</fieldset>
<input type="submit" class="finish" value="Finish!">
</form>
</body>
</html>
iframe
<html>
<body>
<form id="sub_form" name="sub_form">
<label>Question 1:</label>
<input type="text" id="question_1" name="question_1">
<label>Question 2:</label>
<input type="text" id="question_2" name="question_2">
</form>
</body>
</html>
stepy.js
;(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var opt = $.extend({}, $.fn.stepy.defaults, options),
$this = $(this).data('options', opt),
id = $this.attr('id');
if (id === undefined) {
id = 'stepy-' + $this.index();
$this.attr('id', id);
}
var $titlesWrapper = $('<ul/>', { id: id + '-titles', 'class': 'stepy-titles' });
if (opt.titleTarget) {
$(opt.titleTarget).html($titlesWrapper);
} else {
$titlesWrapper.insertBefore($this);
}
if (opt.validate) {
$this.append('<div class="stepy-error"/>');
}
var $steps = $this.children('fieldset'),
$step = undefined,
$legend = undefined,
description = '',
title = '';
$steps.each(function(index) {
$step = $(this);
$step
.addClass('step')
.attr('id', id + '-step-' + index)
.append('<p id="' + id + '-buttons-' + index + '" class="' + id + '-buttons"/>');
$legend = $step.children('legend');
if (!opt.legend) {
$legend.hide();
}
description = '';
if (opt.description) {
if ($legend.length) {
description = '<span>' + $legend.html() + '</span>';
} else {
$.error(id + ': the legend element of the step ' + (index + 1) + ' is required to set the description!');
}
}
title = $step.attr('title');
title = (title != '') ? '<div>' + title + '</div>': '--';
$titlesWrapper.append('<li id="' + id + '-title-' + index + '">' + title + description + '</li>');
if (index == 0) {
if ($steps.length > 1) {
methods.createNextButton.call($this, index);
}
} else {
methods.createBackButton.call($this, index);
$step.hide();
if (index < $steps.length - 1) {
methods.createNextButton.call($this, index);
}
}
});
var $titles = $titlesWrapper.children();
$titles.first().addClass('current-step');
var $finish = $this.children('.finish');
if (opt.finishButton) {
if ($finish.length) {
var isForm = $this.is('form'),
onSubmit = undefined;
if (opt.finish && isForm) {
onSubmit = $this.attr('onsubmit');
$this.attr('onsubmit', 'return false;');
}
$finish.click(function(evt) {
if (opt.finish && !methods.execute.call($this, opt.finish, $steps.length - 1)) {
evt.preventDefault();
} else {
if (isForm) {
if (onSubmit) {
$this.attr('onsubmit', onSubmit);
} else {
$this.removeAttr('onsubmit');
}
var isSubmit = $finish.attr('type') == 'submit';
if (!isSubmit && (!opt.validate || methods.validate.call($this, $steps.length - 1))) {
$this.submit();
}
}
}
});
$finish.appendTo($this.find('p:last'));
} else {
$.error(id + ': element with class name "finish" missing!');
}
}
if (opt.titleClick) {
$titles.click(function() {
var array = $titles.filter('.current-step').attr('id').split('-'), // TODO: try keep the number in an attribute.
current = parseInt(array[array.length - 1], 10),
clicked = $(this).index();
if (clicked > current) {
if (opt.next && !methods.execute.call($this, opt.next, clicked)) {
return false;
}
} else if (clicked < current) {
if (opt.back && !methods.execute.call($this, opt.back, clicked)) {
return false;
}
}
if (clicked != current) {
methods.step.call($this, (clicked) + 1);
}
});
} else {
$titles.css('cursor', 'default');
}
$steps.delegate('input[type="text"], input[type="password"]', 'keypress', function(evt) {
var key = (evt.keyCode ? evt.keyCode : evt.which);
if (key == 13) {
evt.preventDefault();
var $buttons = $(this).parent().children('.' + id + '-buttons');
if ($buttons.length) {
var $next = $buttons.children('.button right-aligned');
if ($next.length) {
$next.click();
} else {
var $finish = $buttons.children('.finish');
if ($finish.length) {
$finish.click();
}
}
}
}
});
$steps.first().find(':input:visible:enabled').first().select().focus();
});
}, createBackButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-back-' + index, href: 'javascript:void(0);', 'class': 'button left-aligned', html: opt.backLabel }).click(function() {
if (!opt.back || methods.execute.call($this, opt.back, index - 1)) {
methods.step.call($this, (index - 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, createNextButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-next-' + index, href: 'javascript:void(0);', 'class': 'button right-aligned', html: opt.nextLabel }).click(function() {
if (!opt.next || methods.execute.call($this, opt.next, index + 1)) {
methods.step.call($this, (index + 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, execute: function(callback, index) {
var isValid = callback.call(this, index + 1);
return isValid || isValid === undefined;
}, step: function(index) {
index--;
var $steps = this.children('fieldset');
if (index > $steps.length - 1) {
index = $steps.length - 1;
}
var opt = this.data('options');
max = index;
if (opt.validate) {
var isValid = true;
for (var i = 0; i < index; i++) {
isValid &= methods.validate.call(this, i);
if (opt.block && !isValid) {
max = i;
break;
}
}
}
$steps.hide().eq(max).show();
var $titles = $('#' + this.attr('id') + '-titles').children();
$titles.removeClass('current-step').eq(max).addClass('current-step');
if (this.is('form')) {
var $fields = undefined;
if (max == index) {
$fields = $steps.eq(max).find(':input:enabled:visible');
} else {
$fields = $steps.eq(max).find('.error').select().focus();
}
$fields.first().select().focus();
}
if (opt.select) {
opt.select.call(this, max + 1);
}
return this;
}, validate: function(index) {
if (!this.is('form')) {
return true;
}
var $step = this.children('fieldset').eq(index),
isValid = true,
$title = $('#' + this.attr('id') + '-titles').children().eq(index),
opt = this.data('options'),
$this = this;
$($step.find(':input:enabled').get().reverse()).each(function() {
var fieldIsValid = $this.validate().element($(this));
if (fieldIsValid === undefined) {
fieldIsValid = true;
}
isValid &= fieldIsValid;
if (isValid) {
if (opt.errorImage) {
$title.removeClass('error-image');
}
} else {
if (opt.errorImage) {
$title.addClass('error-image');
}
$this.validate().focusInvalid();
}
});
return isValid;
}
};
$.fn.stepy = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist!');
}
};
$.fn.stepy.defaults = {
back: undefined,
backLabel: '< Back',
block: false,
description: true,
errorImage: false,
finish: undefined,
finishButton: true,
legend: true,
next: undefined,
nextLabel: 'Next >',
titleClick: false,
titleTarget: undefined,
validate: false,
select: undefined
};
})(jQuery);
If you want to append Text\HTML or any other data to your iframe (which calling to a page on the same domain!) you may use:
jQuery("#iframe_id").contents().find('body').append('<div>Hello World</div>');
Full Example:
Full Example
If your iframe is on another domain you will have to use window.postMessage, which you may read about on Mozilla's docs:
Mozilla's docs
OR to take a look about my blog post about this subject.
Hope I helped,
i have this code on the server side:
<?php
header('Content-Type: text/html; charset=utf-8');
require "../general.variables.php";
require "../functions_validation.php";
require "../functions_general.php";
require "../../db_con.php";
$keyword = mysql_real_escape_string($_POST["keyword"]);
$query = mysql_query("
SELECT user_id, user_fullname, user_area, user_city, user_quarter, user_tmb
FROM `migo_users`
WHERE (
user_fullname LIKE '%".$keyword."%' AND user_id NOT IN (".$superAdmins2string.")
)
ORDER BY tmb_set DESC, user_fname ASC
LIMIT 7;
");
$i = 0;
while ($userInfo = mysql_fetch_array($query)) {
$area_name = mysql_fetch_array(mysql_query("
SELECT area_name
FROM `migo_areas`
WHERE
area_id='".$userInfo['user_area']."';
"));
$city_name = mysql_fetch_array(mysql_query("
SELECT city_name
FROM `migo_cities`
WHERE
city_id='".$userInfo['user_city']."';
"));
if ($userInfo['user_quarter'] != 0) {
$quarter_name = mysql_fetch_array(mysql_query("
SELECT quarter_name
FROM `migo_quarters`
WHERE
quarter_id='".$userInfo['user_quarter']."';
"));
}
else {
$quarter_name['quarter_name'] = "";
}
$rsl[$i]['user_id'] = $userInfo['user_id'];
$rsl[$i]['user_fullname'] = $userInfo['user_fullname'];
$rsl[$i]['user_area_name'] = $area_name['area_name'];
$rsl[$i]['user_city_name'] = $city_name['city_name'];
$rsl[$i]['user_quarter_name'] = $quarter_name['quarter_name'];
$rsl[$i]['user_tmb'] = $userInfo['user_tmb'];
$i++;
}
echo json_encode($rsl);
mysql_close();
?>
and this code on the client side:
$.ajax({
type : 'POST',
url : 'php/general.ajax/header_search.php',
//async : false,
//cache : false,
dataType : 'json',
data: {
keyword : sb_keyword
},
success : function(data) {
var hs_hits = 0;
var hs_row_nr = 1;
var hs_results = "<div class='sb_spacing'></div><div id='sb_rows_cont'>";
if (data != null) {
$.each(data, function(index, arr) {
hs_hits++;
if (arr['user_quarter_name'] != "") {
var quarter_text = " - " + arr['user_quarter_name'];
}
else {
var quarter_text = "";
}
hs_results = hs_results + "<a class='search_links' href=profile.php?id=" + arr['user_id'] + "><div class='sbr_row' row_nr='" + hs_row_nr + "'><div class='sbr_imgFrame'><img src='images/user_48x48/" + arr['user_tmb'] + "' alt=''></div><div class='sbr_name'>" + arr['user_fullname'].replace(regexp_hs_user_fullname, '<span>$&</span>') + "</div><div class='sbr_area'>" + arr['user_area_name'] + "</div><div class='sbr_area'>" + arr['user_city_name'] + quarter_text + "</div></div></a>";
hs_row_nr++;
});
}
if (hs_hits > 0) {
hs_results = hs_results + "</div><div class='sb_spacing'></div><a class='search_links' href='search.php?name=" + sb_keyword + "'><div id='sbr_botttom'>Se flere resultater for <span class='gay'>" + sb_keyword + "</span></div></a>";
$("#sb_results").html(hs_results).show();
searchSet = 1;
total_rows = hs_hits;
$("#sb_rows_cont > a:first .sbr_row").addClass('sbr_row_act');
on_a = $("#sb_rows_cont > a:first");
first_a = on_a;
last_a = $("#sb_rows_cont > a:last");
sb_url = $(on_a).attr('href');
search_navigator_init();
}
else {
$("#sb_results").hide();
searchSet = 0;
}
},
error : function() {
alert("ajax error");
}
});
one problem tho, if the query gives 0 results, and the each function tries to run on the client side my js code stops working..
so i was wondering what i could do here.
how can i retrieve the amount of hits from the server side, before i run the each loop?
You're instantiating $rsl in the middle of a loop (implicitly), but you aren't entering the loop unless you have at least one entry.
Instantiate $rsl up above your while loop:
...
$i = 0;
$rsl = array();
while ($userInfo = mysql_fetch_array($query)) {
...
And now when you encode it, it is an empty array instead of null. This will also save your HTTP error_log, and generally be happier. : )
I would try json_encode() your PHP array to allow JavaScript to eval it as a native JS object.
echo json_encode($some_array);
Just a note, json_encode() is only available for PHP versions 5.2 and higher.
$.getJSON('ajax.php',{form data}, functon(data){
if(data == '') return;
});