I have a question regarding POST method. I'm trying to record the data from form into txt file. But the string is empty (in txt file I have only "The request: ")
HTML:
<form
action=""
method="POST"
id="form"
class="section-contact-me-form"
>
<fieldset>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="name">Name*</label>
<input
type="text"
name="name"
class="section-contact-me-input__input _req"
id="name"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="email">E-mail*</label>
<input
type="text"
name="email"
id="email"
class="section-contact-me-input__input _req _email"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="phone">Phone</label>
<input
type="text"
name="phone"
id="phone"
class="section-contact-me-input__input phone"
>
</div>
<div class="section-contact-me-textarea">
<label class="section-contact-me-textarea__label" for="message">Your message*</label>
<textarea
rows="10"
cols="45"
name="message"
id="message"
class="section-contact-me-textarea__textarea _req"
></textarea>
</div>
</fieldset>
<div id="submit" class="submit-button">
<button class="submit-button_active">Send data</button>
</div>
</form>
JS:
form.addEventListener("submit", formSend);
async function formSend() {
const formData = {
name: document.querySelector("#name").value,
email: document.querySelector("#email").value,
phone: document.querySelector("#phone").value,
message: document.querySelector("#message").value
};
const formDatatoSend = JSON.stringify(formData)
sendData("http://localhost:3000/101_susov_newDesign/contactme.php", formDatatoSend)
.then(() => {
form.reset();
})
.catch((err) => console.log(err))
};
const sendData = async (url, data) => {
const response = await fetch (url, {
method: "POST",
body: data
})
if (!response.ok) {
throw new Error (`URL with error ${url}, status ${response}`)
};
return await response;
};
PHP:
<?php
$value = $_POST['value'];
$f = fopen('file.txt', 'a+');
fwrite($f, "The request: ".$value."\n");
fclose($f);
?>
So, the server works properly: there is the access to php code and txt file refreshes every time I use form button, but the content sended from form is empty. As I told before in txt file I have only "The request: "
Where is the eror in my code? Thanks in advance and have a good day!
You do not have a field called value so $_POST['value'] doesn't return anything. You can get the value of each field by adding it's name attribute as the array key:
$value = $_POST['phone'] would return 'The request: PHONE_NUMBER' into your TXT file.
$value = json_encode($_POST) would return the whole post into your TXT file
This should work:
$value = json_encode($_POST);
Related
index.js
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').onsubmit = send_email;
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
function send_email()
{
const recipients = document.querySelector('#compose-recipients').value;
const subject = document.querySelector('#compose-subject').value;
const body = document.querySelector('#compose-body').value;
//console.log(recipients)
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
}
inbox.html
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
Submitting a form through Javascript via POST method but I am getting an output of GET /? HTTP/1.1" 200 1667 in terminal..
It should be 201 via POST
When I am writing the fetch function in Console.It is working fine
After submitting the form it is just returning back to the inbox page.
Since you are doing a "fetch" in your code, you should prevent the default form submission on the "submit" button click (This this the default behaviour). To achieve this you can receive the "event" as a parameter in the "send_email" function and then do a "event.preventDefault()".
function send_email(event) {
// Your code
...
// Prevent the default form submission
event.preventDefault();
}
More details # https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit
I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>
try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem
I have a HTML form
<div class="contact-form col-md-6 " >
<form id="contact-form" method="post" action="" role="form">
<div class="form-group">
<input type="text" placeholder="Your Name" class="form-control" name="name" id="name" required>
</div>
<div class="form-group">
<input type="email" placeholder="Your Email" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<input type="text" placeholder="Your Phone Number" class="form-control" name="phone" id="phone" required>
</div>
<div class="response_msg"></div>
<div id="mail-success" class="success">
Thank you. You are registerd. :)
</div>
<div id="mail-fail" class="error">
Sorry, don't know what happened. Try later :(
</div>
<div id="cf-submit">
<input type="submit" id="contact-submit" class="btn btn-transparent" value="Register" name="submit">
</div>
</form>
</div>
I need to submit form on same page and show message on successfully submission. I am using JS for this
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='name']").val() === '')
{
$("#contact-form [name='name']").css("border","1px solid red");
}
else if ($("#contact-form [name='email']").val() === '')
{
$("#contact-form [name='email']").css("border","1px solid red");
}
else if ($("#contact-form [name='phone']").val() === '')
{
$("#contact-form [name='phone']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
As soon i clicked on submit button page refresh but my i don't see my pho code inserting data in database.
<?php
require_once("conn.php");
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
// require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$sql="INSERT INTO Beta_Registration (name, email, phone) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
I want my form to submit on same page also stays on same block and shows the messages in div inside form when data entered successfully or failed into database.
The issues i am facing whenever i press submit button it refreshed the page and form data doesn't executed into database. It might be php or JS i am using. Please help me in this.
1- You need to add "return false" in your on submit function to prevent browser to submit the form
$(document).ready(function () {
$("#contact-form").on("submit", function (e) {
...
return false;
});
...
});
2- You need to match you database table name, and their columns name which you have used in your MySQL query.
I have a foreach to get messages in database,My code is here:
<form action="/Send/Message/Reply" method="POST" id="sendReply">
{{csrf_field()}}
<textarea class="text-right" cols="80" rows="5" id="messageReply">
</textarea>
<input type="hidden" value="{{$message->id}}" id="messageId">
<div class="footer text-right">
<button type="submit" class="S-products">Send</button>
</div>
</form>
Now I Want to get message id and Reply_Content in javascript with axios by this code:
(function()
{
document.querySelector('#sendReply').addEventListener('submit',function (e) {
var messageReply = document.querySelector('#messageReply').value;
var messageId = document.querySelector('#messageId').value;
console.log(messageId)
axios.post(this.action,{
'messageReply' : messageReply,
'messageId' : messageId,
'_token': $('input[name=_token]').val()
})
})
})();
Bu i get messageId as Undefined,How I can Fix this problem?
I fixed my problem with this code:
var messageId = document.getElementById('messageId').value;
Am new in javascript , and am trying to POST data with an API endpoint but data is not posting , I have printed in the console , but I see Slow network is detected. See https://www.chromestatus.com/feature/5636954674692096 for more details. Fallback font will be used while loading: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0 in Google chrome.
But internet connection is good and stable.
This is my vanilla javascript for posting data :
function onSignUp() {
signupform
var email = document.signupform.email_edt.value;
var driver_rb = document.getElementById("driver_rb").checked;
var password_edt = document.signupform.password_edt.value;
var r_password_edt = document.signupform.r_password_edt.value;
var url = 'https://tuvuge-app.herokuapp.com/api/v1/signup';
//var data = {username: 'example'};
var data = {
username: email,
email: email,
password: password_edt,
isDriver: 'True'
};
fetch(url, {
method: 'POST',
body: JSON.stringify(data), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Then I attached the onSignUp() function to the button in html as below :
<form class="admin-modal-content" name="signupform" onSubmit="onSignUp();" action="index.html" method="post">
<div class="container">
<h4>Sign Up</h4>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email">
<b>Email</b>
</label>
<input type="email" placeholder="you#example.com" id="email_edt" name="email_edt" required>
<label for="email">
<b>Select an Option</b>
</label>
<p>
<input type="radio" name="driver_rb" value="driver" id="driver_rb">
<label>Driver</label>
</p>
<p>
<input type="radio" name="passenger_rb" id="passenger_rb" value="passenger">
<label>Passenger</label>
</p>
<label for="psw">
<b>Password</b>
</label>
<input type="password" placeholder="Enter Password" id="password_edt" name="password_edt" required>
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<input type="password" placeholder="Repeat Password" id="r_password_edt" name="psw-r_password_edt" required>
<div class="clearfix">
<button type="submit" class="btn">Sign Up</button>
</div>
</form>
What am I missing ,because the endpoint has a message it brings when there's a success or failure of data posting , but I see the above message.
What am I missing?