Javascript to send form to PHP - javascript

I am trying to get my HTML form to pass through Javascript that will then pass it to PHP that will send it to MySQL.
However I either get the page to load the JS file in the browser, or the PHP file to load in the browser.
Here is my HTML form:
<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>
<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>
I want the outcome of the form submit placed into the "outcome" div
My JS code:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById("content");
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById("content");
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function submitForm(){
var name = document.getElementById('name').value;
var booking = document.getElementById('subject').value;
var enquiry = document.getElementById('subject').value;
var email = document.getElementById('email').value;
var telephone = document.getElementById('telephone').value;
var message = document.getElementById('message').value;
getRequest(
'php/form.php?' + params, //URL for the PHP file
procesOutput,
processError
);
return false;
}
function processOutput(){
var container = document.getElementById('outcome');
container.innerHTML = responseText;
}
function processError(){
alert("There has been an error, please try again");
}
and my PHP code:
$con=mysqli_connect("DBLocation","Username","Password",'DBName');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");
if ($conn->query($sql) === TRUE){
echo "Thank you for contacting us, I will replay to you soon!";
}
else {
echo "I'm sorry but an Error has occured. Please try again shortly";
}
mysql_close($conn);
?>
I've had a look at w3schools pages and some other questions on here but I can't seem to get my head around it.

A couple of things, first off what is getRequest? Second off, where is responseText defined? Third, I would check your console as I'm pretty sure there is an error in submitForm. I see lots of getElementByIds, but none of your inputs have ids associated with them:
<input type="text" name="name" placeholder="Name" autofocus required>
Should be:
<input type="text" id="name" placeholder="Name" autofocus required>

I believe you want to use Ajax, which you can easily use with jQuery.
I believe the answer for your question is right on this page: https://learn.jquery.com/ajax/ajax-and-forms/
If jQuery is new for you, you might want to read a little about jQuery: https://learn.jquery.com/about-jquery/
If you don't want to use jQuery, you can use directly XMLHttpRequest in javascript instead.

Here is a demo in JSFiddle.
Remove onClick, onSubmit, action="js/contactform.js" method="post" attributes as you don't need them. Capture the form submit in js. How to? - link
Add id's on the form elements so than you can select them like:
var name = document.getElementById('name').value;
Make a $.post request with jQuery (How to? - Link) and handle the success and failure callbacks. (I don't understand why are you making a post request, I would recommend you a $.get request.

Related

JavaScript AJAX Request Successful, But Returns Nothing

I've been following along a tutorial, but I just can't make it to work. One hour of trying to figure it out, but nothing. This AJAX request returns nothing. I'm a beginner. Help is appreciated.
<form id="postForm">
<input type="text" name="name" id="name1">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
document.querySelector('#postForm').addEventListener('submit', loadText5)
function loadText5(e) {
e.preventDefault();
let name = document.getElementById('name1').value;
let params = "name"+name;
let response = new XMLHttpRequest();
response.open('POST', 'process.php', true);
response.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
response.onload = function() {
console.log(this.responseText);
}
response.send(params);
}
</script>
Process.php
if (isset($_POST['name'])) {
return 'POST: Your name is ' . $_POST['name'];
}

Uploading file through ajax and jquery

Good evening guys, I got a problem in the back-end of my system when I submit my form. It said Unidentified index: file1 . I can't fine the error here in my code.
I'm not a newbie in javascript and seeking for help from you guys. Advance thank you.
So here is my HTML form
<form id="submit_form" action="<?php echo base_url()?>Homepage/add_blog" enctype="multipart/form-data" method="POST" >
<input type="text" class="form-control" id="title" name="title" autocomplete="off">
<input type="text" class="form-control" id="lead" name="lead" autocomplete="off">
<input type="text" id="tags" name="tags" data-role="tagsinput" placeholder="Add tags" class="form-control" >
<input type="file" id="file1" name="file1" >
<textarea id="content" name="content" rows="10" cols="80">
Put the content here!!!
</textarea>
</form>
Here is my script
<script>
function _(el)
{
return document.getElementById(el);
}
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var file = _("file1").files[0];
var title = $('#title').val();
var lead = $('#lead').val();
var tags = $('#tags').val();
var content = $('#content').val();
if(title == '' || lead == '' || tags == '' || content =='')
{
$('#response').html('<br><div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div>');
$('#response2').html('<div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div><br>');
}
else
{
$.ajax({
url:"<?php echo base_url()?>Homepage/add_blog",
method:"POST",
data:$('#submit_form').serialize(),
beforeSend:function()
{
$('response').html('<span class="text-danger">Loading...</span>');
$('#submit').prop("disabled", true);
var formdata = new FormData();
formdata.append("file1",file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress",progressHandler,false);
ajax.addEventListener("load",completeHandler,false);
ajax.addEventListener("error",errorHandler,false);
ajax.addEventListener("error",abortHandler,false);
ajax.open("POST","<?php echo base_url()?>Homepage/add_blog");
ajax.send(formdata);
},
success:function(data)
{
$('form').trigger("reset");
$('#tags').tagsinput('removeAll');
$('#tags').tagsinput('destroy');
CKEDITOR.instances.content.setData('');
$('#response').fadeIn().html(data);
}
});
}
});
$('#title,#lead,#tags,#content').focus(function(){
$('#submit').prop("disabled", false);
});
});
function progressHandler(event)
{
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded;
var percent = (event.loaded/event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded.. please wait";
}
function completeHandler(event)
{
_("progressBar").value = 0;
}
function errorHandler(event)
{
_("status").innerHTML = "Upload Failed.";
}
function abortHandler(event)
{
_("status").innerHTML = "Upload Aborted.";
}
</script>
And the problem relies here in the back-end Homepage/add_blog:
$filename = $_FILES["file1"]["name"];
echo $filename;
If you any more details needed to solve this. Just comment. Need to fix this as soon as possible. Thank you again.
Undefined index notice that the array $_FILES does not contain the "file1" key set. Probably the way you are trying to send the file via ajax is not working properly.
I'd recommend you try to use FormData. I believe the link below is a good reference to solve your problem.
How to use FormData for ajax file upload

how to send json data and 1-n files in POST body use javascript

I have from like this:
<form id="form" method='post' action="http://192.168.1.33/api/" enctype="multipart/form-data">
<label>User login: </label>
<input type="text" id="userLogin"><br />
<label>User password</label>
<input type="text" id="userPass"><br /><br />
<label>Input command here</label>
<input type="text" size="100" placeholder="users" id="command" name="command"><br/><br />
<input type="file" name="file1"><br/>
<input type="file" name="file2"><br/>
<br />
<input type="submit">
</form>
<h3>Output: </h3>
<div id="output"></div>
And simple javascript code. This code gets form data (attached files) and creating 2 fields in http header with userName and userPass, and send it to my api:
<script type="application/javascript">
var myCommand = document.querySelector('#command');
document.forms[0].onsubmit = function (event) {
if (window.FormData) {
event.preventDefault();
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var url = form.getAttribute('action') + '?' + myCommand.value;
xhr.open('post', url);
xhr.setRequestHeader('x-auth-user', document.querySelector('#userLogin').value);
xhr.setRequestHeader('x-auth-pass', document.querySelector('#userPass').value);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// server response: xhr.responseText
document.querySelector('#output').innerHTML = this.responseText;
}
};
xhr.send(data);
}
};
(function() {
document.querySelector('#userLogin').value = "user1";
document.querySelector('#userPass').value = "user";
})();
</script>
How can I add json data in body request use javascript? Json like this:
{
"id":"",
"status":0,
"documentName":"user",
"documentDesctiption":"",
"documentAttachedUsers":"id, id, id"
}
In fact I don't need form. I need to send 1-n files and one json string in POST body.
Now Api (php) receives just only form data (files). I plan on getting the body like this:
$inputJSON = file_get_contents('php://input');

Ajax Not Loading Asynchronous. Refreshing Page when form submitted

I have been trying to learn ajax and from what I can see my code is correct however it always refreshes the page when it echo's the returned json string. Any help would be greatly appreciated!
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.open(oFormElement.method, oFormElement.action, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
return false;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
alert("done");
document.getElementById('comment_form').innerHTML = request.responseText;
}
}
}
</script>
<form action="<?php echo $add_comment; ?>" method="post" enctype="multipart/form-data" id="comment_form" onsubmit="ajaxrequest(this);">
<input name="user_id" type="hidden" value="<?php echo $user_id; ?>">
<input name="user_message_id" type="hidden" value="<?php echo $user_message_id; ?>">
<textarea id="new_comment" name="new_comment" cols="100" rows="5"></textarea>
<input type="submit" value="post request"/>
</form>
You have to stop the event from happening. there is a common used function this in javascript:
e.preventDefault; // e is the event that you need to pass to your function.
or Change <input type="submit" value="post request"/>
to
<input type="button" onclick="ajaxrequest(this);" value="post request"/>
what is going to happen is your form is only going to be processed by javascript and page will mot reload due to the form submission.
Just modify this approach for yourself and it should fix your issue.
Use Jquery library http://api.jquery.com/jQuery.ajax/, but if u wanna build your own script. consult w3c documentation http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
As Pointy pointed out, you might want to prevent the default click event of the submit button from firing
submitForm( event ) {
event.preventDefault();
}
http://api.jquery.com/event.preventDefault/ <- My bad...
Just for clarification, is that your complete code?

JSONRequest.post not functioning

I am developing a web page and the purpose is to perform an http POST from form input elements, in JSON format. While the JSON element to be sent is formed properly, the request is never performed. Here is the code I have been using.
Form
<form id="input" action="javascript:snifForm()" >
User ID:
<input type="text" name="userId" id="userId" required>
Name:
<input type="text" name="name" id="name" required>
<div class="form-submit"><input type="submit" value="Submit" color="#ffffff" > </div></p>
</form>
Javascript (JSON.js, JSONRequest.js and JSONRequestError.js are imported)
<script type="text/javascript">
var requestNumber;
function snifForm()
{
var a1=document.getElementById("userId").value;
var a2=document.getElementById("name").value;
var toSend= {interactions: {id_user:a1, id_name:a2}};
var jToSend=JSON.stringify(toSend);
requestNumber = JSONRequest.post(
"http://someurl.com",
jToSend,
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
alert(value);
} else {
processError(exception);
}
}
);
alert(requestNumber);
}
</script>
I also tried the more classic form:
var xmlhttp = new XMLHttpRequest();
var out;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
out = xmlhttp.responseText;
alert(out);
}
else alert('nothing');
}
xmlhttp.open("POST", "the_same_url", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(jToSend);
After checking the server logs, no post is done ever :/
You should be attaching the event to the submit action of the form and you need to make sure to cancel the submit action.
I would not add the events directly to the form, but it is
<form id="input" onsubmit="snifForm(); return false;">

Categories