Jump to content

<add to cart> link help


Pavlos1316

Recommended Posts

Hello,

 

I have this code to add items into the cart:

<a href="javascript:ajaxpage('body.php?action=add&id=1', 'content');" class="adcart">Add to cart</a>

This adds the item correctly but it takes me into the cart.php page.

 

How should I modified it so it adds the item into the cart and keeps me into my parent page?

 

Thank you

Link to comment
Share on other sites

</script>var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
</script>

Link to comment
Share on other sites

Sorry but due to hour difference and connection problems that I have these couple of days I am delaying on answering...

 

First of all the

body.php

there is wrong. it should say

cart.php

(I was playing aroiund and accidentally I copy paste the wrong line.

body.php

is the page that I want to stay in instead of taking me to

cart.php

 

Now... I have found a solution but... I don't know if it's correct what I did (cause I don't now much of js). I just know that it worked. This is what I did:

<a href="javascript:ajaxpage('cart.php?action=add&id=1', 'body.php', 'content');" class="adcart">Add to cart</a>

Now the

cart.php?action

adds item in the cart while it stays under

body.php

page.

 

Is this ok?

The js code I gave you is for opening me a new link under my content div using this line:

<a href="javascript:ajaxpage('body.php', 'content');" class="adcart">Add to cart</a>

Link to comment
Share on other sites

From what I see, that's not really a work around.  ajaxpage() takes two parameters.  The first is the filename + query string (if necessary) of the PHP script you want to send the request to.  The second is supposed to be the id of the element on the current page that will receive and display the response from the PHP script.  What you did is 'working' because there's likely no HTML element on your page with an id of body.php.  The response you get back from ajaxpage() is essentially being thrown away.

 

So, again, what does your 'add' action do?  It's the response it sends back that's key.

Link to comment
Share on other sites

Hello,

 

My add action takes the item from database with id=1 and inserts it in the cart.

 

If I don't put the add action inside the ajaxpage it redirects me to the cart.php (thing that I want to avoid).

 

 

As for

What you did is 'working' because there's likely no HTML element on your page with an id of body.php.

The only thing I can say is that I will never have any html element with id=body.php!!!

 

But what would be a real solution?

Link to comment
Share on other sites

You're not really understanding me.  I need to see what add does.  Not a generalized description, but actual code.  That way I can see what response, if any, it gives back.

 

Also, I never thought you had an HTML element with that id.  That's the entire point - like I said, ajaxpage()'s second parameter is supposed to be the id of an existing element so it can put the response from cart.php's add action in it.  Your 'fix' had you supplying body.php for that value.  Since no element has that id, the response is being lost, which is likely why you're not being redirected.  This is why I need to see what add does.  I need to verify my hypothesis.

Link to comment
Share on other sites

Here they are both of my cart factions:

 

function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
	return 'no items';
} else {
	// Parse the cart session variable
	$items = explode(',',$cart);
	$s = (count($items) > 1) ? 's':'';
	return ''.count($items).' item'.$s.'';
}
}

function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
	$items = explode(',',$cart);
	$contents = array();
	foreach ($items as $item) {
		$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
	}
	$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
	$output[] = '<table class="tblcart">';
	foreach ($contents as $id=>$qty) {
		$sql = 'SELECT * FROM stock WHERE ID = '.$id;
		$result = $db->query($sql);
		$row = $result->fetch();
		extract($row);
		$output[] = '<tr>';
		$output[] = '<td class="tdcart"><a href="javascript:ajaxpage(\'cart.php?action=delete&id='.$id.'\', \'content\');">Remove</a></td>';
		$output[] = '<td class="tdcart">'.$Item.' by '.$Description.'</td>';
		$output[] = '<td class="tdcart">£'.$Price.'</td>';
		$output[] = '<td class="tdcart"><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" style="text-align: center;"/></td>';
		$output[] = '<td class="tdcart">£'.($Price * $qty).'</td>';
		$total += $Price * $qty;
		$output[] = '</tr>';
	}
	$output[] = '</table>';
	$output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>';
	$output[] = '<div><button type="submit">Update<img src="../stock_photos/shopcart.png"></button></div>';
	$output[] = '</form>';
} else {
	$output[] = 'Your shopping cart is empty.';
}
return join('',$output);
}

Link to comment
Share on other sites

:facepalm: Where is the code you use to add an item to the cart?  ajaxpage() sends data to cart.php?action=add&id=1.  This means you must do something in cart.php with $_GET['action'].  That is the code the JavaScript is invoking, and that's what's supposed to be sending a response back.  That's the code I need to see.
Link to comment
Share on other sites

Ahhhhh....

 

Just a sec.... I thought I posted 3 scripts last time... Please don't hate me... not just yet!!!!! ::)

 

$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
	if ($cart) {
		$cart .= ','.$_GET['id'];
	} else {
		$cart = $_GET['id'];
	}
	break;
case 'delete':
	if ($cart) {
		$items = explode(',',$cart);
		$newcart = '';
		foreach ($items as $item) {
			if ($_GET['id'] != $item) {
				if ($newcart != '') {
					$newcart .= ','.$item;
				} else {
					$newcart = $item;
				}
			}
		}
		$cart = $newcart;
	}
	break;
case 'update':
if ($cart) {
	$newcart = '';
	foreach ($_POST as $key=>$value) {
		if (stristr($key,'qty')) {
			$id = str_replace('qty','',$key);
			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
			$newcart = '';
			foreach ($items as $item) {
				if ($id != $item) {
					if ($newcart != '') {
						$newcart .= ','.$item;
					} else {
						$newcart = $item;
					}
				}
			}
			for ($i=1;$i<=$value;$i++) {
				if ($newcart != '') {
					$newcart .= ','.$id;
				} else {
					$newcart = $id;
				}
			}
		}
	}
}
$cart = $newcart;
break;
}
$_SESSION['cart'] = $cart;
?>

Link to comment
Share on other sites

Okay, so $cart just a comma separated string of IDs....  Where does the actual database insert/update happen?  I see the $cart being passed around through sessions, but not a lot more than that.  And do you echo/return anything after the entire process is done?  Please show code.

Link to comment
Share on other sites

This is my html code after the add action:

 

<body>
<div id="shoppingcart">
<br />
<p class=difftext>Your Shopping Cart</p>
<br />
<p class="shcart">
<?php
echo writeShoppingCart();
?>
</p>
</div>
<br />
<br />
<div id="contents">
<p class=difftext>Please check quantities...</p>
<br />
<br />
<p class="shcart">
<?php
echo showCart();
?>
</p>
</div>

Link to comment
Share on other sites

Okay.  I'd like you to put your link code back to the way it was when it was redirecting you.  Once you do that please click on the link.  After that, I'd like you to answer the following questions:

 

Is the browser actually taking you to another page?  Or is your <div id="content"> being filled with what's in cart.php?  Can you compare the HTML in body.php that exists after you click the link to what's generated by cart.php?  Can you see if you're getting any JavaScript errors after you click your link?

 

Here's the reason why I'm asking these questions: like I've said, the ajaxpage() function anticipates the PHP script it talks to will send a response back.  It takes this response data and stuffs it in the element of the id given as the second parameter.  So, if you have:

 

ajaxpage("cart.php?action=add&id=1", "content")

 

It's going to send the GET data to cart.php, and then capture any response sent back by cart.php and insert it into the element in body.php specified by the second parameter, which in this case is <div id="content">. 

 

What do I mean by response?  Well, anything outputted by cart.php is a response.  This includes raw HTML when you exit PHP-mode in your files.  So, I'm betting you weren't being redirected at all.  Instead ajaxpage() most likely took all of the output generated by cart.php and placed it within body.php's <div id="content">, which would overwrite everything that was in there prior to the link being clicked.  You would still be at body.php, but it would likely look like you were at cart.php.

 

So, why does your modification 'work'?  Like I also said above, you were passing ajaxpage() a bogus value for the second parameter.  The function was looking for an HTML element within body.php with an id of body.php to put the response data in.  Since there is no element with that id, that part of ajaxpage() silently fails.  This ultimately results in the first part of the process - sending the GET data asynchronously - working fine, but the second part of the process - putting the response on the page - having no impact.

Link to comment
Share on other sites

Is the browser actually taking you to another page?  Or is your <div id="content"> being filled with what's in cart.php?

Yes... My <div id="content"> is filled with cart.php (this is what I don't want. I want to stay to my curent.php)

 

Can you compare the HTML in body.php that exists after you click the link to what's generated by cart.php?

I think not... My body.php opens inside the <div id="content"> also as all of my links. So as I know is getting replaced by cart.php.

 

Can you see if you're getting any JavaScript errors after you click your link?

Nope... No error with either of the variations of my ajax code.

ajaxpage("cart.php?action=add&id=1", "content")

or

ajaxpage("cart.php?action=add&id=1", "body.php", "content")

 

So is there a way to fix it so it works the right way?

Thank you

Link to comment
Share on other sites

Okay, so it's doing exactly what I thought it was doing.  Good to know.

 

Your best bet is to simply remove (or comment out, which would be better if you need to go back to the way it worked some time in the future) all JavaScript that relates to the loadpage() function, since you simply want to pass info to cart.php without loading a new page.

 

If you don't feel like mucking around with the innards of your JavaScript, simply use a bogus value for the second parameter sent to ajaxpage(), like:

 

ajaxpage("cart.php?action=add&id=1", "null")

Link to comment
Share on other sites

Thank you... 'null' is working..!

 

Something else on the same factions.... If you see my

faction showcart()

you will see these lines:

$output[] = '<td class="tdcart"><a href="javascript:ajaxpage(\'cart.php?action=delete&id='.$id.'\', \'content\');">Remove</a></td>';

$output[] = '<div><button type="submit">Update<img src="../stock_photos/shopcart.png"></button></div>';

 

Both of them "Remove" and "Update" when they were clicked a new page was opening to show the changes in the cart.

For the "Remove" I entered my ajaxpage code and now is showing the changes inside of my <div id=content>.

 

BUT... with the "Update button" whatever I try in order to update the cart inside the <div id=content> I either get a new page or NO update at all.

 

What am I missing here?

 

Thank you

Link to comment
Share on other sites

If your 'Remove' code is the same as the code you just gave me:

 

$output[] = '<td class="tdcart"><a href="javascript:ajaxpage(\'cart.php?action=delete&id='.$id.'\', \'content\');">Remove</a></td>';

 

Then the same problem as before is happening.  The link, when rendered, becomes:

 

<a href="javascript:ajaxpage('cart.php?action=delete&id=someid, 'content');">Remove</a>

 

The output from cart.php is getting placed in your <div id="content">.

 

The reason why it's not happening when you click "Update" is because that's a plain form submission button.  It's not doing anything with ajax.  Rather, it's simply posting the form data to the URL in its action attribute, which in this case is cart.php?action=update.

 

Now, when you say you don't get any update, what do you mean, specifically?  Is the cart data itself not being updated?

Link to comment
Share on other sites

Yes... when I say any update I mean the cart doesn't get updated...

 

BUT.... The "UPDATE" code as I posted it, IT IS working!

 

It doesn't work when I try with different code modifications to achieve "The cart to be updated and stay inside my <div id=content>".

Is there a way for this? (to have the button updating the cart and staying inside my <div id=content>)

 

Thank you

Link to comment
Share on other sites

I think you'll need to change your PHP a bit.  Right now, you're trying to play with both GET and POST simultaneously with your update code.  You don't need to use GET in your case.  Simply make your update button a normal submit input, and give it a name.  Then, you can check to see if it exists on postback and handle the update from there.  Something like:

 

if (isset($_POST['update'])) // we're updating the cart from a normal form submission
{
   // update code
}

 

And your form:

 

<form action="cart.php" method="post">
   <!-- inputs -->
   <input name="update" type="submit" value="Update" />
</form>

 

That said, for any submissions that make a change to stored data (like adding an item, or updating an item), you should be using POST.  That's how their behavior is defined in the HTTP spec, and it makes things easier overall.  GET is for retrieving (getting) data only.  POST is for modifying existing data.

 

Is your ajaxpage() code something you wrote or does it come from someone else?  I ask because you'd be better off using a bit of jQuery to make the cart additions.  You're quickly moving into "round peg in square hole" territory here, both with the ajax and PHP, and I think you're better off in the long run refining your overall design rather than trying to patch things as you go.

Link to comment
Share on other sites

Where exactly do I insert the

if (isset($_POST['update'])) 
{
}

 

Do I have to change all the update code?

 

You'd put the $_POST check in cart.php.  It's replacing action=update.

 

2nd... No ajaxpage is not my code... but the only one I managed to find to open new pages inside curent <div>

 

You can do that (and everything else) a lot easier through jQuery.

 

jQuery GET: http://api.jquery.com/jQuery.get/

jQuery POST: http://api.jquery.com/jQuery.post/

 

As an example, instead of using ajaxpage(), you'd write something like this:

 

$.post("cart.php", { id = 1 }, function(response) {
   /* this function is a callback function, which is executed after the data is sent
      to the PHP script, and it contains the response sent back by the PHP script */
});

Link to comment
Share on other sites

You'd put the $_POST check in cart.php.  It's replacing action=update.

That far I understood :)

 

BUT... Do I replace the update code

	case 'update':
if ($cart) {
	$newcart = '';
	foreach ($_POST as $key=>$value) {
		if (stristr($key,'qty')) {
			$id = str_replace('qty','',$key);
			$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
			$newcart = '';
			foreach ($items as $item) {
				if ($id != $item) {
					if ($newcart != '') {
						$newcart .= ','.$item;
					} else {
						$newcart = $item;
					}
				}
			}
			for ($i=1;$i<=$value;$i++) {
				if ($newcart != '') {
					$newcart .= ','.$id;
				} else {
					$newcart = $id;
				}
			}
		}
	}
}	
$cart = $newcart;
break;
}

with that or i include the code inside that  :confused: as you said before

if (isset($_POST['update'])) // we're updating the cart from a normal form submission{   // update code}

 

Something else I found out today is that my update button as is now, is working under firefox BUT not under ie9!!!! I hope that's not the reason that my efforts to make it work failed... An ie9 bug, stupidity or something!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.