Jump to content

Recommended Posts

Hello all,

Everybody said I have to go with ajax, so here I am :) I don't know much about AJAX so... any help will be welcomed.

 

I am trying to update my cart without refreshing my page.

 

For updading my quantity I use:

<form name="upd_itm" id="upd_itm" action="cart.functions.php" method="post">
<span class="text">
<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" style="text-align: center;"/>
<br />
<button name="adjustBtn' . $item_id . '" id="adjustBtn' . $item_id . '" type="submit" class="avoid_ref" value=""><img src="bttn_pics/change_value.png" /></button>
<input name="item_to_adjust" id="item_to_adjust" type="hidden" value="' . $item_id . '" />
</span>
</form>

and a similar code to delete item from cart. It is working but only if I refresh the page I get to see the results.

 

Any hint or script example on how I can modify it in order to work?

 

I tried to understand and use this, but with no luck (I don't even know if this is correct):

var request = $.ajax({
var keyValues = {
    pid : $(this).parent().find('input[name="pid"]').val(),
    item_to_adjust : $(this).parent().find('input[name="item_to_adjust"]').val(),
    index_to_remove : $(this).parent().find('input[name="index_to_remove"]').val(),
    recycleCart : $(this).parent().find('input[name="recycleCart"]').val()
};
    url: 'cart_functions.php',
    data: 'keyValues',
    type: 'post',
    dataType: 'html'
});

request.success(function(response, textStatus, jqXHR) {
    // in here, response is what was returned by PHP
    return false;
});

request.error(function(jqXHR, textStatus, errorThrown) {
    // in here, you can get detailed information on why the request would have failed
});

 

Thank you in advance

Here's an example.  It includes 3 files:

 

js/formprocessing.js

01ajax_process.php

01ajax_process.php

 

Hope this helps.  Set this example up on your server.  Play around with it until you understand how it works.  This doesn't include a database but the idea is the same.

 

Below is the HTML form page:

 

<html>
<head>
<title>Form Posts with Ajax</title>
<script type="text/javascript" src="js/formprocessing.js"></script>
</head>
<body>
<form>
    Top: 
    <input name="sortorder" type="radio" value="top">
    Bottom: 
    <input name="sortorder" type="radio" value="bottom"><br>
    Text One*: 
    <input type="text" name="textOne" title="required"><br>
    Text Two: 
    <input type="text" name="textTwo" title="required"><br>
    
    <select name="mySelect">
    <option value="selectedOne">Select One</option>
    <option value="selectedTwo">Select Two</option>
    </select><br>
    
    
    <input type="button" value=" go " onClick="sendRequest(this.form, '01ajax_process.php')">
</form>
<div id="results" />

</body>
</html>

 

Below is the js/formprocessing.js file:

 

// JavaScript Document
//////////////////////////////////////////////////////////////////////
///// DO NOT CHANGE BELOW /////////////////////////////////////////////
var req = createXMLHttpRequest();                                  ////    
													        	///
function createXMLHttpRequest() {                               	/// 
	var ua;                                                     	/// 
	if(window.XMLHttpRequest) {                                 	///
		try {                                                   	///
  			ua = new XMLHttpRequest();								///
		} catch(e) { 												///
  			ua = false;												///
		}															///
	} else if(window.ActiveXObject) {								///
  		try {														///
		ua = new ActiveXObject("Microsoft.XMLHTTP");			///
  		} catch(e) {												///
		ua = false;												///
  		}															///
	}																///
return ua;														///
}																	///	
																///
function sendRequest(frm, file) {									///
	var rnd982g = Math.random();									///
	var str = "";													///
	if(str = getForm(frm)) {										///
  		req.open('GET', file+'?'+str+'&rnd982g='+rnd982g);			///
  		req.onreadystatechange = handleResponse;					///
  		req.send(null);												///
	}																///
	return false;													///
}																	///
																///
function handleResponse() {											///
	if(req.readyState == 4) {										///				
  		var response = req.responseText;							///	
  		document.getElementById("results").innerHTML = response;	///
	}																///
}																   ////
///// DO NOT CHANGE ABOVE /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
function getForm(fobj) {
 var str = "";
 var ft = "";
 var fv = "";
 var fn = "";
 var els = "";
 for(var i = 0;i < fobj.elements.length;i++) {
  	els = fobj.elements[i];
  	ft = els.title;
  	fv = els.value;
  	fn = els.name;

 	switch(els.type) {
  		case "text":
			if(fn == "email") {
				if(fv != "") {
					var filter=/^.+@.+\..{2,3}$/;
					if (!filter.test(fv)) {
						alert("Please input a valid email address!");
						testresults=false;
						els.select();
						return false;				
					}
				}
			}	
			if (fn == "date1" || fn == "date2") {
				if(fv != "") {
					re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; 
					if(regs = fv.match(re)) {   
						if(regs[1] < 1 || regs[1] > 12) { 
							alert("Invalid value for day: " + regs[1]); 
							els.select(); 
							return false; 
						} 
						if(regs[2] < 1 || regs[2] > 31) { 
							alert("Invalid value for month: " + regs[2]); 
							els.select(); 
							return false; 
						} 
						if(regs[3] < 1959 || regs[3] > (new Date()).getFullYear() + 1) {
							var maxyear = new Date().getFullYear() + 1;
							alert("Invalid value for year: " + regs[3] + " - must be between 1959 and " + maxyear); 
							els.select(); 
							return false; 
						} 
					} else { 
						alert("Invalid " + fn + " format: " + fv + "  (mm/dd/yyyy)"); 
						els.select(); 
						return false; 
					}
				}
			}
  		case "hidden":
  		case "password":
  		case "textarea":
			// is it a required field?
			if(encodeURI(ft) == "required" && encodeURI(fv).length < 1) {
				alert('\''+fn+'\' is a required field, please complete.');
				els.focus();
				return false;
			}
			str += fn + "=" + encodeURI(fv) + "&";
		break; 

		case "checkbox":
		case "radio":
			if(els.checked) str += fn + "=" + encodeURI(fv) + "&";
		break;	

		case "select-one":
			str += fn + "=" +
			els.options[els.selectedIndex].value + "&";
		break;
  	} // switch		
 } // for
 str = str.substr(0,(str.length - 1));
 return str;
}

 

Below is the 01ajax_process.php file:

 

<?php
if(isset($_GET['rnd982g'])) {
foreach($_GET as $fieldname => $value) {
	if($fieldname == "rnd982g") {
		// ignore this random number
		// only used to prevent browser caching
	} else {
		if ($fieldname == "sortorder") { $sortorder = stripslashes(htmlentities($value)); }
		if ($fieldname == "textOne") { $textOne = stripslashes(htmlentities($value)); }
		if ($fieldname == "textTwo") { $textTwo = stripslashes(htmlentities($value)); }
		if ($fieldname == "email") { $email = stripslashes(htmlentities($value)); }
		if ($fieldname == "date1") { $date1 = stripslashes(htmlentities($value)); }
		if ($fieldname == "date2") { $date2 = stripslashes(htmlentities($value)); }
		if ($fieldname == "mySelect") { $mySelect = stripslashes(htmlentities($value)); }
	}
}
echo "sortorder($sortorder)<br>";
echo "textOne($textOne)<br>";
echo "textTwo($textTwo)<br>";
echo "email($email)<br>";
echo "date1($date1)<br>";
echo "date2($date2)<br>";
echo "mySelect($mySelect)<br>";
}
?>

Hello,

 

Thank you for the example. I cannot test it right now, but I am reading it in order to understand the most of it. What you say "DO NOT CHANGE" I didn't understand much, especially from the first half, but at the end I think it's checking the str if it's null or not and displays it.

 

AS for the js/formprocessing.js I get the most of it since is validating the form objects. What I cannot understand what exactly it says/does is:

str = str.substr(0,(str.length - 1));

 

From 01ajax_process.php there is nothing really to understand since the whole script is straight forward. Correct?

 

Now since I cannot test it, I cannot see if it's working without refreshing the page :)

Is it the part that I didn't quite understand that does the trick???

 

So to start also understand on how I should change my code:

1. You are replacing my <form action="cart_functions.php">

with onClick="sendRequest(this.form, '01ajax_process.php'). Are these two way different or either one is ok? Do they behave different?

 

2. My file cart_functions.php will replace 01ajax_process.php. Right?

 

And most important:

3... The js/formprocessing.js I have to find the right way to modified it and include it in my scripts in order to get what I want. Correct?

In there you are telling to str to be displayed inside a <div>. My cart will be already displayed when I will be calling this JS file. Should I assign it to use the current <div> by just replacing the div's name in your code or do I have to change something else as well?

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.