PDA

View Full Version : How to combine these 2 scripts?


bigsy85
12-08-2009, 02:57 PM
Hi all,

Feel bad as this is my first post...but I really need some help.

Does anyone know how I can combine the 2 scripts below. I have difficulty with Ajax, much better at PHP so I'll make sure i'll help someone out in that area.


Script 1.
<script language="javascript" type="text/javascript">
function changebgcolor(id,color) {

document.getElementById(id).style.backgroundColor=color;
}
function changevalue(field,color)
{
for(var i=0;i<document.cart_quantity.elements.length;i++)
{
if(document.cart_quantity.elements[i].name==field)
{
document.cart_quantity.elements[i].value=color;
}
}
}

var xmlHttp
function getattribimage(attribfield,width,height,products_options_values_id,products_id)
{


xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}

var url="attrib_prod_info.php";
url=url+"?width="+width+"&height="+height+"&products_options_values_id="+products_options_values_id+"&products_id="+products_id;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

}

function stateChanged()
{
if (xmlHttp.readyState==4)
{

var product_color_image=xmlHttp.responseText;
if(product_color_image!=''){
document.getElementById('productMainImage').innerHTML = product_color_image;
}
}
}
//--------------------------------------------------------

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}


function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>



________________
Script 2

$load = true; // if any of the PHP conditions fail this will be set to false and DPU won't be fired up
define('DPU_PRODUCT_FORM', 'cart_quantity'); // this should never change
define('DPU_PRICE_ELEMENT_ID', 'productPrices'); // this is the ID of the element where your price is dieplayed
$load = true;
$pid = (!empty($_GET['products_id']) ? intval($_GET['products_id']) : 0);
if (0==$pid) {
$load = false;
} elseif (zen_get_products_price_is_call($pid) || zen_get_products_price_is_free($pid) || STORE_STATUS > 0) {
$load = false;
}
$pidp = zen_get_products_display_price($pid);
if (empty($pidp)) $load = false;

if ($load) {
?>
<script language="javascript" type="text/javascript">
// Hidey codey <![CDATA[
// Set some global vars
var theFormName = '<?php echo DPU_PRODUCT_FORM; ?>';
var theForm = false;
var theURL = '<?php echo DIR_WS_CATALOG; ?>dpu_ajax.php';
var _secondPrice = '';
var objSP = false; // please don't adjust this
var request = new Array();

function objXHR()
{ // scan the function clicked and act on it using the Ajax interthingy
var url; // URL to send HTTP requests to
var timer; // timer for timing things
var XHR; // XMLHttpRequest object
var _responseXML; // holds XML formed responses from the server
var _responseText; // holds any textual response from the server
var request; // associative array to hold requests to be sent

request = new Array();
this.createXHR();
}

objXHR.prototype.createXHR = function () { // this code has been modified from the Apple developers website
this.XHR = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest) { // decent, normal, law abiding browsers
try { // make sure the object can be created
this.XHR = new XMLHttpRequest();
} catch(e) { // it can't
this.XHR = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) { // this does stuff too
try {
this.XHR = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
this.XHR = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
this.XHR = false;
}
}
}
}

objXHR.prototype.getData = function(strMode, resFunc) { // send a request to the server in either GET or POST
strMode = (strMode.toLowerCase() == 'post' ? 'post' : 'get');
var _this = this; // scope resolution
this.createXHR();

if (this.XHR) {
this.XHR.onreadystatechange = function () {
if (_this.XHR.readyState == 4) {
// only if "OK"
if (_this.XHR.status == 200) {
_this._responseXML = _this.XHR.responseXML;
_this._responseText = _this.XHR.responseText;
_this.responseHandler(resFunc);
} else {
alert('Status returned - ' + _this.XHR.statusText);
}
}
}
this.XHR.open(strMode.toLowerCase(), this.url+(strMode.toLowerCase() == 'get' ? '?' + this.compileRequest() : ''), true);
if (strMode.toLowerCase() == 'post') this.XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
this.XHR.send(this.compileRequest());
} else {
var mess = "I couldn't contact the server!\n\nIf you use IE please allow ActiveX objects to run";
alert (mess);
}
}

objXHR.prototype.compileRequest = function () {
// parse the request array into a URL encoded string
var ret = ''; // return request string

for (var e in request) {
ret += e + '=' + request[e] + '&';
}

return (ret.substr(0, ret.length - 1));
}

objXHR.prototype.responseHandler = function (theFunction) { // redirect responses from the server to the right function
request = new Array();
eval('this.'+theFunction);
}

objXHR.prototype.getPrice = function () {
this.url = theURL;
var n=theForm.elements.length;
for (var i=0; i<n; i++) {
var el = theForm.elements[i];
switch (el.type) { <?php // I'm not sure this even needed as a switch; testing needed ?>
case 'select':
case 'select-one':
case 'text':
case 'hidden':
request[el.name] = escape(el.value);
break;
case 'checkbox':
case 'radio':
if (true == el.checked) request[el.name] = escape(el.value);
}
}
this.getData('post', 'handlePrice()');
}

objXHR.prototype.handlePrice = function () {
var thePrice = document.getElementById('<?php echo DPU_PRICE_ELEMENT_ID; ?>');
var type = this._responseXML.getElementsByTagName('responseType')[0].childNodes[0].nodeValue;
if (type == 'error') {
this.showErrors();
} else {
var temp = this._responseXML.getElementsByTagName('responseText');
for(var i=0, n=temp.length; i<n; i++) {
var type = temp[i].getAttribute('type');
switch (type) {<?php // the 'type' attribute defines what type of information is being provided ?>
case 'priceTotal':
thePrice.innerHTML = temp[i].childNodes[0].nodeValue;
if (_secondPrice !== false) updSP();
break;
case 'quantity':
with (temp[i].childNodes[0]) {
if (nodeValue != '') {
thePrice.innerHTML += nodeValue;
updSP();
}
}
break;
}
}
}
}

function updSP() {
// adjust the second price display; create the div if necessary
var flag = false; // error tracking flag

if (_secondPrice !== false) { // second price is active
var centre = document.getElementById('productGeneral');
var temp = document.getElementById('<?php echo DPU_PRICE_ELEMENT_ID; ?>');
var itemp = document.getElementById(_secondPrice);

if (objSP === false) { // create the second price object
if (!temp || !itemp) flag = true;

if (!flag) {
objSP = temp.cloneNode(true);
objSP.id = temp.id + 'Second';
itemp.parentNode.insertBefore(objSP, itemp.nextSibling);
}
}
objSP.innerHTML = temp.innerHTML;
}
}

objXHR.prototype.showErrors = function () {
var errorText = this._responseXML.getElementsByTagName('responseText');
var alertText = '';
var n=errorText.length;
for (var i=0; i<n; i++) {
alertText += '\n- '+errorText[i].childNodes[0].nodeValue;
}
alert ('Error! Message reads:\n\n'+alertText);
}

var xhr = new objXHR;

function init() {
var n=document.forms.length;
for (var i=0; i<n; i++) {
if (document.forms[i].name == theFormName) {
theForm = document.forms[i];
continue;
}
}

var n=theForm.elements.length;
for (var i=0; i<n; i++) {
switch (theForm.elements[i].type) {
case 'select':
case 'select-one':
theForm.elements[i].onchange = function () { xhr.getPrice(); }
break;
case 'text':
theForm.elements[i].onkeyup = function () { xhr.getPrice(); }
break;
case 'checkbox':
case 'radio':
theForm.elements[i].onclick = function () { xhr.getPrice(); }
break;
}
}

xhr.getPrice();
}

<?php
// the following statements should allow multiple onload handlers to be applied
// I know this type of event registration is technically deprecated but I decided to use it because I haven't before
// There shouldn't be any fallout from the downsides of this method as only a single function is registered (and in the bubbling phase of each model)
// For backwards compatibility I've included the traditional DOM registration method ?>
try { // the IE event registration model
window.attachEvent('onload', init);
} catch (e) { // W3C event registration model
window.addEventListener('load', init, false);
} finally {
window.onload = init;
}
// Endy hidey ]]></script><?php } ?>

Many Thanks to all thank can help.

bigsy85
12-09-2009, 03:04 PM
As I'm in quite a rush for this, whoever can solve this I will send £30 to their PayPal account(the first reply that combines the two script).

Need to know any more just ask.

Thanks all.

hdewantara
12-09-2009, 08:50 PM
Hi,
Could you be more specific what to combine?

Since there are just bunch of functions,
and no real usage, I guess just to mix the two won't
rise an error or conflicts.

Regards,

bigsy85
12-09-2009, 09:54 PM
Thanks for your reply.

The two scripts are 2 modules for zen cart. One changes the main the product image when an attribute is selected(http://www.zen-cart.com/index.php?main_page=product_contrib_info&products_id=994). And the other separate script updates the price with which ever attribute is selected (http://chrome.me.uk/download.php?id=1).

The problem is when both modules are installed together the price updater stops working. I'm guessing because they both use a global XMLhttrequest which is conflicting. Both modules work until the page stops loading which once loaded locks the scripts down allowing only one to function.

Let me know if you need to know more

hdewantara
12-11-2009, 07:08 AM
Uf! I still can not find any variables nor objects conflicting between the 2 scripts,
but only an unknown reason for repeating of function GetXmlHttpObject() within script #1.
You might delete one of them, but I guess that would not solve the problem.

Script2 declares ajax object xhr, different from script1's, xmlHttp.
Each objects could then send their own requests, and each shall receive own responses.
So if there are any ajax request-response overriding, in your case,
would come from xhr itself.. overriding previous xhr request,
or from xmlHttp.. overriding previous xmlHttp request.

Is there any demo where I could see this conflicting effects?

hdewantara
12-11-2009, 07:53 AM
So if there are any ajax request-response overriding, in your case,
would come from xhr itself.. overriding previous xhr request,
or from xmlHttp.. overriding previous xmlHttp request.

Sorry, I was wrong about it.
Only script1's xmlHttp does self-overriding, not script2's xhr.

How does script1's function getattribimage() get called from your page?
Is it from onclick / onkeyup / onchange events ?

Regards,

bigsy85
12-11-2009, 10:19 AM
Hi hdewantara, thanks for helping.

function getattribimage() is called onChange activated by a drop down menu.

The scripts are used on a canvas site. A canvas size is selected and the main image is replaces by the size reference. And the price should update with which ever canvas they select. I will PM the site address.

The extra function GetXmlHttpObject() in script 2 I remember is a mistake. Only one is needed. If you download the mods from the links given in my previous code, perhaps its something also causing it to conflict.

Thanks

hdewantara
12-11-2009, 12:50 PM
my pleasure...

BTW, I was just changing the size of your "Heath Ledger - The Joker Canvas Art",
got the priced well updated, but not main image. And also got a Firefox warning Empty string passed to getElementById().

So that might be generated from the line within function stateChanged(); that there was no ajax response at all.
To capture what causing it, we could add a bit script to this function:
function stateChanged(){
if (xmlHttp.readyState==4){
if (xmlHttp.status==200){
var
product_color_image=xmlHttp.responseText;
if(product_color_image!=''){
document.getElementById('productMainImage').innerHTML = product_color_image;
}
}
else{
with (xmlHttp){
window.alert("HTTP Status="+status+":"+statusText);
}
}
}
}

... and see what it would report to you now.

Good luck.

bigsy85
12-11-2009, 01:30 PM
I've updated the code with your suggestion, no error is alerted which means its sending a response? but not updating the image.

If I remove the script for the price updater the image will change so there should be a response.

hdewantara
12-11-2009, 06:05 PM
...no error is alerted which means its sending a response? but not updating the image. Yes, you are right. It is just to check, not updating images.
And it also means no HTTP error has occured during request and response.

But why the product_color_image as a response is an empty string?...And also got a Firefox warning Empty string passed to getElementById().

... since there is no request for image updating? :)

So here's a solution (hope I'm right)...

Since script2 (price updater) has always registered its onchange event first,
we'll adjust script1's (image updater) by writing different code for <div class="back">.
It will now look like following:
<div class="back">
<select name="id[x]" id="attrib-x">
<option...
...
</select>
</div>
<script type="text/javascript">
document.getElementById("attrib-x").addEventListener("change",getattribimage('id[x]',547,500, this.value,5),false);
</script>

bigsy85
12-11-2009, 06:20 PM
Hi thanks for continuing to work on this.

The code that you show above, where should this be placed. Is that part of the original script in the thread or part of another script within one of the mods that I linked?

Thanks.

hdewantara
12-11-2009, 06:23 PM
ok let me search the original image updater module first...
Nope, can't find any..

See attachment, I thought you designed this HTML option tag.. no?

bigsy85
12-11-2009, 11:32 PM
Hi,

I'v added for a minute the script and it returns a alert '404 HTTP not found' message.

else{echo $options_name[$i];} ?></h4>
<div class="back"><?php echo "\n" . $options_menu[$i]; ?></div>
<br class="clearBoth" />
</div>
<script type="text/javascript">
document.getElementById("attrib-2").addEventListener("change",getattribimage('id[2]',547,500, this.value,5),false);
</script>

Still need to make the 2 a variable for $i somehow

bigsy85
12-11-2009, 11:45 PM
Is it possible that attrib-2 isnt declared as an elementbyid? how could i change this?

hdewantara
12-12-2009, 12:06 AM
Is it possible that attrib-2 isnt declared as an elementbyid? how could i change this? It is there to detect the <select> HTML element... why?

Just a note:
I still see the a piece of source code of your page as:
...document.getElementById(id[2]).addEventListener(...
where it should be:
...document.getElementById("id[2]").addEventListener(...

Regards,

bigsy85
12-12-2009, 12:15 AM
Updated the code again, its still alerting 'HTTP Status: 404 Not Found'

<label class="attribsSelect" for="attrib-2">1. Canvas Size</label></h4>
<div class="back">
<select name="id[2]" id="attrib-2" onchange="getattribimage('id[2]',547,500, this.value,2);">
<option value="16" selected="selected">-- Please Choose --</option>
<option value="17">8x10 (inch)</option>
<option value="18">12x16 (inch) (+&pound;5.84)</option>
<option value="15">20x16 (inch) (+&pound;12.97)</option>
<option value="1">25x20 (inch) (+&pound;24.65)</option>
<option value="3">30x25 (inch) (+&pound;29.19)</option>
<option value="2">40x30 (inch) (+&pound;42.16)</option>
</select>

</div>
<br class="clearBoth" />
</div>


<script type="text/javascript">
document.getElementById("id[2]").addEventListener("change",getattribimage("id[2]",547,500, this.value,5),false);
</script>

hdewantara
12-12-2009, 12:30 AM
My mistake bigsy85.. I have mistyped it within the latest post.

Since the HTML tag <select> has id="attrib-xxx" then getElementById should be written as document.getElementById("attrib-xxx").addEventListener(...

Sorry.:D

bigsy85
12-12-2009, 12:32 AM
Ok thanks, just updated that.

Still doesnt work though.

if you notice when the page is loading it does work?

hdewantara
12-12-2009, 12:34 AM
OK let me look..

bigsy85
12-12-2009, 12:35 AM
I've added an alert for product_color_image which should have the response text but it is undefined.

function stateChanged(){
if (xmlHttp.readyState==4){
if (xmlHttp.status==200){
window.alert(product_color_image);
var
product_color_image=xmlHttp.responseText;
window.alert(product_color_image);
if(product_color_image!=''){
document.getElementById('productMainImage').innerHTML = product_color_image;

}
}
else{
with (xmlHttp){
window.alert("HTTP Status="+status+":"+statusText);
}
}
}
}

hdewantara
12-12-2009, 12:53 AM
I am confused...:(
Got this error in FF3.5.3:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://www.icanmakeyouart.co.uk/custom-portrait/modern-art-portrait :: <TOP_LEVEL> :: line 599" data: no]

hdewantara
12-12-2009, 01:11 AM
Ahh I think I know why this error showed up. We could not pass function arguments as in
document.getElementById("id[2]").addEventListener("change",getattribimage("id[2]",547,500, this.value,5),false);
and have to write:
document.getElementById("id[2]").addEventListener("change",getattribimage,false);

So how could we pass the arguments?...

hdewantara
12-12-2009, 02:01 AM
Ok. I found an archive related to this @ http://www.codingforums.com/archive/index.php/t-5909.html and did a little experiment.

Based on that, lets try new script as follows:

<div class="back">
<select name="id[x]" id="attrib-x">
<option...
...
</select>
</div>
<script type="text/javascript">
function afunc(){
getattribimage('id[x]',547,500, this.value,5);
}
document.getElementById("attrib-x").addEventListener("change",afunc,false);
</script>

Phew, bigsy85... let's have a break ok?
I'm quite dizzy now.

bigsy85
12-12-2009, 02:20 AM
Good work, works great!

We finally got there, enjoy your rest.

Thanks.

hdewantara
12-13-2009, 01:46 AM
Congratulation,
I'm happy too :thumbsup:

Few last notes in using addEventListener():
a) For usage cleaning reason: should add something like <body unload="removeEventListener("change",afunc,false);"> within each of your HTML pages.
b) For cross browser compability sake: IE uses other its own method w/ same functionality (I forgot what it is).

Nice working with you.