Select2 in a complex form as abstract class - php

I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys

function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));

I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};

Related

loop Ajax Response in select Option tag

i have to select multiple tests and date and when clicked on submit based on the test,laboratory names are loaded in select option
Ajax script
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
Ajax success response is:
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
html
<select class="form-control" id="yourSelect">
</select>
but i am not able to display in select tag
$.ajax({
url: config.routes.profitsReport,
type: "POST",
dataType: 'json',
success: function (result) {
$.each(result, function (i, value) {
$('#category_profit').append('<option id=' + JSON.stringify(value.id) + '>' + JSON.stringify(value.name) + '</option>');
});
},
error: function (request, status, error) {
alert(request.statusText + "[" + request.status + "]");
alert(request.responseText);
$('button#form_salesReport_button').html(config.messages.searchReport);
}
});
Try to loop through the result like this:
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
$.each(data, function(k, v)
{
var id = data[k].laboratory_id;
var val = data[k].laboratory_name;
selOpts += "<option value='"+id+"'>"+val+"</option>";
});
$('#yourSelect').append(selOpts);
}
You can loop
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
via
var options = "";
for (let item in array) {
options += `<option value=${item.id}>${item.laboratory_name}</option>`;
}
document.getElementById("yourSelect").innerHTML = options;
If it's a String, you can convert it to an array via JSON.parse.
If you are expecting json data from ajax request then you need to require to add dataType as json.
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});

Run two ajax calls at the same time?

If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});

Two ajax post simultaneously on one link click jquery

I am using one link which has class name next and id end.
On clcik on it both class name and id i am using jquery post.
The issue i am getting is sometimes the ajax request fires multiple times on one click.on one click i am getting data from one url and simultaneously saving these data into db by another url.So sometimes there are some issues coming while inserting into db.sometimes null values enters and sometimes multiple rows entering into db.So how can i write these two functions so that both will work perfectly?
$('.next').live('click', function (e) {
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
});
$('#end').live('click', function (e) {
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
});
You are firing click on same click even if id and class are different the link is same.
$('.next').live('click', function(e)
fires one ajax call and
$('#end').live('click', function(e)
fires another, what you can do is fire one ajax on success of other
$('.next').live('click', function(e) { ...
success: function(data) { $.ajax({
url: 'submitanswers.php', }
but this is not good practice
Simply check for the event trigger like :
$('.next').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
$('#end').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
By doing so, you will stop multiple event trigger which is quite a common problem and should solve your problem.
Edit :
Your full code will be :
$('.next').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
}
});
$('#end').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
}
});

JSON decode php problems

I have index.php and getting problem with to decode the json array.. please help i am new to this..
<script>
$(document).ready(function () {
$("#slider_price").slider({
range: true,
min: 0,
max: 100,
step: 1,
values: [0, 100],
slide: function (event, ui) {
$("#app_min_price").text(ui.values[0] + "$");
$("#app_max_price").text(ui.values[1] + "$");
},
stop: function (event, ui) {
var nr_total = getresults(ui.values[0], ui.values[1]);
$("#results").text(nr_total);
},
});
$("#app_min_price").text($("#slider_price").slider("values", 0) + "$");
$("#app_max_price").text($("#slider_price").slider("values", 1) + "$");
});
function getresults(min_price, max_price) {
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {
'minprice': min_price,
'maxprice': max_price
},
async: false,
success: function (data) {
number_of_estates = data;
}
});
return number_of_estates;
}
And search_ajax.php
<?php
require_once('includes/commonFunctions.php');
// take the estates from the table named "Estates"
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
$minprice = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);
$maxprice = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT);
$query = mysql_query("SELECT * FROM cars WHERE min_range >= $minprice AND max_range <= $maxprice");
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows);
}
?>
and the problem is i just want to print $rows in specific div "number_results".. how to decode that json array?
are you sure about the data you are passing is in json format
i think it should be
'{"minprice": "min_price", "maxprice":"max_price"}'
you cannot just return ajax returned value from a function since ajax is async...the function will already return number_of_estates , by the time ajax call completes.
use callback or just call a function and append your returned text there
..
stop: function( event, ui ) {
getresults(ui.values[0], ui.values[1]);
},
...
function getresults(min_price, max_price)
{
var number_of_estates = 0;
$.ajax({
type: "POST",
url: 'search_ajax.php',
dataType: 'json',
data: {'minprice': min_price, 'maxprice':max_price},
async: false,
success: function(data)
{
number_of_estates = data;
$("#results").text(number_of_estates);
}
});
}
however ajax is called each time the stop funnction occurs so be careful.

for looping in jquery

in my php I have such code in a while loop...
$result = mysql_query("SELECT * FROM wallpost ORDER BY wallpostid DESC");
while($row = mysql_fetch_assoc($result)){
$rate = "<div class=\"example-".$id." \" data-postid=\"".$id."\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
}
jquery is...
$(document).ready(function() {
$('[class^="example-"]').not('[class^="example-rating-"]').ratings(3).bind('ratingchanged', function (event, data) {
var child = $(this).find('[class^="example-rating-"]');
child.text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: jQuery(this).data("postid")
}, function (data) {
alert(data);
});
});
for the value A I get the null value, but if i replace
var a = $('.example-rating-50').html(); //let say the wallpostid is 50
it only can pass the value 50 to count.php
If now let say I have 2 wallpostid which is 22 and 50 (loop it with while loop )
if I rate wallpostid is 22 then I want pass the value of $id=22 from php to jquery and $.post to count.php. Do the same this if I rate wallpostid=50.
it is a problem with the closure variable i
Since you are using i inside the callback, it will have the last value from the loop which is 102 that is why it is failing
$(document).ready(function () {
for (var i = 1; i < 101; i++) {
(function(idx){
$('.example-' + idx + '').ratings(3).bind('ratingchanged', function (event, data) {
$('.example-rating-' + idx + '').text(data.rating);
var a = $('.example-rating-' + idx + '').html();
$.post('count.php', {
rate: data.rating,
wallpostid: a
}, function (data) {
alert(data);
});
});
})(i)
}
});
a better solution could be
$rate = "<div class=\"examples example-".$id." \" data-idx=\"".$id"\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
then
$(document).ready(function () {
$('.examples').ratings(3).bind('ratingchanged', function (event, data) {
var i = $(this).data('idx')
var a = $('.example-rating-' + i + '').text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: data.rating
}, function (data) {
alert(data);
});
});
});
You dont need a for loop in the javascript, there are selectors that can handle this, for instance class^=
PHP
$rate = "<div class=\"example-".$id." \" data-postid=\"".$id."\"></div></br>Post id: <span class=\"example-rating-".$id."\">".$id."</span>";
JS
//Find elements that have class starting with 'example-' but Not example-rating-
$('[class^="example-"]').not('[class^="example-rating-"]').ratings(3).bind('ratingchanged', function (event, data) {
//Find Child element that has class starting with 'example-rating-'
var child = $(this).find('[class^="example-rating-"]');
child.text(data.rating);
$.post('count.php', {
rate: data.rating,
wallpostid: jQuery(this).data("postid")
}, function (data) {
alert(data);
});
});
I like to not build element selectors dynamically.
var $examples = $('[class^=example-]:not([class^=example-rating])');
var $ratings = $('[class^=example-rating]');
$examples.ratings(3).bind('ratingchanged', function (event, data) {
var index = $examples.index(this);
var $rating = $ratings.eq(index);
$rating.text(data.rating);
var a = $rating.attr('class').split('-')[2];
$.post('count.php', {
rate: data.rating,
wallpostid: a
}, function (data) {
alert(data);
});
});

Categories