I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article
Related
I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}
If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.
So I have an array of default values in a php array the file (backend.php) has multiple functions and acts. I want to target just the array with the act="default". I need to take the the encoded json php array and populate and html form with it.
html page - frontend.html
<html>
<head>
</head>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name:
<input id="name" type ="text" name="name"></input>
<br><br>
Postal Code:
<input id="postal" type ="text" name="postal"></input>
<br><br>
Phone Number:
<input id="phone" type ="text" name="phone"></input>
<br><br>
Address:
<input id="address" type ="text" name="address"></input>
<br><br>
<input type="submit"></input>
</form>
<div id= "content"></div>
Refresh
<a id="InsertDefault" href="#">Insert Default Data</a>
<br><br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
php page - backend.php
<?php
if ($_REQUEST['act'] == 'default'){
$defaultData = array(
'name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street"
);
echo json_encode($defaultData);
}
else if...
?>
main.js page (errors here)
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$(document).ready(function(){
$('#content').load('backend.php', {'default':'defaultData'}, //this format
function (){ $('#content').html('these are the default values')}
);
// prevents link click default behaviour
defaultData.preventDefault();
return false;
});
$("#PersonForm").submit(function()
{
// Clear any success or error messages
$("#success").html("");
$("#errors").empty();
// make an AJAX call here, and set error or success accordingly
// prevents submit button default behaviour
return false;
});
});
Instead of using .load it would be better to use $.ajax or $.post since $.load will set the content of the selected returned data (which should be either text or HTML). In your case you want to return json so that you can set the form element values.
$(document).ready(function()
{
$("#InsertDefault").click(function(e)
{
// prevents link click default behaviour
e.preventDefault();
// make an AJAX call here, and place results into the form
$.ajax({
url: 'backend.php',
type: 'post',
data: {
act:'default'
},
dataType: 'json',
success: function(data) {
// set the form values
$('[name=name]').val(data.name);
$('[name=postal]').val(data.postal);
$('[name=phone]').val(data.phone);
$('[name=address]').val(data.address);
// display message
$('#content').html('Fields filled in with default values');
},
error: function() {
// handle your error
console.log('error');
}
});
return false;
});
$("#PersonForm").submit(function()
{
// Clear any success or error messages
$("#success").html("");
$("#errors").empty();
// make an AJAX call here, and set error or success accordingly
// prevents submit button default behaviour
return false;
});
});
Since your AJAX call is expecting json return you need to use header('Content-Type: application/json'); in your php script to set the data type.
It's also a good idea to use output buffering (see ob_start() and ob_clean() below) so that any notices outputted by php do not dirty the json your AJAX call is expecting.
ob_start();
if (isset($_POST['act']))
{
if ($_POST['act'] == 'default')
{
ob_clean();
header('Content-Type: application/json');
$defaultData = array(
'name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street"
);
echo json_encode($defaultData);
exit();
}
}
I am trying to use jQuery to trigger a form submission and then use AJAX to call a PHP script that will handle the file and return a response. The issue, though, is that the file is not being uploaded upon submitting the form.
HTML:
<div id="browseButton" class="step1Button" onclick="browseFile()">Browse</div>
<form method="post" id="fileForm" style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<input id="submitForm" type="submit" style="display: none"/>
</form>
<div id="previewButton" class="step1Button pull-right" onclick="uploadFile()" style="background-color: #57a957">
Preview
</div>
jQuery:
function uploadFile() {
submitForm();
parseExcel();
}
var submitForm = function() {
$('#previewButton').click(function(){
$('#submitForm').click();
});
};
var parseExcel = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",'default/ParseExcel',true);
xmlhttp.send();
console.log("made it past excel parse");
};
The PHP that's called:
public function actionParseExcel() {
print "made it to parse".PHP_EOL;
print "File:";
if($_FILES['FileInput']['tmp_name']) {
print_r($_FILES['FileInput']['tmp_name']);
}
else {
print "Not found";
}
print "Done.";
}
I know the issue is that my form isn't submitting the chosen file because that's typically why the "Undefined index" error is thrown. But I can't understand why.
First, if you don't want your page to refresh, you better use <input type="button">
or else call your JavaScript via <form onSubmit="uploadFile()"> and return false at the end of your function uploadFile().
Second, you'll need to put enctype="multipart/form-data" in your <form>.
I see you're using JQuery, you should use it to send your AJAX request too :
// This code supports multiple type="file" inputs
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Create a formdata object and add the file
var data = new FormData();
// In case you want to upload more than one file
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'your.php?FileInput',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Prevent the file from beeing converted to string
contentType: false, // Set the content file to false prevent JQuery from using 'application/x-www-form-urlencoded; charset=UTF-8' as default type
...
});
I hope this will lead you to the solution...
Edited : var files declaration + files processing
To send forms with files you need to use enctype="multipart/form-data".
BUT, as far as I know, you can't send files using ajax.
So, the solution for that is to use a hidden iFrame:
Create a hidden iFrame (outside of your form) and assing it an ID
Create the form pointing to yout PHP file, and using the attribute enctype="multipart/form-data" and target="ID_OF_THE_IFRAME" (so the form, when submitted, will be sent to that iframe)
When the PHP finish procesing the file, you could output a javascript that calls parent.YOURFUNCTION(), so you can do whatever you want when the process is done.
Good luck!
Would anyone happen to know how to receive a usb serial output from a device and send it to an html textbox using jQuery? I understand how to send a command using ajax and jQuery to a serial device, but I cannot figure out how to receive a message sent back from the device?
The following javascript is what I use for sending a message to the device, Arduino, from a button click:
<!-- Arduino Serial Connection -->
<script type='text/javascript'>
jQuery(function() {
jQuery('#contact_form').on('click', '.button',function (e) {
e.preventDefault(); //prevents the default of submitting the form
jQuery.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: "rcmd="+jQuery(this).val(),
success: function() {
alert('Enroll Your Finger Now');
}
});
return false;
});
});
</script>
And here is the SubmitFormWORefresh.php:
<?php
$verz="1.0";
$comPort = "/dev/ttyACM0"; /*change to correct com port */
$PHP_SELF="index.php"; //This php file locate it from root
if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case "Stop":
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 1); /* this is the number that it will write */
fclose($fp);
break;
case "Enroll":
$fp =fopen($comPort, "w");
sleep(2);
fwrite($fp, 3); /* this is the number that it will write */
fclose($fp);
break;
default:
die('Crap, something went wrong. The page just puked.');
}/*end switch case*/
}/*end if statemen t*/
?>
The following code is from the index.html page that displays the button that javascript manipulates, and also the textbox that I want the output of the serial device to display to.
<!----This is the button that I first send a message to the device -->
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<input type="submit" name="rcmd" class="button" id="submit_btn" value="Enroll" />
</fieldset>
</form>
</div>
<!----This is the textbox I need to send incoming data to-->
<input type="text" value="" id="table_0_fprint_id" data-key="fprint_id" data-input_type="text" class="editDialogInput " />
After I click the button and send a message to the device, the device then sends a message over a serial connection back to the webpage. I need the javascript to input this message into the textbox. I know I will probably need use the GET function, but I cannot get it to work properly.
All you need to do is to handle the ajax response. In my example i called it response (argument to the anonymous function bind to success). Code is untested, but should work:
<!-- Arduino Serial Connection -->
<script type='text/javascript'>
jQuery(function() {
jQuery('#contact_form').on('click', '.button',function (e) {
e.preventDefault(); //prevents the default of submitting the form
jQuery.ajax({
type: "POST",
url: '/test/SubmitFormWORefresh.php',
data: "rcmd="+jQuery(this).val(),
success: function(response) {
alert('Enroll Your Finger Now');
$("input#table_0_fprint_id").val($(response).text());
}
});
return false;
});
});
</script>
You also have to make sure that /test/SubmitFromWORefresh.php script prints/echo'es a message to be placed in the input on response.
I have thoroughly researched this topic, but cannot seem to find an answer due to the fragmented nature of the discussions and the very different use cases everyone seems to have.
I am using JQuery mobile to send data to a PHP login/registration script via $.ajax() call. It appears that the data I am trying to send never makes it to the server to be evaluated, and I am at a loss as to why.
I am trying to send the data from this form:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
Which is triggered by this javascript:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
Which is sent to this php script:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
However, as stated earlier, the if/else block detects that $_POST['formDataReg'] is not even set. When I try to use it to assign values to variables, it obviously has no data to assign and I get null values.
I used alert to verify that indeed formDataReg did hold the proper form values before being passed to the server in the ajax call. It somehow gets lost in the ajax call, or I am not accessing it correctly.
If someone can point me in the right direction, I would very much appreciate it.
By this:
var formDataReg = $("#reg_form").serialize();
You serialized your form into the form. Now in formDataReg has such contents:
reg_email=xxx#gmail.com®_pass=yyy®_pass_conf=yyy
You have to parse this query in your php file:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
But you tried to work with $_POST['formDataReg'] which wasn't sent. So it is wrong. Yes, you had variable formDataReg in your JS, but it means nothing. You had sent serialized string (query) with your ajax-request and have to handle it.
So this code:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
wouldn't work because you hadn't sent formDataReg and there are no value with this key in $_POST array.
This:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
should work properly.
Let me know is something is unclear.