jQuery/AJAX execution of PHP not working - javascript

I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?

Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code

Related

I want to Customise the Message Shown when Form Submitted in html. How to to do it?

I have built a Send Email from a Static HTML Form using Google Apps Mail. The problem is that when I submit the form, I see a confirmation message that it was sent like:
{"result":"success","data":"{\"firstname\":[\"Abhay\"]}"}
I want to remove that and besides that I want a clean text after a form submission e.g. "Thanks for submitting". Please correct my code to remove this output.
<!DOCTYPE HTML>
<html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title> contact form </title>
</head>
<body>
<div>
<form id="gform" method="POST"
action="https://script.google.com/macros/s/AKfycbwlSM9z9ELHa1-
X6C_srRrB0j7FUlGgevJw7w7M/exec" >
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.."
required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit" value="Submit"/>
</form>
<div style="display: none;" id="thankyou_message">
<h2> <em>Thanks</em>xfn</h2>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-
without-server/master/form-submission-handler.js"></script>
</body>
</html>
You can make an ajax request instead of submitting the from directly.
<form id="gform" onsubmit="return postMessage()">
In below
<script>
function PostMessage() {
var form = document.getElementById('gform')
fetch('"https://script.google.com/macros/s/AKfycbwlSM9z9ELHa1-
X6C_srRrB0j7FUlGgevJw7w7M/exec', {
method: 'POST',
body: new URLSearchParams(new FormData(a)).toString()
}).then(function(res){ return res.json(); })
.then(function(data){
if(data.result == "success") {
document.getElementById('thankyou_message').style.display = 'block';
}
});
return false;
}
</script>

Save insert from to file

I have a input form and want to save the data that I haved insert into a file. Should I use get and set for this? Anyone have any ideas on what I should do?
function myfunction() {
if (validation()) // Calling Validation Function
{
// Serializing Form Data And Displaying It In <p id="wrapper"></p>
document.getElementById("wrapper").innerHTML = serialize(document.forms[0]); // Serialize Form Data
document.getElementById("form").reset(); // Reset Form Fields
}
}
function validation() {
var name = document.getElementById("namn").value;
var number = document.getElementById("number").value;
}
<!DOCTYPE html>
<html lang="sv">
<head>
<title>Write</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://form-serialize.googlecode.com/svn/trunk/serialize-0.2.min.js" type="text/javascript"></script> <!-- For Serialization Function -->
<script src="hej.js"></script> <!-- Include JavaScript File Here-->
</head>
<body>
<div id="main">
<div id="login">
<hr/>
<form action="" method="post">
<label>Name:</label>
<input type="text" name="name" id="name" required="required" placeholder="fill in your name"/><br /><br />
<label>Number :</label>
<input type="text" name="number" id="number" required="required" placeholder="0876856"/><br/><br />
<input onclick="myfunction()" type="submit"id= "submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</body>
</html>
Thanks in advance!
If you use the normal $_POST you can access the data over $_POST and write it with fopen, fwrite to a file. Over ajax you have to send the Data to a PHP File and do the same there. You cant access the local filesystem over Javascript.
<?php
if(isset($_POST) && !empty($_POST){
// reformat your data here and format it
$yourDataToWriteInTheData = $_POST['firstname'] . '|' . $_POST['lastname'] . PHP_EOF;
// Open the file (or create it, read the fopen manual)
$fileHandler = fopen('file1.txt', 'a+');
fwrite($fileHandler, $yourDataToWriteInTheData);
fclose($fileHandler);
}

In Sinatra, how do I make a multi-page pop-under form which stays on the same page as you fill it out?

I've made a form that appears in a pop-under window, but I can't figure out how to make it multi-step.
Here's my code:
1) main.rb file:
[
'rubygems',
'sinatra',
'sequel'
].each{|g| require g}
DB = Sequel.sqlite('database.sqlite')
DB.create_table? :data_table do
primary_key :id
varchar :img_path
varchar :form1_name
varchar :form2_option
end
before do
#img_path = nil
#form1_name = nil
#form2_option = nil
end
get '/?' do
erb :index
end
post '/form2' do
user_img = params['user_img']
#img_path = './public/images/uploads/' + user_img[:filename]
File.open(#img_path,'wb'){|f| f.write(user_img[:tempfile].read)}# Copying the upload file to the server directory
#form1_name = params['form1_name'] # !!!DATAPOINT!!!
end
2) layout.erb file
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multi-page form test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!-- jQuery UI CSS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- jQuery -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!-- jQuery UI -->
<script src="./js/script.js"></script>
</head>
<body>
<%= yield %>
</body>
3) index.erb file
<button id="upload_form_opener" type="button">Click here to upload</button>
<div id="upload_form_container" title="Form container title">
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<img id="upload_preview" style="width: 300px; height: 300px;" />
<input id="upload_image" accept="image/*" type="file" name="user_img" onchange="PreviewImage();" />
<script type="text/javascript">
// This JavaScript snipppet is for previewing the image upload
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("upload_image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("upload_preview").src = oFREvent.target.result;
// document.getElementById("upload_image").disabled = true
}; // DONE: function (oFREvent)
}; // DONE: function PreviewImage()
</script>
<p>Name <input type="text" name="form1_name" /></p>
<input type="submit" value="Next" />
</form>
</div>
4) script.js
$(document).ready(function(){
var uFormContainer = $('#upload_form_container');
// This snippet is for opening the pop-under form
uFormContainer.dialog({autoOpen: false});
$('#upload_form_opener').click(function(){
uFormContainer.dialog('open');
});
});
5) I want the second step of the form to look like this...
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<p>Some other text field <input type="text" name="form2_option" /></p>
<input type="submit" value="Next" />
</form>
...but I don't want to leave the page (which is '/', as far as Sinatra is concerned). Is this possible in Sinatra?
There are multiple ways to implement this:
Save some cookie or session, which step is now, and depends on that yield different forms. After submitting write next step id into session and redirect to root_url.
Use ajax to send form and render next step's form.
You can even not really send form, but just switch to next, just hidding previous fields with javascript and show next step's fields. After submitting all parameters will be sent.

how to submit a form from loaded form into main page?

contact.php
... html form ...
$('#submit').click(function(){
$.post("mail.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
mail.php is a separate file (for sending mail), and everything works in this arrangement.
But I need to load contact.php into index.php
$('#divR').load('chapters/contact.php');
so corresponding js line becomes
$.post("chapters/mail.php", $("#contact").serialize(), function(response) {...
Submitting the form in this case response from mail.php is received, but POST array is empty, i.e. form doesn't send any data to mail.php !?
I wrote your code in 2 new pages to see what it actually does, and noticed a few things. A few small things such as calling the submit handler instead of click, since people can also press Enter to submit a form, but most important the data itself: A form doesn't need to be serialized, the browser will already do that for you. In this script I store the data in a new object and pass it to the $.post method.
<form method="post" action="" id="contact">
<div>
<input id="email" type="text">
</div>
<div>
<input id="submit" type="submit">
</div>
</form>
Script:
$("#contact" ).on("submit", function () {
var data = {
email: $("#email").val()
};
$.post("test.php", data, function (response) {
$('#success').html(response);
});
return false;
});
In test.php I simply do a print_r($_POST), which is also the response. It will output something like:
Array
(
[email] => test
)
Hope this helps.
I've made a simple test, trying to mimic your goal:
testLoad.php = index.php in your case:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
$('#testLoad').load('Test/testForm.php');
});
</script>
</head>
<body>
<div id="testLoad"></div>
<div id="success"></div>
</body>
</html>
testForm.php and testTarget.php are respectively - contact.php and mail.php and are situated in folder Test their code is as follows:
testForm.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form id="contact" method="post" action="">
<p>
<label for="textfield">Name:</label>
<input type="text" name="textfield" id="textfield">
</p>
<p>
<label for="textfield2">Address:</label>
<input type="text" name="textfield2" id="textfield2">
</p>
<p>
<label for="textfield3">Mail:</label>
<input type="text" name="textfield3" id="textfield3">
</p>
<p>
<label for="textfield4">Subject:</label>
<input type="text" name="textfield4" id="textfield4">
<br>
</p>
<p>
<label for="textarea">Message:</label>
<textarea name="textarea" id="textarea"></textarea>
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" onClick="sendForm();">
</p>
</form>
<script>
$('#submit').bind('click', function(){
//console.log($("#contact").serialize());
$.post("Test/testTarget.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
</script>
</body>
</html>
and testTarget.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php print_r($_POST);?>
</body>
</html>
when testing in success div I receive the POST printed out.
Hope this helps.

Convert jQuery Object to String upon AJAX call

Let's say I submit a form with anything in the value of user_input like "I am free." I submit it through AJAX and it gets returned to me as a string. Ok now it's an Object... how would I turn that into a string?
Thank you,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<title>Sin título 3</title>
</head>
<body>
<div id="result_target" style="display:none;"></div>
<form id="form_to_post" action="#" method="post">
<input type="hidden" name="url" value="example.php" />
<input type="text" name="user_input" />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#form_to_post").submit(function() {
var hiddenURL = $("input[name=url]");
var userInputForm = $("input[name=user_input]");
//var dataString = "userInput="+inputForm;
$.ajax({
type: "POST",
url: hiddenURL;
data: {userInput: userInputForm},
success: function(return_contents) {
//returns jquery object...
var output =//
$("#result_target").html(output);
}
});
});
});
</script>
</body>
</html>
use val() to get values from inputs
data: {userInput: userInputForm.val()},

Categories

Resources