Send html table data & form data without leaving page - javascript

I have to code to do both of these functions, however, when I try to integrate them its either one or the other. (either the email is sent with the name / email & lands on server.php, or the email is sent with the data & none of the inputs are sent). I want to be able to send both the html table data as well as the users name & email inputs. The code below will simply echo the html data or the users inputs.
This code sends data to the server:
Jquery / Html
<script language="javascript" type="text/javascript" src="jQuery.js">
</script>
<script language="javascript" type="text/javascript">
$(function(){
var dataArr = [];
$("table").each(function(){
dataArr.push($(this).html());
});
$('#sendServer').click(function(){
$.ajax({
type : "POST",
url : 'server.php',
data : "content="+dataArr,
success: function(data) {
alert(data);// alert the data from the server
},
error : function() {
}
});
});
});
</script>
<table id="table" border=1>
<thead> <tr>
<th>First</th>
<th>Last</th>
<th>Date of birth</th>
<th>City</th>
</tr></thead>
<tbody>
<tr>
<td>TEXT1</td>
<td>TEXT2</td>
<td>TEXT3</td>
<td>TEXT4</td>
</tr>
<tr>
<td>TEXT5</td>
<td>TEXT6</td>
<td>TEXT7</td>
<td>TEXT8</td>
</tr>
<tr>
<td>TEXT9</td>
<td>TEXT10</td>
<td>TEXT11</td>
<td>TEXT12</td>
</tr>
</tbody>
</table>
<input id="sendServer" name="sendServer" type="button" value="Send to Server" />
Server.php
<?php
echo $_REQUEST['content'];
?>
This form send data using ajax
<div style="padding:3px 2px;border-bottom:1px solid #ccc">Ajax Form</div>
<form id="ff" action="test.php" method="post">
<table>
<tr>
<td>Name:</td>
<td><input name="name" type="text"></input></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" type="text"></input></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="phone" type="text"></input></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input></td>
</tr>
</table>
</form>
The jquery script
$('#ff').form({
success:function(data){
$.messager.alert('Info', data, 'info');
}
});
And the php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
echo "Your Name: $name <br/> Your Email: $email <br/> Your Phone: $phone";
I'm sure that I'm just missing something small. When I implement these into my code, an email is sent. The email contains either the name & email, or the html table data. The difference in code is putting a button action="submit" on my code. Whenever the email sent displays the name & email, the page also redirects to the blank php page. Hopefully I'm being clear enough.
Cheers.

Just add a e.preventDefault(); to your submission javascript inside #sendServer's click handler. This will prevent the form from submitting traditionally like it's doing now.
You'll also need to add the parameter e to that function:
$('#sendServer').click(function(e){
// ajax call
e.preventDefault();
}
Or return false; in the same place as was commented below.

Related

MPGS integration 3DSecure PHP

I've downloaded the Direct Payment Sample_REST-JSON_PHP.zip . I successfully integrated with my merchant info, but when doing the pay operation in x_pay_simple.html I get the following error
{
"error": {
"cause": "INVALID_REQUEST",
"explanation": "Missing parameter. value: null - reason: A 3DS Authentication ID value or 3DS Authentication Details is required for the transaction source used for this transaction",
"field": "3DSecure",
"validationType": "MISSING"
},
"result": "ERROR"
}
I read the docs and I understood that 3DSecure is generated from the gateway, I think add payment & 3Dsecure are done in 1 use case.
how can I add 3DSecure to my implementation ?
Here's the HTML :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>
<link rel="stylesheet" type="text/css" href="./assets/paymentstyle.css" />
<head>
<title>API Example Code</title>
<meta http-equiv="Content-Type" content="text/html, charset=iso-8859-1">
</head>
<body>
<h1>PHP Example - REST (JSON)</h1>
<h3>Simple Pay Operation</h3>
<p>Return to the Home Page</p>
<form action="./process.php" method="post">
<table width="60%" align="center" cellpadding="5" border="0">
<!-- Credit Card Fields -->
<tr class="title">
<td colspan="2" height="25"><P><strong>URL Fields</strong></P></td>
</tr>
<tr>
<td colspan="2" height="25"><P class="desc">Order and Transaction IDs are required and used to calculate the URL along with the version and merchant ID. In your integration, you would calculate these fields within your code (process.php based on this example) and not expose these to the card holder on this page, or pass them as hidden fields.</P></td>
</tr>
<tr class="shade">
<td align="right" width="50%"><strong>version </strong></td>
<td width="50%"><input type="text" readonly="readonly" name="version" value="34" size="8" maxlength="80" /></td>
</tr>
<tr>
<td align="right" width="50%"><strong>order.id</strong></td>
<td><input type="text" name="orderId" value="" size="20" maxlength="60"/></td>
</tr>
<tr class="shade">
<td align="right" width="50%"><strong>transaction.id</strong></td>
<td><input type="text" name="transactionId" value="" size="20" maxlength="60"/></td>
</tr>
<tr><td colspan="2"></td></tr>
<tr class="title">
<td colspan="2" height="25"><P><strong> Transaction Fields</strong></P></td>
</tr>
<tr>
<td align="right" width="50%"><strong>method </strong></td>
<td width="50%"><input type="text" readonly="readonly" name="method" value="PUT" size="20" maxlength="80"/> ** See Note 1 Below</td>
</tr>
<tr class="shade">
<td align="right" width="50%"><strong>apiOperation </strong></td>
<td width="50%"><input type="text" readonly="readonly" name="apiOperation" value="PAY" size="20" maxlength="80"/></td>
</tr>
<tr>
<td align="right"><strong>sourceOfFunds.type </strong></td>
<td><input type="text" name="sourceOfFunds[type]" value="CARD" size="19" maxlength="80"/></td>
</tr>
<tr class="shade">
<td align="right"><strong>sourceOfFunds.provided.card.number </strong></td>
<td><input type="text" name="sourceOfFunds[provided][card][number]" value="" size="19" maxlength="80"/></td>
</tr>
<tr>
<td align="right"><strong>sourceOfFunds.provided.card.expiry.month </strong></td>
<td><input type="text" name="sourceOfFunds[provided][card][expiry][month]" value="" size="1" maxlength="2"/></td>
</tr>
<tr class="shade">
<td align="right"><strong>sourceOfFunds.provided.card.expiry.year </strong></td>
<td><input type="text" name="sourceOfFunds[provided][card][expiry][year]" value="" size="1" maxlength="2"/></td>
</tr>
<tr>
<td align="right"><strong>sourceOfFunds.provided.card.securityCode </strong></td>
<td><input type="text" name="sourceOfFunds[provided][card][securityCode]" value="" size="8" maxlength="4"/></td>
</tr>
<tr class="shade">
<td align="right"><strong>order.amount </strong></td>
<td><input type="text" name="order[amount]" value="" size="8" maxlength="13"/></td>
</tr>
<tr>
<td align="right"><strong>order.currency </strong></td>
<td><input type="text" name="order[currency]" value="SAR" size="8" maxlength="3"/></td>
</tr>
<tr>
<td colspan="2"><center><input type="submit" name="submit" value="Process Payment"/></center></td>
</tr>
<tr><td colspan="2"></td></tr>
<tr>
<td colspan="2" height="25"><P class="desc"><strong>Note 1:</strong> This field is used by this example to set the HTTP Method for sending the transaction. In your integration, you should determine the HTTP Method in your code (process.php based on this example) and never display it to the card holder or pass it as a hidden field.</P></td>
</tr>
</table>
</form>
<br/><br/>
</body>
process.php
<?php
/* Main controller page
1. Create 1 MerchantConfiguration object for each merchant ID
2. Create 1 Parser object
3. Call Parser object FormRequest method to form the request that will be sent to the payment server
4. Parse the formed reqest to SendTransaction method to attempt to send the transaction to the payment server
5. Store the received transaction response in a variable
6. Include receipt page which will output the response HTML and parse the server response
*/
include "configuration.php";
include "connection.php";
// This is used to set the HTTP operation for sending the transaction
// In your integration, you should never pass this in, but set the value here based on your requirements
if (array_key_exists("method", $_POST))
$method = $_POST["method"];
// The following section allows the example code to setup the custom/changing components to the URI
// In your integration, you should never pass these in, but set the values here based on your requirements
$customUri = "";
if (array_key_exists("orderId", $_POST))
$customUri .= "/order/" . $_POST["orderId"];
if (array_key_exists("transactionId", $_POST))
$customUri .= "/transaction/" . $_POST["transactionId"];
// Add any HTML/$_POST field names that you want to unset to this array
// If you have any other fields in the HTTP POST, you need to process them here and remove from $_POST
// After this, $_POST should only contain fields that are being sent as part of the transaction
$unsetNames = array("orderId", "transactionId", "submit", "method");
// loop through each field in the unsetNames array
// unset the field if the key exists
foreach ($unsetNames as $fieldName) {
if (array_key_exists($fieldName, $_POST))
unset($_POST[$fieldName]);
}
// Creates the Merchant Object from config. If you are using multiple merchant ID's,
// you can pass in another configArray each time, instead of using the one from configuration.php
$merchantObj = new Merchant($configArray);
// The Parser object is used to process the response from the gateway and handle the connections
$parserObj = new Parser($merchantObj);
// In your integration, you should never pass this in, but store the value in configuration
// If you wish to use multiple versions, you can set the version as is being done below
if (array_key_exists("version", $_POST)) {
$merchantObj->SetVersion($_POST["version"]);
unset($_POST["version"]);
}
// form transaction request
$request = $parserObj->ParseRequest($_POST);
// if no post received from HTML page (parseRequest returns "" upon receiving an empty $_POST)
if ($request == "")
die();
// print the request pre-send to server if in debug mode
// this is used for debugging only. This would not be used in your integration, as DEBUG should be set to FALSE
if ($merchantObj->GetDebug())
echo $request . "<br/><br/>";
// forms the requestUrl and assigns it to the merchantObj gatewayUrl member
// returns what was assigned to the gatewayUrl member for echoing if in debug mode
$requestUrl = $parserObj->FormRequestUrl($merchantObj, $customUri);
// this is used for debugging only. This would not be used in your integration, as DEBUG should be set to FALSE
if ($merchantObj->GetDebug())
echo $requestUrl . "<br/><br/>";
// attempt sending of transaction
// $response is used in receipt page, do not change variable name
$response = $parserObj->SendTransaction($merchantObj, $request, $method);
// print response received from server if in debug mode
// this is used for debugging only. This would not be used in your integration, as DEBUG should be set to FALSE
if ($merchantObj->GetDebug()) {
// replace the newline chars with html newlines
$response = str_replace("\n", "<br/>", $response);
echo $response . "<br/><br/>";
die();
}
// the receipt page is included and displayed here.
// in your integration, you would most likely also want process the transaction response, and make appropriate updates
// you can see how to parse and retrieve the results and other fields in the transaction at the top of receipt.php
include "receipt.php";
?>
receipt.php
<?php
//Rima - start
include "process.php";
//Rima - end
$errorMessage = "";
$errorCode = "";
$gatewayCode = "";
$result = "";
$tmpArray = array();
// [Snippet] howToDecodeResponse - start
// $response is defined in process.php as the server response
$responseArray = json_decode($response, TRUE);
// [Snippet] howToDecodeResponse - end
// either a HTML error was received
// or response is a curl error
if ($responseArray == NULL) {
print("JSON decode failed. Please review server response (enable debug in config.php).");
die();
}
// [Snippet] howToParseResponse - start
if (array_key_exists("result", $responseArray))
$result = $responseArray["result"];
// [Snippet] howToParseResponse - end
// Form error string if error is triggered
if ($result == "FAIL") {
if (array_key_exists("reason", $responseArray)) {
$tmpArray = $responseArray["reason"];
if (array_key_exists("explanation", $tmpArray)) {
$errorMessage = rawurldecode($tmpArray["explanation"]);
}
else if (array_key_exists("supportCode", $tmpArray)) {
$errorMessage = rawurldecode($tmpArray["supportCode"]);
}
else {
$errorMessage = "Reason unspecified.";
}
if (array_key_exists("code", $tmpArray)) {
$errorCode = "Error (" . $tmpArray["code"] . ")";
}
else {
$errorCode = "Error (UNSPECIFIED)";
}
}
}
else {
if (array_key_exists("response", $responseArray)) {
$tmpArray = $responseArray["response"];
if (array_key_exists("gatewayCode", $tmpArray)){
$gatewayCode = rawurldecode($tmpArray["gatewayCode"]);
}
}
else
$gatewayCode = "Response not received.";
}
}
?>
<!-- The following is a simple HTML page to display the response to the transaction.
This should never be used in your integration -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<link rel="stylesheet" type="text/css" href="assets/paymentstyle.css" />
<head>
<title>API Example Code</title>
<meta http-equiv="Content-Type" content="text/html, charset=iso-8859-1">
</head>
<body>
<br/>
<center><h1>PHP Example - REST (JSON)</h1></center>
<center><h3>Receipt Page</h3></center><br/><br/>
<table width="60%" align="center" cellpadding="5" border="0">
<?php
// echo HTML displaying Error headers if error is found
if ($errorCode != "" || $errorMessage != "") {
?>
<tr class="title">
<td colspan="2" height="25"><P><strong> Error Response</strong></P></td>
</tr>
<tr>
<td align="right" width="50%"><strong><i><?=$errorCode?>: </i></strong></td>
<td width="50%"><?=$errorMessage?></td>
</tr>
<?php
}
else {
?>
<tr class="title">
<td colspan="2" height="25"><P><strong> <?=$gatewayCode?></strong></P></td>
</tr>
<tr>
<td align="right" width="50%"><strong><i>Result: </i></strong></td>
<td width="50%"><?=$result?></td>
</tr>
<?php
}
?>
<!-- Response Fields -->
<tr class="title">
<td colspan="2" height="20"><P><strong> JSON Response</strong></P></td>
</tr>
</table>
<table width="50%" align="center" cellpadding="5" border="0">
<tr>
<td><p>The display of the below response is intended to be for this example only. In your integration, you should parse this response to extract and use the response fields required.</p>
</td>
</tr>
<tr>
<td align="center" width="100%">
<textarea rows="40" cols="118" name="outContent" id="outContent"><?=$response?></textarea>
</td>
</tr>
<!-- The below Java Script & HTML formats the JSON output result to make it clean
and readable. You should not use these scripts to format or expose the
JSON response in your integration, but rather store/use any of the
specific fields required for your integration -->
<tr>
<td align="center" width="100%">
<p>Note: The above response has been formatted to make it easier to read. The reformatting also changes amounts to be strictly defined JSON numbers. This means 0's are removed from after the decimal place i.e. 1.00 is displayed as 1 and 1.10 is displayed as 1.1. Click here to display the unformatted JSON Response</p>
</td>
</tr>
<script type="text/javascript" src="./assets/json2.js"></script>
<script type="text/javascript" src="./assets/jsonformatter.js"></script>
<script type="text/javascript" src="./assets/jquery-1.3.2.js"></script>
<script>
var orginalJSON = $("#outContent").val();
function FormatTextarea() {
var sJSON = $("#outContent").val();
var oJSON = JSON.parse(sJSON);
sJSON = FormatJSON(oJSON);
$("#outContent").val(sJSON);
}
FormatTextarea();
function displayRawJSON() {
$("#outContent").val(orginalJSON);
}
</script>
</table>
<br/><br/>
</body>
</html>
3-D Secure (3DS) is a separate workflow that occurs before the authorization. As a prerequisite, your merchant account needs to support 3DS. During checkout, first you will get the 3DS response. If the card supports 3DS and fails authentication, then you should display an error message to the cardholder. Otherwise, if the 3DS authentication is successful or undetermined, you can proceed to the authorization step.
There is a separate integration document for 3-D Secure Authentication

Email is send on loading of the app script, but email needed to be send onclick

I have created an app script in which email can be send to the login user and to the email Ids which are mentioned in spreadsheet. The email is send to the active user and to all the mentioned email Ids.
However I want email to be send to login user (which is done) and to the specified email Id when selected via app script.
But the mail is send to all the mentioned email IDs in spreadsheet when the app script is getting loaded, whereas the mail should be send onclick, which is not working.
function doGet() {
return HtmlService
.createTemplateFromFile('index')
.evaluate();
}
function getData() {
return SpreadsheetApp
.openById('SS ID')
.getDataRange()
.getValues();
}
function sendMessage(ManagerID,proNo,proName){
var email=Session.getActiveUser().getEmail();
var eId=ManagerID;
var subject="Feedback form initiated" ;
var message="Feedback form initiated by "+eId;
var message2="To fill the feedback form please follow the url: ";
var url="googleform's ID";
var subject2="Feedback Form";
MailApp.sendEmail(eId, subject, message);
MailApp.sendEmail(email,subject2,message2+url);
}
//index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body onload="document.getElementById('one').style.visibility='hidden'">
<div id="initiateFb">
<form>
<? var data = getData(); ?>
<table border='1px solid black'>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<?if(j==(data[i].length-1)&&i!=0) { ?>
<td><input type="submit" name="submit" value="Initiate"
onclick="document.getElementById('initiateFb').style.display = 'none';
document.getElementById('one').style.visibility='visible';
<?var ManagerID=data[i][6];?> <?var proNo=data[i][1];?> <?var proName=data[i][2];?>
document.getElementById('div1').innerHTML='<?=data[i][1] ?>';
document.getElementById('div2').innerHTML='<?=data[i][2] ?>';
document.getElementById('div3').innerHTML='<?=data[i][3] ?>';
document.getElementById('div4').innerHTML='<?=data[i][4] ?>';
document.getElementById('div5').innerHTML='<?=data[i][5] ?>';
document.getElementById('div6').innerHTML='<?=data[i][6] ?>';
document.getElementById('div7').innerHTML='<?=data[i][7] ?>';
document.getElementById('div8').innerHTML='<?=data[i][8] ?>';
document.getElementById('div9').innerHTML='<?=data[i][9] ?>';
return false;"/>
</td>
<? } ?>
<? } ?>
</tr>
<? } ?>
</table>
</form>
</div>
<div id="one">
<form>
<table>
<tr>
<td>ca :</td>
<td id="div1"></td>
</tr>
<tr>
<td>cb :</td>
<td id="div2"></td>
</tr>
<tr>
<td>cc:</td>
<td id="div3"></td>
</tr>
<tr>
<td>cd :</td>
<td id="div4"></td>
</tr>
<tr>
<td>ce:</td>
<td id="div5"></td>
</tr>
<tr>
<td>cf:</td>
<td id="div6"></td>
</tr>
<tr>
<td>cg :</td>
<td id="div7"></td>
</tr>
<tr>
<td>ch :</td>
<td id="div8"></td>
</tr>
<tr>
<td>ci:</td>
<td id="div9"></td>
</tr>
</table>
<input type="submit" name="submit" value="Initiate Feedback" onclick="<?sendMessage(ManagerID,proNo,proName);?>"/>
</form>
</div>
</body>
</html>
I have attached my code.
arturro is correcct in the question comment. To make an asynchronous call you must use
google.script.run.sendMessage(ManagerID,proNo,proName)
However make note that
<input type="submit" name="submit" value="Initiate Feedback" onclick="google.script.run.sendMessage(ManagerID,proNo,proName)"
will not work because you are doing that within the HTML body. You are better of using a javascript code between <script></script> which would fetch the variables you need and then you can use the google.script.run in order to send out the email.
So you would then have
<script>
function sender() {
var ManagerID, proNo, proName;
//use Document.getElementById in order to populate the variables with
//what you need from the form
google.script.run.sendMessage(ManagerID, proNo, proName);
}
</script>
<input type="submit" name="submit" value="Initiate Feedback" onclick="sender()">
The <script></script> part is supposed to be in your index.html as it is a client side script that will handle the calling of the server side script
I have done something similar and it works fine.

Update form using Ajax, PHP, MYSQL

I found a tutorial that auto submits the form data but all I want to do is add a submit button to pass the data to ajax.
My goal is to have a form with multiple inputs and when the user clicks the submit button it sends it through ajax and updates the page without reloading the page. Also, another key piece is the way it post all the inputs into an array so that when the update script is ran the name attributes from the input fields match the columns in the database.
I think I'm close. I've searched and haven't found my exact solution. Thanks in advance.
<script type="text/javascript" src="/js/update.js"></script>
<form method="POST" action="#" id="myform">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
<div id="alert">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event) {
updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
$('#alert').text('Updated');
$('#alert').fadeOut().fadeIn();
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
// FORM: Variables were posted
if (count($_POST))
{
$data=unserialize($_POST['data']);
// Prepare form variables for database
foreach($data as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$column."='".$value."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
Ended up figuring it out. Thanks for everyones help.
<p id="alert"></p>
<form id="form" method="post" action="/ajax/update_company_info.php">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<input type="submit" value="Save" id="submit">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var value = input.val();
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
//var method = form.attr('method');
//var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
$.ajax({
url: "/ajax/update_company_info.php",
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
type: "POST",
success: function(data) {
$('#alert').html("<p>Sent Successfully!</p>");
}
}); // end post
});// end each input value
}); // end submit
}); // end ready
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
function clean($value)
{
return mysql_real_escape_string($value);
}
// FORM: Variables were posted
if (count($_POST))
{
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
I think that you want to update form when submit.so you should
remove submit with a button given below.
<button id="myBtn">Save</button>.
You should add the given below code in ur js file.
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event){
Updateform('give id of the form');
});
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
});
You can retrieve input value in your php code by using unserialize()
as an array.So you can save data to
database and whatever you want to.i hope you get the answer.Hence,your code will become
<form method="POST" action="#" id="form1">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
</td>
<td></td> </tr> </table> <!-- end id-form --> </form>
Your js code become
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event)
{ Updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_company_info.php will become
$data=unserialize($_POST['data']);
// you can retrieve all values from data array and save all .
?>
Instead of:
$(".submit").click(function() {
Give your form a id like 'myform': <form method="POST" action="#" id="myform">
And use this for preventing default submission of form:
$("#myform").submit(function(e) {
e.preventDefault();
//your code
}

Html form is not working with Php, Ajax request

Hello following is my html form which I want to validate with Ajax. So that Browser do not load the page. If user enter First Name, It's should show the first name above the html form. But It doesn't showing...
Html form:
<form id="validation"/>
<table width="500" border="0" cellspacing="10" cellpadding="0">
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="<?php if(isset($_POST['fname'])) echo $_POST['fname']; ?>" class="tr" placeholder="First Name"/></td>
</tr>
<tr>
<td></td>
<td><input type="reset" name="reset" value="Clear" class="submit"/> <input type="submit" name="Submit" id="submit" value="Registration" class="submit"/></td>
</tr>
</table>
</form>
<script>
$('#validation').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'regProcess.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
}
});
});
</script>
Php code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Registration"){
$fname = $_POST['fname'];
echo $fname;
}
?>
Near the bottom of your code, you have this:
success: function (data) {
}
That's your problem. You're not doing anything with the returned "data" - you need to use javascript or jquery to insert it into the DOM somewhere.
EDIT: UPDATE
To use jquery to insert the data into the dom, do something like this:
success: function (data) {
$("#id of the element where you want the data").innerHTML+=data
}
That will append the "data" retrieved from the AJAX into the element with the specific ID. You can use any CSS selector inside the $("HERE") I believe.

How do I get a form populated using ajax and codeigniter

I am trying to teach myself code igniter and mvc. I have a working site in php that allows the input of an isbn number and returns the title, rank etc. I use ajax to get the information from amazon and then put it into the existing form. This works great, now i am trying to convert it to code igniter. My view is buybackmws.php and looks like this:
<?php echo validation_errors();?>
<?php echo form_open('buyback', $title);?>
<table height="220">
<tr>
<td><label>ISBN</label></td>
<td><input type="text" id="isbn" name="isbn" value="<?php echo set_value('isbn'); ?>" /></td>
<td></td>
<td rowspan=7><a id="detailURL" href="#" target="_blank"><img id="bookCover" src="<?php echo base_url();?>images/imgNotFound.gif" height="200px" /></a></td>
</tr>
<tr>
<td><label for="quantity" class="label">Quantity</label></td>
<td><input type="text" id="quantity" name="quantity" value="<?php echo set_value('quantity'); ?>"/></td>
<td></td>
</tr>
<tr>
<td><label for="payPrice" class="label">Price to Pay</label></td>
<td><input type="text" id="payPrice" name="payPrice"/></td>
<td></td>
</tr>
<tr>
<td><label>Edition</label></td>
<td><input type="text" id="edition" name="edition" readonly="readonly"/></td>
<td></td>
</tr>
<tr>
<td><label>Title</label></td>
<td><input type="text" id="title" name="title"/></td>
<td></td>
</tr>
<tr>
<td><label>Sales Rank</label></td>
<td><input type="text" id="salesRank" name="salesRank" readonly="readonly" /></td>
<td></td>
</tr>
<tr>
<td></td><td><input type="button" id="buy" value="Buy" /></td><td></td>
</table>
<?php echo form_close() ?>
my js with the ajax is buybackmws.js:
$('#isbn').keydown(function () {
//retrieve price to pay (and other data)
var isbn = $('#isbn').val();
$('#quantity').val('0'); //default quantity to 0
$('#buy').attr('disabled', false).css('backgroundColor', '');
$('#quantity').css('border', '');
$('#payPrice').css('border', '');
$('#payPrice').css('backgroundColor', '');
$('#payPrice').css('color', '');
$.ajax({
type: "POST",
url: ' ../verifybuyback/title',
async:false,
dataType: "json",
data: ({isbn: isbn }),
success: function(data){
console.log(data);
$('#title').val(data.title);
$('#salesRank').val(data.salesRank);
$('#edition').val(data.edition);
$('#binding').val(data.binding);
$("#detailURL").attr("href",data.DetailURL);
} //end of success
});
verifybuyback is:
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Verifybuyback extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('amz','',TRUE);
$this->load->helper('amazon');
}
function title()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('isbn', 'ISBN','trim|required|xss_clean|callback_title_check' );
if($this->form_validation->run('title')==FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('buybackmws');
}
else
{
//GOTO RESTRICTED AREAS
redirect('buybackmws', 'refresh');
}
}
function title_check()
{
//Field validation succeeded. Validate against database
$isbn=$this->input->post('isbn');
//QUERY AMAZON FOR THE INFORMATION
$result = basic($isbn);
if($this->session->userdata('amazon'))
{
$sess_array = array();
$result=$this->session->userdata('amazon');
$sess_array=array(
'title'=>$result['Title'],
'rank'=>$result['SalesRank'],
);
}
else
{
$this->form_validation->set_message('get_title', 'Invalid ISBN number');
return false;
}
}
} //END OF BUYBACK
When I test it, and look at what is shown in the response tab, the information is there. My console.log is not doing anything so i don't think the information is being returned to the js. I am therefore having an issue getting everything into the view. How do I do this?
EDIT: I got the console.log in the ajax success to show the results in Firebug, but they are still not populating the form. Any ideas??
you are using datatype json for ajax . Remove json datatype and use
$data['view'] = $this->load->view($view, $this->data, true);
$this->output->set_output($data);
you can now access data.view in ajax
OR
with json in datatype
Use
$data['view'] = $this->load->view($view, $this->data, true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
Also if you redirect in controller from ajax it will not work for page . you need to redirect in ajax after success return data

Categories

Resources