for looping in jquery - php

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);
});
});

Related

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) {
}
})
});
}
});

How to set selected value of jQuery chosen?

<script>
$(document).ready(function () {
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data).trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>
Above is my code to generate district based on state, and it works fine. I just want set the value what is selected by user. At present the selected value is cleared after selecting a state and submit.
You can use a global to hold selected value
var selectedDistrict = 0;
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
then do:
$("#district")
.html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
in your ajax success.
Means your code will become:
<script>
var selectedDistrict = 0;
$(document).ready(function () {
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>

Ajax image using jquery form.js

I am working with this piece of code. Here I am using jQuery, Jquery form.js, and jQueryUI. The task is to upload an image in the upload folder and store the path of the image along with its position which is set by users (jQueryUI draggable is used for this). It works just fine. But I don't know exactly how it works.
Can anyone explain to me how we are grabbing the dragged position set by users and how the whole thing is working all together. If you need to see the PHP script I can share thattoo. Thanks
$(document).ready(function () {
/* Uploading Profile BackGround Image */
$('body').on('change', '#bgphotoimg', function () {
$("#bgimageform").ajaxForm({
target: '#timelineBackground',
beforeSubmit: function () {},
success: function () {
$("#timelineShade").hide();
$("#bgimageform").hide();
},
error: function () {
}
}).submit();
});
/* Banner position drag */
$("body").on('mouseover', '.headerimage', function () {
var y1 = $('#timelineBackground').height();
var y2 = $('.headerimage').height();
$(this).draggable({
scroll: false,
axis: "y",
drag: function (event, ui) {
if (ui.position.top >= 0) {
ui.position.top = 0;
} else if (ui.position.top <= y1 - y2) {
ui.position.top = y1 - y2;
}
},
stop: function (event, ui) {}
});
});
/* Bannert Position Save*/
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + Z[0];
$.ajax({
type: "POST",
url: "image_saveBG_ajax_bg.php",
data: dataString,
cache: false,
beforeSend: function () {},
success: function (html) {
if (html) {
$(".bgImage").fadeOut('slow');
$(".bgSave").fadeOut('slow');
$("#timelineShade").fadeIn("slow");
$("#timelineBGload").removeClass("headerimage");
$("#timelineBGload").css({
'margin-top': html
});
return false;
}
}
});
return false;
});
});
$("body").on('click', '.bgSave', function () {
var id = $(this).attr("id");
var p = $("#timelineBGload").attr("style");
var Y = p.split("top:");
var Z = Y[1].split(";");
var dataString = 'position=' + `Z`[0];
You are getting the position here just before the ajax post to the PHP script, it is crudely getting the 'top' CSS attribute from the inline style on #timelineBGload element.
If you inspect the DOM when dragging #timelineBGload UIDraggable updates the top (and left) as you move it around

Select2 in a complex form as abstract class

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);
});
}
};

What would i use as a get request in jquery/ajax to set parameters

i am new to Jquery/Ajax and i am trying to have the source url for the json change based on the url parameters i setup, i have working version in PHP, but i don't know how to write it in JQuery
This is my PHP Code (what i am currently using
$id = urlencode($_GET['id']);
$page = urlencode($_GET['results']);
$url = "https://gdata.youtube.com/feeds/api/playlists/$id?alt=jsonc&v=2&max-results=25&&start-index={$results}";
This code grabs the id and includes it to alter the url of the source file used in the script
so how would i make this code act in the same way?
$(document).ready(function() {
startindex = 1;
loadmore = 20;
addMore(startindex, loadmore);
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore($('#list li').length, 20);
});
});
function addMore(startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/ID_WOULD_GO_HERE?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
Please help, Thanks!
Please try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="list"></div>
<script>
$(document).ready(function() {
startindex = 1;
loadmore = 20;
id = urlVar("id");
if (id!="") {
addMore(id, startindex, loadmore);
}
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore(id, $('#list li').size(), 20);
});
});
function urlVar(varName) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[varName]?vars[varName]:"";
}
function addMore(id, startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/"+ id +"?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
console.log(data);
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
</script>
To test: this_script.php?id=RD029cW4vF6U2Dc
Potentially you could also get PHP to put the variable into the URL before hand.
Example:
src = "https://gdata.youtube.com/feeds/api/playlists/<?php echo $_GET['id'];?>?alt=json&max-results=" + loadmore + "&start-index=" + startindex;

Categories