I have a registration page on my website for which I want to implement PHP and AJAX validation. I will show template of my code (my code is much bigger) to try to explain the problem.
registration.php
<!DOCUMENT html>
<html>
<head>
<script>
$(document).ready(function(){
$("#signupForm").submit(function(event){
event.preventDefault();
var firstNameInput = $("#firstName").val();
var lastNameInput = $("#firstName").val();
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput
});
});
});
</script>
</head>
<body>
<form id="signupForm" action="includes/signup.script.php" method="POST">
<input id="firstName" type="text" name="firstName">
<input id="firstName" type="text" name="firstName">
<button id="submit" name="submit" type="submit">Submit</button>
<div class="messageForm"></div>
</form>
</body>
</html>
signup.script.php
<?php
if (isset($_POST['submit'])) {
include "dbconn.script.php";
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
//Validators for inputs in PHP with various error messages (1-15) and database INSERT and SELECT functions.
...
} else {
echo "<span>Error 16</span>";
exit();
}
}
?>
<script>
// JQuery validator for inputs and CSS style changers based on errors
...
</script>
My problem is when I click Submit button, I get error message "Error 16", so my function skip whole PHP script and does not insert data into database. I concluded that the problem is because the variable $_POST['submit'] is not set, because when I change first line of code to if (!isset($_POST[submit''])), it works like charm, but I don't wanna loose ability to prevent users from type signup.script.php in URL field of the browser and run it. How to correct this to work? The tutorial I watched has this code and in that case it works without problem.
P.S. I will expand my code if needed for solution of this problem, because I wanted to spare space so I gave the shorthand version of it.
You simply don't send "submit" with the request.
You could add it here:
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput,
submit: 1
});
or check for isset($_POST['firstName'])
Sidenote: If there wasn't an object passed in with load() it would be a GET request. Worth remembering...
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
The Docs
according to the jQuery documentation of jQuery.load() (which is a shorthanded jQuery.ajax method), this sound much alike if this would be a $_GET and not a $_POST... better use something alike jQuery.ajax() in combination with method: 'POST' - or check for the $_GET in PHP.
Dear check your JavaScript code carefully
event.preventDefault(); // Preventing default form submission
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput
});
Only posts firstName and lastName to signup.script.php
And you are trying to check for isset($_POST['submit'])
It will surely be false until you pass 'submit' in post like firstName and lastName you have passed already like below
$(".messageForm").load("inculdes/signup.script.php", {
firstName: firstNameInput,
lastName: lastNameInput,
submit: 'yes'
});
Hope it helps
Related
I'm trying to combine a form.submit() call with a jquery/ajax call to get a response from my php login script - I've just spent a few hours trying to hack together some of the hundreds of posts/examples on a similar topic but am out of ideas now so am hoping someone can help.
My sign in form looks like this...
<form id ="signInForm" action= "/userManagement/proxy_process_login.php" method="post" name="login_form">
<input required id="signInUserId" name="email" type="text" placeholder="Username/Email" class="input-medium">
<input required id="signInPassword" name="password" type="password" placeholder="Password" class="input-medium">
<button id="signin" name="signin" class="btn btn-success" onclick="signInSubmit(this.form, this.form.signInPassword);">Sign In</button>
</form>
The function signInSubmit() (called by the button's onclick) simply validates the text fields, and replaces the plain text password with a hashed version before finally calling "form.submit()", like this...
//ommited a bunch of text input validation
var p = document.createElement("input");
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
password.value = ""; // Make sure the plaintext password doesn't get sent.
form.submit();
My PHP script (proxy_process_login) also works fine before adding any jquery/ajax and essentially does this...
if (login($email, $password, $mysqli) == true) {
// Login success (ok to reload existing page)
header("Location: ../index.php?login=success");
exit();
} else {
// Login failed (do NOT want to reload page - just message "fail" back via AJAX so I can update page accordingly)
echo "fail";
exit();
}
But given the route I'm taking to submit the form, I'm struggling to incorporate an Ajax example - because I've got this new "form" variable (with the hashed p variable appended), so I can't use an Ajax call which refers back to the form using jquery like this...
$.ajax({type:'POST', url: '/userManagement/proxy_process_login.php', data:$('#signInForm').serialize(), success: function(response) {
console.log(response);
}});
(because the jquery reference doesn't include the new variable, and I've already specified the php script in the action attribute of my form)
And I also can't call something like "serialize()" on my "form" variable inside signInSubmit().
Any ideas on an appropriate way to structure a solution to this?! Thanks!
Unfortunately there is no callback for native form submission using action attribute , it was used in the past to redirect you to that page and show the results there.
Modern method now is to use ajax call , after perventingthe default submission.
Solution:
HTML:
<form id="myForm">
<!-- form body here --!>
</form>
Javascript:
$("#myForm").submit(function(e){
e.preventDefault();//prevent default submission event.
//validate your form.
//disable your form for preventing duplicate submissions.
//call you ajax here.
//upon ajax success reset your form , show user a success message.
//upon failure you can keep your fields filled , show user error message.
})
this is a typical algorithm i use in any project i do , i recommend using parsley JS for front-end validation.
I'm trying to change my form action in my HTML then submit using javascript.
The conditions are in PHP .
I need help if anyone can assist me.
This is my PHP function :-
<?php
error_reporting(0);
if(isset($_POST['email'])){
$email=$_POST['email'];
if(!empty($email)) {
$chrono = 0;
} else {
$chrono = 1;
}
}
?>
The motive of the PHP is to check null email entry.
Here's the javascript function :-
<script type="text/javascript">
function fireform(val){
// missing codes
document.forms["demoform"].action=val;
document.forms["demoform"].submit();
}
// missing codes
</script>
HTML :-
<form name="demoform" action="">
<input type ="text" name="name" id="name">
<input type="hidden" name="buttonpressed" id="buttonpressed">
<input type="button" value="submit B" onclick="fireform('b')">
I want to do it in a way , when the user entered an empty email , the PHP will read it as chrono = 0.
Then goes to javascript , if the chrono equal to 0 , the action will remain empty.
If the chrono = 1 , the javascript will change the action of the form and submit.
I need help thanks.
Your flow is unclear: it seems that you want to change the form action from PHP, but PHP is triggered after the form submission. So there's something weird in your flow. You also don't seem to have a field called email in your markup. Add it (or rename the field name):
<input type="text" name="email" id="email">
Nonetheless, having an empty action means the form will be submitted to the page itself.
Probably what you need is a client side validation of the email field. In the fireform() JavaScript function, just add a check for email field:
function fireform(val){
if (document.forms["demoform"].email.value.length > 0){
document.forms["demoform"].action = val;
document.forms["demoform"].submit();
}
}
This should be enough to get what you need.
I would recommend checking the email field (for being empty) in javascript, and when you have set the proper action submit the form in javascript.
Check the field:
$('#<enter id of field>').val();
Update the action:
$('form').attr('action', 'Enter your updatet action here');
Submit the form:
http://api.jquery.com/submit/
Let me Clear what title means:
In my code for a validation purpose of one field dependent on field "t1" I need to auto submit my form once (Just Once). But my below code is submitting it infinite times and I know the reason why its happening.
I guess Reason is everytime the form submits again JS in header runs. Please help me avoid this. Following is my code:
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm" method="Post">
<input type="text" id="t1" name="t1"/>
</form>
</body>
</html>
I tried stopping it using variable like flag and static variables like arguments.callee.count = ++arguments.callee.count || 1 and placing my CheckForm.submit() line in if clause. But nothing worked. Any advice or help is appreciable.
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("t1");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("CheckForm.t1");
temp1.value = "Task";
}
if(window.location.search=="")document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm">
<input type="text" id="t1"/>
</form>
</body>
</html>
Surely your form is more complex than:
<form name="CheckForm">
<input type="text" id="t1">
</form>
That will not submit anything to the server since there are no successful controls (the only control doesn't have a name).
Since the form is just submitting to the same page, you can submit a hidden value like:
<form name="CheckForm">
<input type="text" id="t1">
<input type="hidden" name="hasBeenSubmitted" value="yes">
</form>
Now when the form submits the URL of the new page will include ...?hasBeenSubmitted=yes so you can look for that value in the URL, e.g.
if (/hasBeenSubmitted=yes/.test(window.location.search)) {
// this page loaded because the form was submitted
}
If it exists, don't submit the form again.
So since you are using a post method the easiest way's to handle this is to ubmitted to a new url , however you seem set on keeping the form submitted to the same url in which case is you are using php (or really any other language) you can check if the http request has a post attribute with a value t1
<?php
if(isset($_POST['t1']){
$your_text=$_POST['t1'];
/*do some string checking to make safe and the throw into your database or mdo whatever you please with data
if you wanted to include the ip address of the user you can get a basic and most likely client ip address like so
$ip_address= $_SERVER['REMOTE_ADDR'];
if you are handing a mulitpage form look into php session or similar tech ... cookies is kind of over kill for this scenario
then include a succes page as the form has been submitted
or you could end php with this tag ?> and then have your html and start again with <?
*/
include 'form_submitted.php';
}else{
//this would be the html page that you included in your question and can be handle in same ways as form submitted
include 'my_form.php'
}
?>
Ip address may not be best included as it would stop 2 user from filling out the form if they are in the same LAN for eg. 2 people in same office or same house (if your page is acttual on the worldwide web).
I would take a look at #RobG answer as it he is basically suggesting the same type of thing with a get instead of post
ANyways hope this helps
I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function DoPost(){
$.post("index.html", { name: "John", time: "2pm" } );
}
</script>
</head>
<body>
GO
</body>
</html>
I made function and trying to call that function, inside that function I mentioned url and data as mentioned here. But, It's not working for me.
NOTE : Even I mentioned in my post title, then also I want to clarify that, I want to navigate to another page using POST method through simple hyperlink.
Create an html form with all the data you need to send and specify as action the page you need to forward the user.
<form method="post" id="theForm" action="REDIRECT_PAGE.php">
Then put some hidden fields in that form.
<input type="hidden" name="name" value="John">
<input type="hidden" name="time" value="2pm">
</form>
Wrap this inside of your doRedirect function and the redirect will work while correctly submitting your POST data.
document.getElementById('theForm').submit()
As a side note, you may want to redirect the user to a .php page not a .html one if you need to read POST data. This depends on your server configuration but, by default, I don't think you can run PHP code inside of a .html file.
I know this question is almost 4 years old and there is already an accepted answer, but I would like to provide an alternative solution as well as point out your mistake.
Part 1: The Solution
The conventional solution for navigating with a POST request is a form, which the accepted answer uses. I will build on top of this by presenting a solution to programmatically create forms using DOM.
var payload = {
name: 'John',
time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden'; // no user interaction is necessary
form.method = 'POST'; // forms by default use GET query strings
form.action = 'index.html';
for (key in Object.keys(payload)) {
var input = document.createElement('input');
input.name = key;
input.value = payload[key];
form.appendChild(input); // add key/value pair to form
}
document.body.appendChild(form); // forms cannot be submitted outside of body
form.submit(); // send the payload and navigate
I used index.html as per your original code, but I would take the accepted answer's advice and use PHP to accept and process the POST data.
Part 2: The Problem
The main problem with your original solution is that it used $.post, a helper function built on top of $.ajax. AJAX is meant to be used when retrieving data from a server and using it within current page, rather than navigating to another page.
This should work fine.
Similar to one answer, but a better one.
var payload = {
name: 'John',
time: '2pm'
};
var form = document.createElement('form');
form.style.visibility = 'hidden';
form.method = 'POST';
form.action = link;
$.each(Object.keys(payload), function(index, key) {
var input = document.createElement('input');
input.name = key;
input.value = payload[key];
form.appendChild(input)
});
document.body.appendChild(form);
form.submit();
function js_navigate_with_post(js_url, js_post_params)
{
var js_html='';
js_html += "<form id='js_navigate_with_post' method='post' action='"+js_url+"'>\n";
js_html += "<input type='hidden' name='js_navigate_with_post' value='true'>\n";
for (var js_key in js_post_params) {
if (js_post_params.hasOwnProperty(js_key))
{
js_html += "<input type='hidden' name='"+js_key+"' value='"+js_post_params[js_key]+"'>\n";
}
}
js_html += "</form>\n";
jQuery('body').append(js_html);
jQuery('#js_navigate_with_post').submit();
}
Finally, I did it, but not exactly as I wanted. But it is helpful for me. Now, sharing for others
<html>
<head>
<script type="text/javascript">
function DoPost() {
document.postlink.submit();
}
</script>
</head>
<body>
GO
<form action="demo.php" name="postlink" method="post">
<input type="hidden" name="name" value="this is my POST data">
</form>
</body>
</html>
I got it working finally in one of my projects.
You can try
<html>
<head>
</head>
<body>
<button id="clickme">GO</button>
</body>
<script>
$("#clickme").click(function(e){
var myForm = '<form id="ff" action="page2.php" method="POST">\
<input name="name" value="John">\
<input name="time" value="2pm">\
</form>';
$('body').append(myForm);
$('#ff').submit();
$('#ff').remove();
});
</script>
</html>
<html>
What do you mean it is not working? How can it work when you post results to a simple .html page?
The $.post function is a shorthand for $.ajax, which I always found easier to read and debug! Please have a look again in the link that you provided and see the examples in the bottom of the page!
For example:
$.post("test.php", { name: "John", time: "2pm" } );
Update: No, it shouldn't go to the index.html. What your code actually does is sending post variables to an .html page, so basically it doesn't do that much. That said, you can do what you want with many different solutions, see two of them below:
You can either add an done event on the $.post function, for example:
$.post("test.php", { name: "John", time: "2pm" } ).done(function() { alert("Success, do the redirection here!"); });
Or maybe maybe redirect using get variables instead of post ones? for example:
window.location = "index.php?username=blah&pass=blah";
and deal with them in the php page.
ps. the above solution obviously is for testing purposes, if you go that way you will have somehow to encrypt your data!