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
Related
Below code works on localhost, but not on live server.
MAIN EDIT:
Only 1 thing remains which is not working:
On AJAX success this will being executed:
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
How ever, the label(for example) is not being updated. The label needs to be updated by the score which is given (data.score_result).
Ajax code:
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
When I put alert('test'); above the $.ajax({ code it shows 'test'. When I put the alert INSIDE (just below) the $.ajax({ code, it does not show the alert.
saveScore function:
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
Results/info:
alert(post); gives me the correct data result.
saveScore is executed, but won't close afterwards (setTimeout).
#label and #monitoring_score are not being updated like it has to do.
using jquery-3.1.1.
I'm distraught on how to solve this. Anyone has an idea on how to fix?
Extra:
#Teemu:
Add an error handler to the AJAX call too, most likely it's the
server-side which passes an error instead of data. Or open Network tab
from the DevTools, and see if you're actually getting 200 OK message
and the data.
Edit 1: (Whole javascript code):
<script>
$(document).ready(function () {
$(".nav-tabs a").click(function () {
$(this).tab('show');
});
});
$(document).ready(function () {
$('.summernote').summernote({
height: 450, //set editable area's height
toolbar: [
['view', ['fullscreen']],
['help', ['help']]
],
codemirror: { // codemirror options
theme: 'monokai'
}
});
});
jQuery(document).ready(function () {
$('.nvt').on('click', function () {
// get the id:
var id = $(this).attr('id');
var res = id.split("_");
// Reset rating:
var rating_input = "item_score_" + res[1];
$('#' + rating_input).rating('update', 0);
var comment = $("#comments_" + res[1]).val();
var score = 0;
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: 'json',
beforeSend: function (data) {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
});
$('.savecomment').on('blur', function () {
var comment_id = $(this).attr('id');
var res = comment_id.split("_");
var commentraw = $("#comments_" + res[1]).val();
var comment = encodeURIComponent(commentraw);
var post = 'controller=QualityMonitoring&task=setComment&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
success: function (data) {
if (data.result == 666) {
$("#comments_" + res[1]).css("background-color", "#ffcccc");
}
}
});
});
});
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready(function () {
$('.btn-file :file').on('fileselect', function (event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if (input.length) {
input.val(log);
} else {
if (log) alert(log);
}
});
});
function closediv() {
$(document).unbind("keyup");
$("#overlay").fadeOut("slow", function () {
$("#overlay").remove();
$(".FixedDiv").removeClass("panel-danger");
});
}
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
$(document).ready(function () {
var $sidebar = $(".FixedDiv"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 55;
$window.scroll(function () {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 24
});
}
});
});
</script>
Is your PHP code valid and not throwing extra code which is messing up your JSON object. When there is a notice the JSON object becomes a string instead of a JSON string and then javascript can't parse it anymore.
Please make a new clean controller without any other code, post the data again and then check what is happening. Never return data but echo data with an exit.
Javascript and Code looks valid but somewhere else in your MVC may throw HTML code in the exit statement or generating it before you enter the controller which is required to return the data.
after function saveScore() add:
var close = function() { $('#overlay').remove(); };
after success: function (data) {} remove last comma
I think a few of the other posters are on to something about the invalid JSON,
I would add however, this is something I like to do for JSON
<?php
ob_start(); //turn on output buffering
//...other code
$debug = ob_get_clean();
$response['debug'] = $debug; //comment this when live in production
header('Content-type: application/json');
echo json_encode($response);
What this does is turn on output buffering. Which traps any output and buffers it. This includes warnings, notices, echo, and print stuff. Then it stuffs it into the response as debug and forwards it to the client.
Obviously you would not want to do this on live production server, but you can easily comment it out. It can be a security issue to include some errors and stack trace information to the client. But for debugging purposes it works great.
The problem with JSON is if you are checking the value of something somewhere (printing it) or have any notices it will muck up your JSON. For example
printed content
{"foo":"bar"}
So this takes away that problem entirely (assuming you output buffer before printing anything) like so:
{"foo":"bar", "debug":"printed content"}
And now you have valid JSON, and as a side bonus you can print out your debug info by simply doing
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
if(data.debug) console.log(data.debug);
}
});
It's simple and effective.
Hope it helps.
Try adding an error handler to your Ajax function and see what it returns:
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
Share the result with us so we can trouble shoot your issue and help you.
Are you wrapping your js code in $(document).ready() ?
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Try enclosing everything in
$(function(){
//your code here
})
Like this:
$(function(){
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
});
From the code you posted, the comments below and the discussion ( actually was very helpful to jump to this conclusion ) .. i can point a couple of things, but first :
adding error_reporting(0); in the begining of the controller right after <?php should solve your problem. ( if my guess is correct and it's just a notice, not an actual error)
i'm guessing that you already have this in your localhost 's php.ini and on the live server you have the default error_reporting = E_ALL, due to two different installations of php.
there's probably somewhere in the controller a notice of an undefined index or something, and php is trying to let you know by outputting this :
<br />
<b>Notice</b>: Undefined index: ...
{"calculated_score":10,"score_result":"1.75 pts"}
it starts with a < and that's where this comes from
SyntaxError: Unexpected token < in JSON at position 0
the $.ajax is unable to parse this because you have dataType="json" and this means that it is expecting a valid json back from the server, so you get the 200 status because the request was successful with no errors and console.log(data) will be empty because it was unable to parse it.
a simple way to reproduce this is creating a test php file and send the request to it instead of controller.php like :
<?php
error_reporting(0); // try with and without this line.
$data = [
'city' => 'Montreal',
'Country' => 'Canada'
];
echo $_GET['something']; // this will trigger a notice of undefined index something
echo json_encode($data);
?>
you can remove dataType:"json" and put console.log(data) in the success function and look in the console to see what the server is really telling you.
but here's something that bugs me ..
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
this looks like a query string you use for GET requests but you have type:"POST" in your ajax request ..
i don't know how you're handling this in the controller but it should be type:"GET" to send data like this, but if you want to send the data with POST then var post should be an object, ( this could be the problem as it defaults to GET when not set and in the controller there's a $_GET['task'] instead of $_POST['task'] or vise-versa ) so here's a snippet to convert the query string to a json :
function QueryStringToJSON(str) {
var pairs = str.split('&');
var result = {};
pairs.forEach(function (pair) {
pair = pair.split('=');
var name = pair[0]
var value = pair[1]
if (name.length)
if (result[name] !== undefined) {
if (!result[name].push) {
result[name] = [result[name]];
}
result[name].push(value || '');
} else {
result[name] = value || '';
}
});
return (result);
}
var string = 'controller=QualityMonitoring&task=setScore&monitor_id=5&q=blah&item_score=99&comment=hello';
var obj = QueryStringToJSON(string);
console.log(obj);
i hope this helps or at least gives you an idea, and Good Luck.
<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>
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");
}
}
});
}
}
});
I have this ajax-loaded #container and I'm trying to get it to play nice with some of my plugins. So far I managed to get scrollTo and a lightbox working inside this "container of death" using jquery.live but no luck with my fancy "add to cart" buttons. I've been playing around with .delegate, the livequery plugin, etc., for a few days now but I'm really not advanced enough to figure out what goes where. (I have a pretty shallow understanding of what I'm doing.)
Here's my shopping cart plugin, it's fairly small and straightforward. Can you give suggestions on what (.live, .delegate, or .livequery, or perhaps something else entirely) should be inserted where?
(Note: shopme p = the add to cart buttons, which need to be inserted inside the ajax-loaded "container of death." The rest of the cart exists outside said container and works fine since it's not ajax'ed in.)
$(document).ready(function(){
$('.wooo').bloooming_shop();
$('body').append('<div id="panel"><div id="panelcontent"></div><div class="panelbutton" id="hidepanel" style="display: none;"><a><font class="cartfont2">hide cart</font></a></div></div><div id="showpanel" class="panelbutton" style="display: visible;"><a><font class="cartfont">shopping cart</font></a></div><div id="btntarget"></div>');
$('#panelcontent').hide();
$.ajax({
type: "GET",
url: "/wooo/cart.php",
async: false,
dataType: "html",
success: function(html){
$('#panelcontent').html(html);
}
});
$(".panelbutton").click(function(){
$("#panel").animate({
height: "200px"
}, "fast",function(){
$('#panelcontent').show();
});
$("#hidepanel").fadeIn();
$("#showpanel").fadeOut();
});
$("#hidepanel").click(function(){
$("#panel").animate({
height: "0px"
}, "fast", function(){
$("#showpanel").fadeIn();
$('#panelcontent').hide();
});
$("#hidepanel").fadeOut();
});
// START 'ADD TO CART' BUTTONS
$('.shopme p').click(function(){
var pid = $(this).attr('rel');
$('body').prepend('<div class="shadow" id="'+$(this).attr('rel')+'_shadow"></div>');
var shadow = $('#'+pid+'_shadow');
shadow.width($(this).parent().css('width')).height($(this).parent().css('height')).css('top', $(this).parent().offset().top).css('left', $(this).parent().offset().left).css('opacity', 0.5).show();
shadow.css('position', 'absolute');
shadow.animate( {
width: $('#btntarget').innerWidth(),
height: $('#btntarget').innerHeight(),
top: $('#btntarget').offset().top,
left: $('#btntarget').offset().left
}, {
duration: 2000
} )
.animate({
opacity: 0
},
{
duration: 700,
complete: function(){
shadow.remove();
}
});
var option = $('#'+pid+' .woooptions').val();
var formData = 'pid=' + pid + '&option=' + option;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : formData,
success : function (html) {
$('#panelcontent').html(html);
}
});
});
$('.removeitem').live('click', function() { // .LIVE is used here
rid = $(this).attr('id');
rop = $(this).attr('rel');
var remData = 'remove=' + rid + '&rop=' + rop;
$.ajax({
type : 'POST',
url : '/wooo/cart.php',
data : remData,
success : function (html) {
$('#panelcontent').html(html);
// alert('thx');
}
});
});
}); // document
function checkOut(){
jQuery.ajax({
url: "/wooo/cart.php",
type: "POST",
data : "destroysession=true",
success: function(data, textStatus, jqXHR){
if(data){
window.location.href=jQuery('a.checkout').attr("data-href");
}else{
console.log("There is no data!")
}
},
error: function(jqXHR, textStatus, errorThrown){
console.log("AJAX ERROR: "+errorThrown)
}
});
}
/** replace ******/
jQuery.fn.bloooming_shop = function(){
this.each(function(){
var elem = $(this);
var cl = 'bt1';
var id = $(this).html();
var opt = $(this).attr('options');
var text = $(this).attr('text');
var price = $(this).attr('price');
// alert(price);
if (text == undefined) {
text = 'add to cart';
}
if (opt == 'true' && price != 'true' ) {
cl = 'bt3';
}
if (price == 'true' && opt == 'true') {
cl = 'bt4';
}
if (price == 'true' && opt != 'true') {
cl = 'bt2';
}
elem.removeClass('wooo');
elem.addClass('shopme');
elem.addClass(cl);
elem.attr('id','pid'+id);
elem.html('<p rel="pid'+id+'" class="'+cl+'">'+ text +'</p>');
// get product data
if (price == 'true' || opt == 'true') {
$.ajax({
type : 'GET',
url : '/wooo/functions.php?mode=p_data&id='+id+'&opt='+opt+'&price='+price,
success : function (html) {
elem.append(html);
if (jQuery().sSelect) {
elem.children('.woooptions').sSelect();
}
// change price
$('.woooptions').change(function(){
var selid = $(this).attr('id');
var rel = $('#'+selid+' option:selected').attr('rel');
if (rel != undefined) {
$(this).parent().children('.woooprice').html(rel);
}
});
}
});
}
});
return false;
};
How do I keep this plugin alive, even within ajax'ed-in #container? I really just need the 'add to cart' buttons (shopme p) to be in said container div. Thank you.
.live("click", function(){
instead of just click.
How could I change the code below so that when an element is being being dragged the script will stop fetching the output file until that element was released?
$(document).ready(function() {
//$(".draggable").draggable();
$(".draggable").draggable({ containment: '#container', scroll: false });
$(".draggable").draggable({ stack: { group: '#container', min: 1 } });
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
//post x,y to php (and the id of the elemnt)
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top);
});
var req = function () {
$.ajax({
url: "out.php",
cache: false,
success: function(html){
$("#stuff").empty().append(html);
var css_attr = html.split(",");
$('#1').css('left', css_attr[0] + 'px').css('top', css_attr[1] + 'px');
},
complete: function(){
req();
}
});
};
req();
});
Note: This script is dependent on the following JavaScript sources:
jquery.js
http://jqueryui.com/latest/ui/ui.core.js
http://jqueryui.com/latest/ui/ui.draggable.js
http://jqueryui.com/latest/ui/ui.droppable.js
Anything Helps...Thanks.
Draggables has options to allow you to associate functions with the start and stop of the drag. (see http://api.jquery.com/, click jQuery UI at the top for docs). So you can use that and perhaps have a global boolean that gets set when the drag starts and unset when the drag ends. Have your req() function check this boolean and exit if it's set. Something like:
var halt_request = 0;
$(".draggable").draggable({
containment: '#container',
scroll: false,
start: function(){ halt_request = 1; },
stop: function(){ halt_request = 0; }
});
...
var req = function () {
if (halt_request) {
sleep(10); // so you're not looping too quickly
req();
return;
}
$.ajax({
url: "out.php",
...
And better yet, instead of having req() call itself, have it use setTimeout. Have the timeout as a global and have the start/stop functions clear/set the timeout.
You can even take kbosak's idea a bit further:
var req = function () {
...
$(".draggable").draggable({
containment: '#container',
scroll: false,
stop: req
});
In other words, create a draggable that calls the function "req" when dragging stops.
Also, you can also totally rewrite this in a more standard form:
function req () {
...
and it will be the exact same thing. Also, you can do:
$(function() {
instead of:
$(document).ready(function() {
and you can merge your two draggable calls. So ... if I were writing it, the final code would be:
function req () {
...*insert code for req here*...
};
$(function() {
$(".draggable").draggable({
containment: '#container',
scroll: false,
stack: { group: '#container', min: 1 },
stop: req
});
$("*", document.body).click(function (e) {
var offset = $(this).offset();// get the offsets of the selected div
e.stopPropagation();
var theId = $(this).attr('id');// get the id of the selceted div
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
//post x,y to php (and the id of the elemnt)
$.post("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top);
});
req();
});
Maybe you can associate it with the mouseup event?
http://docs.jquery.com/Events/mouseup#fn
Instead of associating the draggable object directly with the AJAX call, associate it with a trigger which you can use to activate the mouseleave.