PHP - Submit Form Using Ajax
I have a form on my website and when the user submits it I want all the server processing to be done using AJAX so the page doesn't refresh. I was wondering what the best way to do this is because if your form has a submit button doesn't that automatically refresh the page?
Thanks for any help. Similar TutorialsHi Guys, I'm struggling with a submit form via ajax. This is the code, but I've been looking for about 3 hours and cannot work out why it doesnt submit the form... Any ideas? <script type="application/javascript"> function addForm() { $.ajax({type:'POST', url: 'cart.php?ajax=1&a=add&domain=register', data:$('#add-form').serialize(), success: function(response) { $('#add-form').find('.form_result').html(response); }}); return false; } function transferForm() { $.ajax({type:'POST', url: 'cart.php?ajax=1&a=add&domain=transfer', data:$('#transfer-form').serialize(), success: function(response) { $('#transfer-form').find('.form_result').html(response); }}); return false; } </script>My code is mixed with smarty but the call is just a standard call {foreach from=$availabilityresults key=num item=result} {if $result.status eq "available"} <form method="post" id="add-form" onsubmit="return addForm();"> {else} <form method="post" id="transfer-form" onsubmit="return transferForm();"> {/if} <table width="700" border="0" cellspacing="5" cellpadding="0"> <input type="hidden" name="domain" value="{$result.domain}" /> <tr style="border-bottom: #333 1px solid;"> <td rowspan="2">{if $result.status eq "available"}<img src="templates/dj/yes.jpg" />{else}<img src="templates/dj/no.jpg" />{/if}</td> {if $result.status eq "available"}<td style="color:#339933;" />{$result.domain|replace:$domain:''}</td>{else}<td style="color:#cc0000;" />{$result.domain|replace:$domain:''}</td>{/if} <td rowspan="2">{$result.domain}</td> <td rowspan="2">{if $result.status eq "unavailable"}{else} <select name="domainsregperiod[{$result.domain}]"> {foreach key=period item=regoption from=$result.regoptions} <option value="{$period}">{$period} {$LANG.orderyears} @ {$regoption.register}</option> {/foreach} </select> {/if}</td> <td rowspan="2">{if $result.status eq "available"} <input type="image" src="templates/dj/add-basket.jpg" border="0" alt="Add to Basket" /><div class="form_result"> Added to Basket </div> {else} <input type="image" src="templates/dj/transfer.jpg" border="0" alt="Transfer to Us" /> {/if}</td> </tr> <tr> <td>{if $result.status eq "available"}Available{else}Taken{/if}</td> </tr> <tr><td colspan="8" style="height:1px; background-color:#999;"></td></tr> </table> </form> {/foreach} Hi,
I'm a novice and have the below code in a Wordpress theme. I'm trying to get the form to submit automatically so it logs an entry into the MySql db as though the person clicked the heart icon (submit). Ideally I subsequently want to hide the heart icon so on load maybe after 3 seconds the entry is auto fired to the MySql DB.
I have got as far as the manual click adding the entry, however can't get to to auto submit, any gel would be appreciated. Thank you in advance.
////PHP Form/////
<form class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST"> here my sample code <form> <input id="query" type="text" name="query" placeholder="search here..." autocomplete="off"> <button type="submit" value="query" >search</button> <div class="sugbx"></div> </form> //php code, assume we already run a whole php code ...... <ul class="list-group list-unstyled" style="cursor:pointer; color: #191919; position:absolute; top:12px;"> <?php foreach($query as $movie) { ?> <li class="list-group-item" onClick="searchValue('<?php echo $movie["movie_name"]; ?>'),;"><?php echo $movie["movie_name"]; ?></li> <?php } ?> </ul> <?php } ?> //ajax here $('#search').keyup(function(){ $.ajax({ type: 'GET', url: 'phpcode.php', data:'query='+$(this).val(), success: function(data){ $('.sugbx').show(); $('.sugbx').html(data); } }); }); function searchValue(val) { $('#query').val(val); $('.sugbx').hide(); } //ajax the input accept the value only after selecting one of the listed value on the suggesstion box and then i have to click the submit button the problem is, how to submit the value accepted when a list is clicked Say I have an "Entries" table. I want to submit same multiple entries using a form submission. And If I have other queries submitted in the same form, I want those quarries to be submitted only once. Is that possible to do? Here's my code. if(isset($_POST['submit'])) { $entries = 10; $id = 55; $name = 'Smith'; $insert = $db->prepare("INSERT INTO entries(id, name) VALUES(:id, :name)"); $insert->bindParam(':id', $id); $insert->bindParam(':name', $name); $result_insert = $insert->execute(); if($result_insert == false) { echo 'Fail'; } else { echo 'Success'; } } ?> <form action="" method="post"> <input type="submit" name="submit" value="SUBMIT" /> </form> Edited January 13, 2019 by imgrooot Hi. Pretty straight forward I guess but as the name suggests am a newbie. I have a form that requires the user to enter certain parameters. If the values are blank it submits to itself and loads the error messages. What I want to do is create PHP code that submits the form to a different url. What I thought was create two forms (the second with hidden fields replicating the first form), each form having a different url in the action"" code. What I cant work out is the PHP IF ELSE code to submit form 2 if Form1 is is validated correctly. This is the PHP code relevant to the form validation. Help? <?php //If form was submitted if ($_POST['submitted']==1) { $errormsg = ""; //Initialize errors if ($_POST[width]){ $title = $_POST[width]; //If title was entered } else{ $errormsg = "Please enter width"; } if ($_POST[drop]){ $textentry = $_POST[drop]; //If comment was entered } else{ if ($errormsg){ //If there is already an error, add next error $errormsg = $errormsg . " & content"; }else{ $errormsg = "Please enter drop"; } } } if ($errormsg){ //If any errors display them echo "<div class=\"box red\">$errormsg</div>"; } //If all fields present if ($title && $textentry){ //Do something echo 'THIS IS WHERE I WANT THE CODE TO SUBMIT FORM 2 or SUBMIT FORM 1 TO A DIFFERENT URL'; } ?> This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=326913.0 Hello, first time poster.. I've looked the web over for a long time and can't figure this one out. - Below is basic code that successfully checks MySQL for a match and displays result. I was debugging and forced the "height" and "width" to be 24 and 36 to make sure that wasn't the problem. That's good.. - I'd like to give the user ability to select width and height from a form.. and have it do an onchange this.form.submit so the form can be changing as fields are altered (thus the onchange interaction) - In a normal coding environment I've done this numerous times with no "Page cannot be displayed" problems. It would simply change one select-option value at a time til they get down the form and click submit... but in WordPress I'm having trouble making even ONE single onchange work! - I've implemented the plugins they offer which allows you to "copy+paste" your php code directly into their wysiwyg editor. That works with basic tests like my first bullet point above. - I've copied and pasted the wordpress url (including the little ?page_id=123) into the form "action" url... that didn't work... tried forcing it into an <option value=""> tag.. didn't work. I'm just not sure. I've obviously put xx's in place of private info.. Why does this form give me Page Cannot Be Displayed in WordPress every time? It won't do anything no matter how simple.. using onchange.. Code.. $con = mysql_connect("xxxx.xxxxxxx.com","xxxxxx","xxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("xxxxxx", $con); $myprodwidth=24; $myprodheight=36; $result = mysql_query("SELECT * FROM product_sizes WHERE prodwidth='$myprodwidth' and prodheight='$myprodheight'"); while($row = mysql_fetch_array($result)) { echo $row['prodprice']; } mysql_close($con); <form method="post" action=""> <select name="myheight" onchange="this.form.submit();"> <option selected="selected" value="">select height</option> <option value="xxxxxxxxx.com/wordpress/?page_id=199&height=36">36</option> <option value="xxxxxxxxx.com/wordpress/?page_id=199&height=36">48</option> </select> Hi- the code below lets me upload a CSV file to my database if I have 1 field in my database and 1 column in my CSV. I need to add to my db "player_id" from the CVS file and "event_name" and "event_type" from the form... any ideas??? here's the code: Code: [Select] <?php $hoststring =""; $database = ""; $username = ""; $password = ""; $makeconnection = mysql_pconnect($hoststring, $username, $password); ?> <?php ob_start(); mysql_select_db($database, $makeconnection); $sql_get_players=" SELECT * FROM tabel ORDER BY player_id ASC"; // $get_players = mysql_query($sql_get_players, $makeconnection) or die(mysql_error()); $row_get_players = mysql_fetch_assoc($get_players); // $message = null; $allowed_extensions = array('csv'); $upload_path = '.'; //same directory if (!empty($_FILES['file'])) { if ($_FILES['file']['error'] == 0) { // check extension $file = explode(".", $_FILES['file']['name']); $extension = array_pop($file); if (in_array($extension, $allowed_extensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) { if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) { $keys = array(); $out = array(); $insert = array(); $line = 1; while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { foreach($row as $key => $value) { if ($line === 1) { $keys[$key] = $value; } else { $out[$line][$key] = $value; } } $line++; } fclose($handle); if (!empty($keys) && !empty($out)) { $db = new PDO( 'mysql:host=host;dbname=db', 'user', 'pw'); $db->exec("SET CHARACTER SET utf8"); foreach($out as $key => $value) { $sql = "INSERT INTO `table` (`"; $sql .= implode("`player_id`", $keys); $sql .= "`) VALUES ("; $sql .= implode(", ", array_fill(0, count($keys), "?")); $sql .= ")"; $statement = $db->prepare($sql); $statement->execute($value); } $message = '<span>File has been uploaded successfully</span>'; } } } } else { $message = '<span>Only .csv file format is allowed</span>'; } } else { $message = '<span>There was a problem with your file</span>'; } } ob_flush();?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>CSV File Upload</title> </head> <body> <form class="form" action="" method="post" enctype="multipart/form-data"> <h3>Select Your File</h3> <p><?php echo $message; ?></p> <input type="file" name="file" id="file" size="30" /> <br/> <label>Event Name:</label><input name="event_name" type="text" value="" /> <br/> <label>Event Type:</label><input name="event_type" type="text" value="" /> <br/> <input type="submit" id="btn" class="button" value="Submit" /> </form> <br/> <h3>Results:</h3> <?php do { ?> <p><?php echo $row_get_players['player_id'];?></p> <?php } while ($row_get_players = mysql_fetch_assoc($get_players)); ?> </body> </html> Hi all, What I am trying to achieve is, I thought quite simple! Basically, a user signs up and chooses a package, form is submitted, details added to the database, email sent to customer, then I want to direct them to a paypal payment screen, this is where I am having issues! Is their any way in php to submit a form without user interaction? Here is my code for the form process page Code: [Select] <?php include('config.php'); require('scripts/class.phpmailer.php'); $package = $_POST['select1']; $name = $_POST['name']; $email = $_POST['email']; $password = md5($_POST['password']); $domain = $_POST['domain']; $a_username = $_POST['a_username']; $a_password = $_POST['a_password']; $query=mysql_query("INSERT INTO orders (package, name, email, password, domain, a_username, a_password) VALUES ('$package', '$name', '$email', '$password', '$domain', '$a_username', '$a_password')"); if (!$query) { echo "fail<br>"; echo mysql_error(); } else { $id = mysql_insert_id(); $query1=mysql_query("INSERT INTO customers (id, name, email, password) values ('$id', '$name', '$email', '$password')"); if (!$query1) { echo "fail<br>"; echo mysql_error(); } if($package=="Reseller Hosting") { //email stuff here - all works - just cutting it to keep the code short if(!$mail->Send()) { echo "Message could not be sent. <p>"; echo "Mailer Error: " . $mail->ErrorInfo; exit; } ?> <form name="_xclick" action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick-subscriptions"> <input type="hidden" name="business" value="subscription@jollyhosting.com"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="item_name" value="Jolly Hosting Reseller Packages"> <input type="hidden" name="no_shipping" value="1"> <!--1st month --> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="a3" value="3.00"> <input type="hidden" name="p3" value="1"> <input type="hidden" name="t3" value="M"> <input type="hidden" name="src" value="1"> <input type="hidden" name="sra" value="1"> </form>'; <?php } //last } //end ?> Ok I have been trying to get learn ajax and php contact forms for a few days now and I can't seem to get my head around why mine refuses to work. I know the form and the php does what it is suppost to do but I can't understand why when i link the whole thing together it doesn't work. As it sits at the moment its just sticking on the loading part of the ajax and refuses to execute the validate in the php file. Can anyone please point me in the right direction? index.php (the form) Code: [Select] <div id="contact_wrapper"> <div id="contact_form"> <script src="js/ajax.form.js" language="javascript"></script> <form action="javascript:contact_form()" method="post"> <h1 class='contact_form_h' id='contact-loading'>Contact Us</h1> <div id="login_response"></div> <input type='text' name='name' id='name' class='contact_form_input' value='Name' onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;" /> <input type='text' name='email' id='email' class='contact_form_input' value='Email' onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;" /> <textarea name='enquiry' id='enquiry' class='contact_form_textarea' rows='10' cols='10' onfocus="if(!this._haschanged){this.value=''};this._haschanged=true;">Enquiry</textarea> <input type='submit' name='contact' id='contact' class='contact_form_submit' value='Contact Us' /> </form> </div> </div> ajax.form.js (Ajax) Code: [Select] /* ---------------------------- */ /* XMLHTTPRequest Enable */ /* ---------------------------- */ function createObject() { var request_type; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer"){ request_type = new ActiveXObject("Microsoft.XMLHTTP"); }else{ request_type = new XMLHttpRequest(); } return request_type; } var http = createObject(); /* -------------------------- */ /* Contact */ /* -------------------------- */ /* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */ var nocache = 0; function contact_form() { // Optional: Show a waiting message in the layer with ID ajax_response document.getElementById('contact_wrapper').innerHTML = "<div id='contact_error'><img src='img/loader.gif' alt='loading' /> Loading...</div>" // Required: verify that all fileds are not empty. Use encodeURI() to solve some issues about character encoding. var name = encodeURI(document.getElementById('name').value); var email = encodeURI(document.getElementById('email').value); var enquiry = encodeURI(document.getElementById('enquiry').value); // Set the random number to add to URL request nocache = Math.random(); // Pass the form variables like URL variable http.open('get', 'send_email.php?name='+name+'&email='+email+'&enquiry='+enquiry+'&nocache = '+nocache); http.onreadystatechange = Reply; http.send(null); } function Reply() { if(http.readyState == 4){ var response = http.responseText; if(response == 1){ // if fields are empty document.getElementById('login_response').innerHTML = 'Please fill in all the fields.'; } else if(response == 2){ // if email isnt valid document.getElementById('login_response').innerHTML = 'Please enter a valid email address.'; } else if(response == 3){ // if email has been sent document.getElementById('login_response').innerHTML = 'Your email has been sent.'; } else if(response == 10){ // if email hasnt been sent document.getElementById('login_response').innerHTML = 'Your email has not been sent.'; } } } send_email.php (php) Code: [Select] <?php //Require check email function require "check_email.php"; //Variables $err_name=stripslashes($_GET['name']); $err_email=stripslashes($_GET['email']); $err_enquiry=stripslashes($_GET['enquiry']); $to="xxx@xxxxxxxxxx.com"; $subject="Website Contact Form"; $from = stripslashes($_GET['name'])."<".stripslashes($_GET['email']).">"; $message = $err_enquiry; $headers = "From: $from\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; //Check all form fields are filled in if ($_GET["name"]!='' && $_GET["name"]!='Name' && $_GET["email"]!='' && $_GET["email"]!='Email' && $_GET["enquiry"]!='' && $_GET["enquiry"]!='Enquiry') { //Check email address is valid if (isValidEmail($_GET['email'])){ //Send Mail if (@mail($to, $subject, $message, $headers)) { echo "3"; } else{ echo "10"; } } //Email isnt valid else{ echo"2"; } } else { echo"1"; } ?> So basically I am attempting to make my code work with AJAX also to get rid of the page refreshing to the user. It does physically submit the data to the file and write it how it is supposed to be. However the notifications are not working at all. I am not the best at bug shooting JS stuff as I don't use it a lot - but would be grateful if someone can point out where I am going wrong.
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="HandheldFriendly" content="true" /> <link rel="stylesheet" type="text/css" href="css/default.css" /> <script src="scripts/jquery-1.11.1.min.js"></script> <script> $(document).ready(function() { $('#formContainer').submit(function() { var formData = $(this).serialize(); $.post('index.php', formData, processData); function processData(data) { if (data=='1') { $('.form').html('<p>success</p>'); } else if (data=='2') { $('#form').prepend('<p>already exists</p>'); } else if (data=='3') { $('#form').prepend('<p>fail</p>'); } } return false; }); }); </script> <title>WyTraining</title> </head> <body class="background"> <header> <div class="logo"><a href="index.php"><img src="images/logo.png" alt="wyTraining"></a></div> </header> <div class="form"> <div class="title">coming soon</div> <?php /* email entered = 1 */ /* email exists = 2 */ /* email incorrect = 3 */ if($_SERVER['REQUEST_METHOD'] == 'POST') { $trimmed = array_map('trim', $_POST); if(filter_var($trimmed['email'], FILTER_VALIDATE_EMAIL)) { $file = 'data\emails.txt'; if( strpos(file_get_contents($file),$trimmed['email']) == false) { $email = $trimmed['email']; echo '1'; $current = file_get_contents($file); $current .= "$email,\n"; file_put_contents($file, $current); } else { echo '2'; } } else { echo '3'; } } ?> <center><form action="index.php" method="POST" id="formContainer"> <input type="text" name="email" value="" placeholder="enter email to stay updated" autocomplete="off"/> <input type="submit" name="submit" value=" " class="button"/> </form></center> </div> </body> </html> Hi All, I am trying to get this contact form to work correctly. The problem I have right now is that the e-mail sends only the Name, Email Address, and Phone Number, and it will not send anything for the body or "message" portion. The first code is contact.php Code: [Select] <?php /* Credits: Bit Repository URL: http://www.bitrepository.com/ */ include 'contact_config.php'; session_start(); error_reporting (E_ALL ^ E_NOTICE); $post = (!empty($_POST)) ? true : false; if($post) { include 'functions.php'; $name = stripslashes($_POST['name']); $email = trim($_POST['email']); $phone = stripslashes($_POST['phone']); $subject = stripslashes($_POST['subject']); $message = "Site visitor information: Name: ".$_POST['name'] ." E-mail Address: ".$_POST['email'] ." Phone: ".$_POST['phone'] ." Message: ".$_POST['message']; $error = ''; // Check name if(!$name) { $error .= 'Please enter your First name.<br />'; } // Check email if(!$email) { $error .= 'Please enter an e-mail address.<br />'; } if($email && !ValidateEmail($email)) { $error .= 'Please enter a valid e-mail address.<br />'; } if(isset($_SESSION['captcha_keystring']) && strtolower($_SESSION['captcha_keystring']) != strtolower($_POST['capthca'])) { $error .= "Incorect captcha.<br />"; } if(!$error) { $mail = mail(WEBMASTER_EMAIL, $subject, $message, "From: ".$name." <".$email.">\r\n" ."Reply-To: ".$email."\r\n" ."X-Mailer: PHP/" . phpversion()); if($mail) { echo 'OK'; } } else { echo '<div class="notification_error">'.$error.'</div>'; } } ?> and contact_config.php only contain the webmaster's email address. Thank you for your help. Hey Guys, I've got a section of code that generates a date and time. This is currently standalone however I'm looking to integrate it with a standard page. This is the code page: <?php error_reporting(0); include("options.php"); include("include/functions.php"); include("include/class.php"); list($year,$month,$day) = explode("-",date("Y-n-j",strtotime($_REQUEST["date"]))); $bookFrom = formatDateByCalendarId($day,$month,$year,$_REQUEST["cid"]); $sql = "SELECT * FROM ".$TABLES["Calendars"]." WHERE id=".$_REQUEST["cid"]; $sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql); $Calendar = mysql_fetch_assoc($sql_result); $CalendarOptions = unserialize($Calendar["options"]); $fontFamily = $Fonts[$CalendarOptions["fonts"]]; $daysFontSize = $FontSize[$CalendarOptions["daysFontSize"]]; $daysFontStyle = $Styles[$CalendarOptions["daysFontStyle"]]; $availableDaysFontSize = $FontSize[$CalendarOptions["availableDaysFontSize"]]; $availableDaysFontStyle = $Styles[$CalendarOptions["availableDaysFontStyle"]]; $timeSlot=new Timeslot($_REQUEST["cid"]); $reservations=$timeSlot->getFreeFilter($CalendarOptions["startTime"],$CalendarOptions["endTime"],$year,$month,$day,$CalendarOptions["timeSlot"]); if (!isset($_REQUEST["view"])) { $view = '1'; } else { $view = $_REQUEST["view"]; }; if ($_REQUEST["ac"]=='book') { $message =''; $format = GetCalendarDateFormat($_REQUEST["cid"]); $sYear = GetYear($format,$_REQUEST["startDate"]); $sMonth = GetMonth($format,$_REQUEST["startDate"]); $sDay = GetDay($format,$_REQUEST["startDate"]); $reservations=$timeSlot->getFreeFilter($CalendarOptions["startTime"],$CalendarOptions["endTime"],$sYear,$sMonth,$sDay,$CalendarOptions["timeSlot"]); $sDateLong = strtotime($CalendarOptions["startTime"],mktime(0,0,0,$sMonth,$sDay,$sYear)); $first=-1; $last=-1; for ($i=0;$i<count($reservations);$i++) { if (($_REQUEST[$i]=="on")&&((($reservations[$i]>0)&&($reservations[$i]==$_REQUEST["rid"]))||(!$reservations[$i]))) { if ($first<0) $first=$i; $last=$i; } } $eDateLong = strtotime("+".($CalendarOptions["timeSlot"]*($last+1))." minutes",$sDateLong); $sDateLong= strtotime("+".($CalendarOptions["timeSlot"]*$first)." minutes",$sDateLong); if($_REQUEST["rid"]>0) { $updateRange = $_REQUEST["rid"]; } else $updateRange = NULL; if(! $timeSlot->checkInterval($sDateLong,$eDateLong,$updateRange)){ $message = "Some of the timeslots on the selected date are already booked."; } else { $settings["status"]=$CalendarOptions["reservationStatus"]; $settings["notes"]=mysql_escape_string(utf8_encode($_REQUEST["notes"])); $settings["customerName"]=mysql_escape_string(utf8_encode($_REQUEST["customerName"])); $settings["phone"]=mysql_escape_string(utf8_encode($_REQUEST["phone"])); $settings["email"]=mysql_escape_string(utf8_encode($_REQUEST["email"])); $settings["price"]=$_REQUEST["price"]; if (! isset($updateRange)) $settings["dt"]=date("Y-m-d H:i:s"); if (! $timeSlot->addReservation($sDateLong,$eDateLong,$settings,$updateRange)) $message = 'Failed saving'; else { if($_REQUEST["findReservation"]=="1") $_REQUEST["ac"]='findReservation'; else $_REQUEST["ac"]='view'; $_REQUEST["month"] = $sMonth*1; $_REQUEST["year"] = $sYear; $search_tokens=array("<Name>","<Email>","<Phone>","<Notes>","<Date>","<StartTime>","<EndTime>","<Price>"); $replace_tokens=array($_REQUEST["customerName"],$_REQUEST["email"],$_REQUEST["phone"],stripslashes($_REQUEST["notes"]),$_REQUEST["startDate"],formatTime($sDateLong,$_REQUEST["cid"]),formatTime($eDateLong,$_REQUEST["cid"]),$_REQUEST["price"]); $MESSAGE_BODY=$CalendarOptions["emailMessage"]; $MESSAGE_BODY=nl2br(str_replace($search_tokens,$replace_tokens,$MESSAGE_BODY)); $mailheader = "From: ".$CalendarOptions["NotificationEmail"]."\r\n"; $mailheader .= "Reply-To: ".$CalendarOptions["NotificationEmail"]."\r\n"; $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; if ($CalendarOptions["NotificationEmail"]<>'') { if(!mail($CalendarOptions["NotificationEmail"], 'Reservation Confirmation', $MESSAGE_BODY, $mailheader)) $message="Failure sending e-mails.<br />"; }; if ($_REQUEST["email"]<>'') { if (!mail($_REQUEST["email"], 'Reservation Confirmation', $MESSAGE_BODY, $mailheader)) $message="Failure sending e-mails.<br />"; }; if($CalendarOptions["allowPaypal"]=="true" and $CalendarOptions["paypalAddress"]<>"" and $CalendarOptions["depositPayment"]>0 and isset($_REQUEST["price"]) and $_REQUEST["price"]>0){ $price = $_REQUEST["price"]; $deposit = $price * ($CalendarOptions["depositPayment"] / 100); $_REQUEST["ac"] = "redirectToPaypal"; } else { unset($_REQUEST["ac"]); } $message.='Reservation saved.'; } } } echo '<div style="font-family:'.$fontFamily.'; color:#'.$CalendarOptions["availableDaysFontColor"].'; font-size:'.$availableDaysFontSize.'px; font-weight:bold">'.$message.'</div>'; if($_REQUEST["ac"]=="redirectToPaypal"){ } else { ?> <?php if(isset($_REQUEST["date"])){ ?> <form action="load-bookingform.php" method="post" name="frm" style="margin:0px; padding:0px" onsubmit="return false"> <table width="<?php echo $CalendarOptions["width"]; ?>" border="0" cellspacing="0" cellpadding="2" style='font-family:"<?php echo $fontFamily; ?>"; color:#<?php echo $CalendarOptions["availableDaysFontColor"]; ?>; font-size:<?php echo $availableDaysFontSize; ?>px; <?php echo $availableDaysFontStyle; ?>'> <tr> <td width="16%" align="left">Date:</td> <td width="85%" align="left" name="startDate" id="startDate"><strong><?php echo $bookFrom; ?></strong></td> </tr> <?php $price = 0; ?> <tr> <td colspan="2"> <table width="100%" border="0" cellspacing="2" cellpadding="2"> <tr> <td width="33%" valign="top" bgcolor="#DDDDDD">Start time</td> <td width="33%" valign="top" bgcolor="#DDDDDD">End time</td> <td colspan="2" valign="top" bgcolor="#DDDDDD">Book </td> </tr> <?php for ($i=0;$i<count($reservations);$i++) { ?> <tr> <td align="left" style="border-bottom:1px solid #DFE4E8"><?php if ($CalendarOptions["timeFormat"]=='12') echo date("h:i A",strtotime("+".($CalendarOptions["timeSlot"]*$i)." minutes",strtotime($CalendarOptions["startTime"]))); else echo date("H:i",strtotime("+".($CalendarOptions["timeSlot"]*$i)." minutes",strtotime($CalendarOptions["startTime"]))); ?></td> <td align="left" style="border-bottom:1px solid #DFE4E8"><?php if ($CalendarOptions["timeFormat"]=='12') echo date("h:i A",strtotime("+".($CalendarOptions["timeSlot"]*($i+1))." minutes",strtotime($CalendarOptions["startTime"]))); else echo date("H:i",strtotime("+".($CalendarOptions["timeSlot"]*($i+1))." minutes",strtotime($CalendarOptions["startTime"]))); ?></td> <td width="34%" align="left" valign="top" style="border-bottom:1px solid #DFE4E8"><input type="checkbox" id="<?php echo $i; ?>" name="<?php echo $i; ?>" <?php if ($reservations[$i]) { echo "checked"; echo ' disabled="disabled"'; } ?> onclick="selectTimeSlot()" /></td> </tr> <?php }; ?> </table> </td> </tr> <tr> <td align="left"> </td> <td align="left"> <input type="button" name="Button" value="Book" onclick="pass=checkForm(); if (pass) submitBooking('<?php echo $bookFrom; ?>','<?php echo date("n",strtotime($_REQUEST["date"])); ?>','<?php echo date("Y",strtotime($_REQUEST["date"])); ?>')" /> <input type="button" name="Button" value="Cancel" onclick="javascript: ajaxpage('<?php echo $SETTINGS["installFolder"]; ?>load-bookingform.php?cid=<?php echo $_REQUEST["cid"]; ?>','DateBookings<?php echo $_REQUEST["cid"]; ?>','get'); " /> </td> </tr> <?php } ?> </table> </form> <?php }; ?> I already have a checkout page, that this info needs to be parsed to. Any ideas how I can integrate it? I want to perform a php process initiated by AJAX according to the method described in http://www.w3schools.com/PHP/php_ajax_database.asp with this line Code: [Select] xmlhttp.open("GET","getuser.php?q="+str,true); the php process in getuser.php is initiated. But how I can restrict direct access to getuser.php? If someone visit getuser.php?q=something; the process will be started for "something". I want to run the getuser.php process only and only when it is initiated from my main page. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=342898.0 Hi, This is my first post in this forum and am a PHP beginner. I have written a script in php and need to use echo to see the values of variables etc. However I dont get the output on the screen while using echo . I am using Xampp server with Apache. The startup.html file code is
<!DOCTYPE HTML>
</head>
and the test.php code is <?php
$lat = $_REQUEST['latitude'];
echo 'latitude- '.$lat . ', longitude- ' . $lon; Please help regards
Sanjish The Business Logic is: If product is already purchased, upgrade the product I have a customer input form to get information, along with some fields which should be auto populated based on what the customer chooses. Screen Shot:
https://i.stack.imgur.com/Fkyim.png When we come to the shipping cost I am getting it from Magento, using a PHP function. form :
https://paste.ofcode.org/335FVUhpBGbazQtrcPLVQUs sp_cost.php
https://paste.ofcode.org/hvG2sP9TW9CEPgMMuKXNuw $results = getShippingEstimate('14419','1',"IN","642001"); How can i get country and zipcode from the user entry and return the shipping cost?
Edited April 26, 2019 by aveeva Hello forum,
So I've been developing an app mostly in PHP, but am rather afraid of JS. Hope to fix that.
I have an AJAX dropdown using JQuery to search locations. It works great. However, I want to make it similar to what is seen on this site:
http://placefinder.com/
As you can see, the dropdown, when clicked populates a box. Then the user submits the form and the data is used in the application.
I have no clue how to make the form populate with data from the DB (I'm using mySQL) when clicked. So far, I've only been able to make it clickable as a URL (not what I want, obvioiusly!)
Is there a way to do this on a really small, simple script for starters? I'm certain their is, but don't even know where to begin.
Any help appreciated
/*I'm trying to use dropzone js plugin for drag/drop single phote but it require me to create another form for file upload, but i want to use single form for both image and name input, i have no idea on how to combine this field in sinle request, the form to submit both image and name look like*/ <form method="POST" enctype="multipart/form-data"> <input type="text" name="name" id="name"> <!--how to replace this field with dropzone but in this form in order to use the same ajax as below--> <input type="file" name="photo" id="photo"> <button type="submit">send</button> </form> //ajax, how to add dropzone data in $("form").on('submit', function(e) { $.ajax({ url: 'add.php', type: 'POST', data: new FormData(this), dataType: 'JSON', contentType: false, cache: false, processData:false, }).done( function (data) { if(data.success == false) { //for error message response if(data.errors.name) { $('#name').append('<span class="text-danger">' + data.errors.name + '</span>'); } if(data.errors.photo) { $('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>'); } } }); e.preventDefault(); });
When I click on the letter of the alphabet on my form page, it will bring up the results of my query. I got this part working. The next part is to be able to click on any of the populated results and have it autofill my form with organization, first name, last name, email address and phone number.
I know that I need to use Ajax and jQuery to accomplish this.
Here is my html
<!-- Letter Search --> <div class="searchBox span12"> <h3>Choose the First Letter of the Person's Last Name</h3> <ul> <li class="alphabets" id="A"><a href="?by=A">A</a></li> <li class="alphabets" id="B"><a href="?by=B">B</a></li> <li class="alphabets" id="C"><a href="?by=C">C</a></li> <li class="alphabets" id="D"><a href="?by=D">D</a></li> <li class="alphabets" id="E"><a href="?by=E">E</a></li> <li class="alphabets" id="F"><a href="?by=F">F</a></li> <li class="alphabets" id="G"><a href="?by=G">G</a></li> <li class="alphabets" id="H"><a href="?by=H">H</a></li> <li class="alphabets" id="I"><a href="?by=I">I</a></li> <li class="alphabets" id="J"><a href="?by=J">J</a></li> <li class="alphabets" id="K"><a href="?by=K">K</a></li> <li class="alphabets" id="L"><a href="?by=L">L</a></li> <li class="alphabets" id="M"><a href="?by=M">M</a></li> <li class="alphabets" id="N"><a href="?by=N">N</a></li> <li class="alphabets" id="O"><a href="?by=O">O</a></li> <li class="alphabets" id="P"><a href="?by=P">P</a></li> <li class="alphabets" id="Q"><a href="?by=Q">Q</a></li> <li class="alphabets" id="R"><a href="?by=R">R</a></li> <li class="alphabets" id="S"><a href="?by=S">S</a></li> <li class="alphabets" id="T"><a href="?by=T">T</a></li> <li class="alphabets" id="U"><a href="?by=U">U</a></li> <li class="alphabets" id="V"><a href="?by=V">V</a></li> <li class="alphabets" id="W"><a href="?by=W">W</a></li> <li class="alphabets" id="X"><a href="?by=X">X</a></li> <li class="alphabets" id="Y"><a href="?by=Y">Y</a></li> <li class="alphabets" id="Z"><a href="?by=Z">Z</a></li> </ul> <? include('search.php'); ?> </div> <hr style="color:#ccc; margin-bottom:20px;" /> <!-- Main Form --> <div id="mainForm"> <form method="post" id="icsForm" class="searchBox span12"> <div id="col1" class"span6"> <h3>Contact Information</h3> <label>Church / Organization:</label><input type="text" name="organization" id="organization" class="span6 upright" /><br /> <label>First Name:</label><input type="text" name="firstName" id="firstName" class="span6 upright" /> <label>Last Name:</label><input type="text" name="lastName" id="lastName" class="span6 left upright" /> <label>Email Address:</label><input type="text" name="email" id="email" class="span6 left upright" /> <label>Phone Number:</label><input type="text" name="phone" id="phone" class="span6 left upright" /> </div> </div>Here is my php if(preg_match("/^[A-Z | a-z]+/", $_POST['name'])){ $name=$_POST['name']; } if(isset($_GET['by'])){ $letter=$_GET['by']; //query to sort by last name $sql="SELECT contact_id, first_name, last_name, church_org, email_address, phone_number FROM ics_data WHERE last_name LIKE '$letter%' ORDER BY last_name ASC"; //run the query against the mysql query function $result=mysql_query($sql); //count results $numrows=mysql_num_rows($result); echo "<p>" .$numrows . " results found for " . $letter . "</p>"; //Create while loop and loop through result set while($row=mysql_fetch_array($result)){ $first_name=$row['first_name']; $last_name=$row['last_name']; $church_org=$row['church_org']; $email_address=$row['email_address']; $phone_number=$row['phone_number']; $contact_id=$row['contact_id']; //display the result of the array echo "<div id=\"search-results\">"; echo "<ul class=\"letter-results\">\n"; echo "<li class=\"result-row\">" . "<a href=\"#\" class=\"testclass\">" .$first_name . " " .$last_name . "". ", " ."" .$church_org ."</a></li>\n"; echo "</ul>"; echo "</div>"; } }Here is my Javascript file (Ajax) $(document).ready( function() { function formfill() { var organization = $('#organization').val(); var firstname = $('#firstname').val(); var lastname = $('#lastname').val(); var email = $('#email').val(); var phone = $('#phone').val(); $.ajax ({ method: "GET", url: "search.php", dataType: 'json', data: { organization:organization, firstname:firstname, lastname:lastname, email:email, phone:phone }, type: "POST", success: function(data) { $organization $firstname $lastname $email $phone }, failu function() { alert('fail!'); } }); }I know that I do not have a reference yet to JSON in my php file and that it is needed. I'm not solid on the Ajax part. That is the part that is tripping me up. I know that I need to make the form autofill when clicking on a specific result returned from my query... but i'm not sure how to do that. Thank you in advance for any help or advice you can give!! I am relatively new to programming. Hopefully I posted this in the right forum as a lot of these technologies overlap. Edited by kjetterman, 26 September 2014 - 10:23 AM. |