runnerjp
asked on
AJAX submit
at the moment im using AJAX tabs , but im using classic nonAJAX form actions. i have been told that for my script to work properly so that forms an be processed under each tab that i need to have it completely AJAX. so how can i chnage the code below so that it carries out the submittion to the db via ajax
<?php error_reporting(E_ALL);
session_start();
require_once '../../../settings.php';
include "../../../info.php"; // sets username/id ect
$getuser = mysql_fetch_assoc(mysql_query("SELECT * from users where Username='$username'"));
$getuserprofile = mysql_fetch_assoc(mysql_query("SELECT * from profile where ID='" .
$getuser['ID'] . "'"));
?>
<html>
<head>
<title></title>
</head>
<body>
<?
if(isset($_POST['submitted']))
{
foreach($_POST as $field => $value) {
if (($field != 'submit') && ((!$value) || (trim($value) == ''))) {
$err .= "$field cannot be empty. <br>";
$warnings[$field] ="required";
}
}
if (!$_POST["about_me"] || !preg_match("/^[a-zA-Z ]+$/", $_POST["about_me"])) {
$warnings["about_me"] = " <label for=\"uname\" class=\"error\"><em>*</em>please only user words</label>";
}
$count = count($warnings);
}
if($count === 0)
{
if(array_key_exists('submit', $_POST))
{
$about_me = mysql_real_escape_string($_POST['about_me']);
$update = "UPDATE profile SET about_me = '$about_me' WHERE ID='$id' ";
echo $update;
$result = mysql_query($update);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$er = 'Invalid query: ' . mysql_error() . "\n";
$er .= 'Whole query: ' . $query;
die($er);
}}
echo ' <p class="error">' . $message . '</p>' . "\n";
}
if ($err){?>
<div class="errors">
<p align="center"><em>Oops... the following errors were encountered:</em></p>
<div align="center"><?php echo $err; ?> </div>
<p align="center"> </p>
<p align="center">Data has <strong>not</strong> been saved.</p>
</div>
<p>
<?php } ?>
<fieldset>
<legend>About me</legend>
<div class="c1">
<p> </p>
<form action='members/include/profiletab/hobbies.php' method="post" name="submit">
<p><em><strong>Tell everybody a little bit about yourself...</strong></em></p>
<p>
<textarea <? if (count($warnings) > 0){ if ($warnings['about_me']) echo "class=\"inputerror\""; }?> onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="about_me" rows="7" wrap="physical" cols="60">
<?php echo $getuserprofile['about_me']; ?><?php if (count($warnings) > 0){ echo $warnings["about_me"];} ?>
</textarea>
<br />
<br />
You have <b><span id="myCounter">1000</span></b> characters remaining</p>
<input type="hidden" name="submitted" value="1" />
<input name="submit" type="submit" value="Submit" />
</form>
</div>
</fieldset>
</body>
</html>
ASKER
ok ...how would u validate the code? so say only a certian number of char could be used?? could i still use php?
Yes you can validate in two ways:
- With Javascript, the traditional way, with a validation script which prevents submitting the form before all the fields have been filled appropriately.
- With PHP, by adding code in the PHP page to verify each field for unallowed characters, too many chars, etc; while it does not prevent submitting the data, it would return the error message in the DIV instead of a message that the data has been saved successfully.
Below there's a simple example of validation with PHP after submit, using the PHP field of the demo I provided above.
Try the demo again and leave a field blank and submit to see it in action.
http://www.aleixcortadellas.com/demos/ajaxpost/index.html
Regards
- With Javascript, the traditional way, with a validation script which prevents submitting the form before all the fields have been filled appropriately.
- With PHP, by adding code in the PHP page to verify each field for unallowed characters, too many chars, etc; while it does not prevent submitting the data, it would return the error message in the DIV instead of a message that the data has been saved successfully.
Below there's a simple example of validation with PHP after submit, using the PHP field of the demo I provided above.
Try the demo again and leave a field blank and submit to see it in action.
http://www.aleixcortadellas.com/demos/ajaxpost/index.html
Regards
<?php
if($_POST['name'] != ''){
if($_POST['email'] != ''){
echo '<br /><p style="font-weight: bold;">Data received successfully!</p>';
echo 'Your name is <span style="font-weight: bold;">' . $_POST['name'] . '</span><br />';
echo 'Your e-mail address is <span style="font-weight: bold;">' . $_POST['email'] . '</span><br /><br />';
$str = "You submitted the form on %a, %b %d, %Y, %X - Time zone: %Z";
echo(gmstrftime($str,time()));
} else {
echo '<br /><p style="font-weight: bold; color: red;">Please fill in the email field</p>';
}
} else {
echo '<br /><p style="font-weight: bold; color: red;">Please fill in the name field</p>';
}
?>
Javascript validation of maximum length of a text field:
http://www.rgagnon.com/jsdetails/js-0091.html
http://www.rgagnon.com/jsdetails/js-0091.html
ASKER
so php will still submit the data but show error message BUT javascript will stop the form being submitted
Exactly.
ASKER
ok i chnage the ajax code so i can have a textbox... but now it wont show me the $_POST['about_me']
below is the code,,,,
below is the code,,,,
<?php
require_once 'settings.php';
include "info.php"; // sets username/id ect
include "getuser.php"; // records user view on page
$getuser = mysql_fetch_assoc(mysql_query("SELECT * from users where Username='Admin'"));
$getuserprofile = mysql_fetch_assoc(mysql_query("SELECT * from profile where ID='1'"));
$your_date = $getuserprofile['dob'];
$splitDate = explode("-", $your_date);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>AJAX Post form demo</title>
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = 'Processing...';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
} else {
alert('XmlHttpRequest error!');
}
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "text":
str += fobj.elements[i].name +
"=" + escape(fobj.elements[i].value) + "&";
break;
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
</head>
<body style="text-align: center;">
<div id="wrapper" style="position: relative; top: 50px;"><form id="aForm">
Please insert data in the fields below for trying the demo. Submitted data needn't be real; it is not stored anyway.
<br /><br />
<label for="name" style="font-weight: bold;">
<div align="center">About me</div>
</label>
<textarea onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')" name="about_me" rows="7" id="about_me" wrap="physical" cols="60">
<?php echo $getuserprofile['about_me']; ?>
</textarea>
<br /><br />
<input type="button" name="Send" value="OK" onclick="javascript: formget(this.form, 'do.php');">
</form>
<br /><br />****** SERVER RESPONSE ******<br /><br /><br />
<div id="output" style="color: blue;">
</div>
</div>
</body>
</html>
Because Textarea is not an element type recognized in the GetFormValues() function in the code above.
Do the following:
Add, after line 100 of the code above (so between the case "text" and the case "select-one" blocks)
case "textarea": str += fobj.elements[i].name + "=" + escape(fobj.elements[i].va lue) + "&"; break;
This will also retrieve text areas in the form.
Retrieve the value normally with:
echo $_POST['about_me'];
Regards
Do the following:
Add, after line 100 of the code above (so between the case "text" and the case "select-one" blocks)
case "textarea": str += fobj.elements[i].name + "=" + escape(fobj.elements[i].va
This will also retrieve text areas in the form.
Retrieve the value normally with:
echo $_POST['about_me'];
Regards
ASKER
ok that works lol sorry to be really annoying but i added that char limit from that website yet it doent work lol
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring (0, limitNum);
}
<textarea onKeyDown="limitText(this, 20);" onKeyUp="limitText(this,20 );" name="about_me" rows="7" id="about_me" wrap="physical" cols="60">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring
}
<textarea onKeyDown="limitText(this,
<?php
require_once 'settings.php';
include "info.php"; // sets username/id ect
include "getuser.php"; // records user view on page
$getuser = mysql_fetch_assoc(mysql_query("SELECT * from users where Username='Admin'"));
$getuserprofile = mysql_fetch_assoc(mysql_query("SELECT * from profile where ID='1'"));
$your_date = $getuserprofile['dob'];
$splitDate = explode("-", $your_date);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>AJAX Post form demo</title>
<script type="text/javascript">
<!--
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
var divid = 'output';
var loadingmessage = 'Processing...';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
} else {
alert('XmlHttpRequest error!');
}
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "text":
str += fobj.elements[i].name +
"=" + escape(fobj.elements[i].value) + "&";
break;
case "textarea":
str += fobj.elements[i].name +
"=" + escape(fobj.elements[i].value) + "&";
break;
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
</head>
<body style="text-align: center;">
<div id="wrapper" style="position: relative; top: 50px;"><form id="aForm">
Please insert data in the fields below for trying the demo. Submitted data needn't be real; it is not stored anyway.
<br /><br />
<label for="name" style="font-weight: bold;">
<div align="center">About me</div>
</label>
<textarea onKeyDown="limitText(this,20);" onKeyUp="limitText(this,20);" name="about_me" rows="7" id="about_me" wrap="physical" cols="60">
<?php echo $getuserprofile['about_me']; ?>
</textarea>
<br /><br />
<input type="button" name="Send" value="OK" onclick="javascript: formget(this.form, 'do.php');">
</form>
<br /><br />****** SERVER RESPONSE ******<br /><br /><br />
<div id="output" style="color: blue;">
</div>
</div>
</body>
</html>
There's a missing } in line 25. See if this is causing the problem.
ASKER
well thats perfect lol... so now i can use php on the do page to add it to the db :)...
i think i will chnage all my forms to this as its much neater! but that means 1 thing lol i use drop downm menus... would this still work?
i think i will chnage all my forms to this as its much neater! but that means 1 thing lol i use drop downm menus... would this still work?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok 1 more quick question lol
would the below code be ok or would i have to use if submit or something liek a normal form?
would the below code be ok or would i have to use if submit or something liek a normal form?
<?php require_once 'settings.php';
$about_me = mysql_real_escape_string($_POST['about_me']);
$update = "UPDATE profile SET about_me = '$about_me' WHERE ID='$id' ";
echo $update;
$result = mysql_query($update);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$er = 'Invalid query: ' . mysql_error() . "\n";
$er .= 'Whole query: ' . $query;
die($er);
}
$str = "You submitted the form on %a on %b %d, %Y, %X - Time zone: %Z";
echo(gmstrftime($str,time()));
?>
Took a quick glance to it and looks good. In principle you needn't add anything else for it to work (as you could see in the example, there was nothing like if submit). But if you want of course - and it would be a good idea . you can add some function to check that a form has been submitted; or actually that variables are being passed through POST; so to avoid people accessing directly the PHP page by just typing it in their browsers. I don't know what the consequences of this would be, I guess it depends on the code of the file.
ASKER
hey i have slight problem ..u still there too help me out?
Yep. If it's related with the post above post here, if not open a new question and will try to help as well.
Regards
Regards
ASKER
well what i have done is addit into my tabs.. shown here www.runningprofiles.com/test2.php but it keeps saying the error XmlHttpRequest error!
It works to me. I can open the first two tabs and seems it does it with the AJAX code.
The other tabs stay at "requesting content..." perhaps you didn't finish them yet?
At no point got a XMLHTTPREQUEST ERROR. Consider trying your website from another browser to see if error persists to you or it is just your computer's browser.
Tested it successfully both from Mozilla Firefox 3 and IE 7.
The other tabs stay at "requesting content..." perhaps you didn't finish them yet?
At no point got a XMLHTTPREQUEST ERROR. Consider trying your website from another browser to see if error persists to you or it is just your computer's browser.
Tested it successfully both from Mozilla Firefox 3 and IE 7.
ASKER
sorry it works in that link but if you sign in and try it it gives XMLHTTPREQUEST ERROR its the exact same code lol which is wierd... www.runningprrofiles.com username:dmeo password:demo
then go to edit profile button on left then it does it
then go to edit profile button on left then it does it
ASKER
sorry username:demo password:demo
indeed weird; still works to me after logging in; furthermore now all tabs work...
No idea what the problem could be but as for now I can only think it's something related with your browser. What browser you're trying it with?
No idea what the problem could be but as for now I can only think it's something related with your browser. What browser you're trying it with?
ASKER
im using Mozilla Firefox 3 ... i fixed the tabs as i waited lol
ASKER
this is what im seeing"
test.jpg
test.jpg
I really have no idea what is causing the problem then. It would be nice to know if other people experience it too; can someone else test it as well?
ASKER
yup got someone else to test it on firefox and also happend
Ok add the following debug line in your AJAX xmlhttpobject code:
alert(xmlHttp.status);
Should look like the snippet below:
Check what value it returns (should be different than '200')
List of value meanings for status property:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
alert(xmlHttp.status);
Should look like the snippet below:
Check what value it returns (should be different than '200')
List of value meanings for status property:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
} else {
alert('XmlHttpRequest error!');
}
Forgot saying, insert the debug line right after line 7 from the code snippet above
ASKER
i got 404 error :S what has it not found though lol
Never came through such error with AJAX, yet. I'd say it didn't find the file to load, but that is indeed strange because to me everything seemed to load normally...
ASKER
lol this is very strange :S... on both computers it does not seem to work though... yet works on my test page of it :S
ASKER
what shall i do?? would you like me to send u all the code involveD
To be honest I have no idea of what the problem might be. if you want you can attach a zip for me with the files and code; and will take a look at it, but can't guarantee I'll be able to fix it.
ASKER
thnaks here is everything invloled apart form functions and setting ..
wont allow me to add it here but just follow this link for it www.runningprofiles.com/web.zip
wont allow me to add it here but just follow this link for it www.runningprofiles.com/web.zip
Got it. Right now I'm a bit busy but I will write here again when I've looked at it.
ASKER
thankyou so much :) bit of a puzzle...
Hello again,
Tried to test the site but there are includes missing; settings, header, main, etc. so I could not manage to run it locally.
I just had a crazy idea, give it a try.
Change this:
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById(di vid).inner HTML=xmlHt tp.respons eText;
} else {
alert('XmlHttpRequest error!');
}
To this:
if (xmlHttp.readyState == 4) {
document.getElementById(di vid).inner HTML=xmlHt tp.respons eText;
}
It is really strange that to you and your colleague, a 404 appears but to me a 200. Try removing the status check and see what happens. Let me know....
Tried to test the site but there are includes missing; settings, header, main, etc. so I could not manage to run it locally.
I just had a crazy idea, give it a try.
Change this:
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById(di
} else {
alert('XmlHttpRequest error!');
}
To this:
if (xmlHttp.readyState == 4) {
document.getElementById(di
}
It is really strange that to you and your colleague, a 404 appears but to me a 200. Try removing the status check and see what happens. Let me know....
ASKER
wahoo it works now lol what did it do :)
not sure what it did... apart from solving the problem.... :)
Seriously, it ignores the status. As long as the page exists and its route correct, there should be no problem (i hope ^^)
Seriously, it ignores the status. As long as the page exists and its route correct, there should be no problem (i hope ^^)
ASKER
could you check my post https://www.experts-exchange.com/questions/24206429/turning-this-php-form-to-work-in-ajax.html ... i belive u would really be able to help lol
Just wrote a post on how to submit a form using AJAX.
http://www.aleixcortadellas.com/main/2009/03/01/ajax-post/
In the PHP file mentioned, you may place the PHP code for saving the data into the database, as you would do for a normal form sending the data through POST to a PHP script.
There's a simple demo here:
http://www.aleixcortadellas.com/demos/ajaxpost/index.html
I hope this helps.
Regards