PHP get div position and store in session - php

I know how to get the position of a div using JS, I'm using Jquery's draggable script, and have an event that when the person stop dragging that it should get the location of the div (top and left):
document.getElementById('object').style.top;
document.getElementById('object').style.left;
now the question is how do I get those coordinates into a php session...?

Maybe the best (easiest) option is to store them in a cookie. The cookie can be read by PHP if you like, but even if you don't, you can still use the cookie again when the page is reloaded in the same browser.
If you want to store the value so it is kept too if the user logs in on another browser (or in a different session), you can store the cookie in a database.

On drop, make an Ajax request to a PHP script that puts them into $_SESSION.

This is the final solution I made thanks to GolezTrol :), I never knew you could make cookies using js
<script type="text/javascript">
function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
</script>
<script type="text/javascript">
$(function() {
$( "#object" ).draggable({ containment: ".body", scroll: false });
$( "#object" ).bind( "dragstop", function(event, ui) {
var l = document.getElementById('object').style.left;
javascript: setCookie('objectl', l, 365);
var t = document.getElementById('object').style.top;
javascript: setCookie('objectt', t, 365);
});
});
</script>

Related

Extract div id to php variable to multiply

I have a script Ajax/jQuery this autoupdate a statistics in my site this is the code:
<!--Jquery/AJAX script-->
<script type="text/javascript">
function updateStats(stat)
{
var stat = ["online","newestPlayer","cuentas","personajes","guilds"];
var url = "template/Next/stats_do.php";
$.each(stat, function(i, key){
$.post(url, {stats: key}, function(data) {
$("#" + key).text(data);
});
});
}
setInterval('updateStats("updateStats")', 500);
</script>
Work all fine. for the results i use. for example...
But i have a ProgressBar with php. The code for work is (a part)
<?= round (HERE MY RESULT*100/$pBar2max); ?>%
The problem is that putting the does not allow multiplication in order to get the percentage
and i try
$onlines = <span id="online">
and insert a echo in the code, but not work, any solutions? i need extract a number in text for multiply with *100

Store Form Values In Cookie

I've been trying to teach myself about cookies for the last couple of hours and how I would go about storing values from a few form fields into a cookie.
Im not having much luck, all the examples I've found havent been very helpful.
Should I generate them using PHP or JS?
Any feedback or a kick in the right direction would be highly appreciated!
http://jsfiddle.net/yucM7/
Thanks in advance!
Here's an example.
All you need is jQuery and cookie plugin
Keep in mind, there're couple of changes in html code.
$(document).on('submit', '#myForm', function() {
// serialize our form (get string containing field names and values)
dataString = $(this).serialize();
// set new cookie
$.cookie('formCookie', dataString);
return false;
});
$(document).on('click', '#getCookie', function() {
// get serialized string from cookie
cookieData = $.cookie('formCookie');
// if cookie exists continue
if (cookieData != null) {
// split cookieData string into an array of fields and their values
cookieArray = cookieData.split('&');
// go through each field and split it too to get field name and it's value
$.each(cookieArray, function(k, v) {
field = v.split('=');
// populate field with data
$('#myForm [name="'+field[0]+'"]').val(field[1]);
});
}
return false;
});
You can set cookie using Javascript by following (Refer http://www.w3schools.com/js/js_cookies.asp):
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Setting cookie using Jquery: $.cookie("example", "foo");
Alternatively you can set your cookie from server by :
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);

Binding a php variable with Jquery slider

I have two JQuery sliders, value of "Second_Slider" gets updated and a div named
"amount2" as well as it should.
Now i want to update an php variable to the value of "Second_Slider" also. how can i achieve this?
$( "#Slider" ).bind( "slide", function(event, ui) {
$("#Second_Slider").slider({ value:300 });
$( "#amount2" ).val( "$" + $( "#Second_Slider" ).slider( "value" ) );
<?php $Php_Var_I_Want_to_Change = "what-do-i-put-here? ?> };
updated
you could try something like this
var slideXHR;
function setSlideSession(slideValue){
if( slideXHR == 'XMLHttpRequest'){
//stop previous ajax request
slideXHR.abort();
}
slideXHR = $.get('url/file.php', { item : slideValue });
}
$( "#Slider" ).bind( "slidestop", function(event, ui) {
$("#Second_Slider").slider({ value:300 });
var slideValue = $( "#Second_Slider" ).slider( "value" );
$( "#amount2" ).val( "$" + slideValue );
//set session variable on php via ajax
setSlideSession( slideValue );
};
php file
<?php
session_start();
$_SESSION['variable'] = $_GET['item'];
?>
You can't "bind" php variables to javascript variables.
Javascript is run client side, the only way you can get the values into PHP is by making a request from the client side.
e.g.
Submitting a form
Clicking a link
Sending an ajax request
I wouldn't suggest an approach to take without understanding why you want to bind it in the first place.
I can't really get your question but if i am following right you want to update a PHP variable through a jQuery slider's slideevent?
That's absolutely impossible once php is processed on server-side and then passed into the client as javascripts are processed on the client, after PHP has done its job!
If you want to send data to the server, use AJAX!
you are mixing JavaScript (client-site) with PHP (server-site) - will not work.
in your case you may consider sending an ajax request on change of slider - what could be overkill - every thing depends what it is for

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Unable to get Id of draggable divs in jQuery (using jQuery UI)

For some reason the script below is unable to get the id of the draggable divs using attr('id'), but it works on the other static elements on the page. I am totally confused as to why this wont work and if anyone has a solution for me it would me much appreciated.
$(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("http://localhost/index.php", "id=" + theId + "&x=" + offset.left + "&y=" + offset.top); //post x,y to php (and the id of the elemnt)
});
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
Currently you're attaching the click handler to all elements in the DOM with * (very very bad, don't do this!), including any children in those draggables.
You are correctly stopping the event from bubbling up using .stopPropagation(), but it's likely a child of a .draggable you've clicked, not the draggable itself. What you want is actually listening on the .draggable element themselves, like this:
$(".draggable").click(function (e) {
var offset = $(this).offset(),
theId = this.id;
e.stopPropagation();
$("#result").text(this.tagName + " id=" + theId + " (" + offset.left + "," + offset.top +")");
$.post("http://localhost/index.php", { id: theId, x: offset.left, y: offset.top });
});
The other changes here are id can be accessed directly, via this.id, and passing an object to $.post() is safer for serialization, like I have above.
Even the above isn't quite there though, you likely want to send the position when you stop dragging, by changing this:
$(".draggable").click(function (e) {
To this:
$(".draggable").bind("dragstop", function (e) {
...or in newer versions of jQuery (1.4.2+):
$(document.body).delegate(".draggable", "dragstop", function (e) {
Your click function works for me on a test page. Out of curiosity, if you move the 'e.stopPropogation()' line to the bottom of your click function, does it behave differently?
Be careful with *, you know, all means all, if you have <div><p><span><a></a></span></p></div> it means that the action is set to every single element. I'd specify classes or tags that should be affected by your function, to be always sure that you get what you want to be clicked.
Try your code replacing * with the object you think it's ID isn't get, and see if it works..
This may seem pretty obvious but are you sure that all the elements that your selecting actually have IDs. If your including everything (with the *) then it is likely that some elements don't have IDs.

Categories