Getting an Ajax response from a form.submit() to PHP - javascript

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.

Related

How would you design this webpage with multiple forms?

I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !
you can use AJAX for this purpose...
$(document).ready(function() {
// 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 = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.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);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however
If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.

Ajax call on form submission - MVC 5

The Goal:
Use an ajax call to either bring back information from database if the user supplied correct information, or if the user is a new user then it will return redirectToAction and send the user to another form. I want to do all of this using either parsley or bootstrap validator (I want to use these tools so that I can put the validator in the input and once I click on submit it will validate the form, but will not submit it. I also want it to have the same look, so the fields highlight similar to http://1000hz.github.io/bootstrap-validator/ The ajax call will handle the decision)
The problem:
Here is a similar form:
<form action="" id="application">
First Name: <input type="text" name="first" required/>
Last Name: <input type="text" name="last" required/>
<button type="submit">Submit</button>
</form>
When one clicks on this form, if the user has not supplied the first and last name it will not submit the form.
What I want it to do is if the user has supplied this information it will not go to the action but will instead execute the ajax call and never submit the form from the button press similar to $(button).click(function (){//do stuff});(the ajax call will handle the submission, my guess here is that we can substitute this ajax call for any JavaScript function).
Finally:
I have read about the e.preventdefault but it did not seem to work for me. How can I get the form to validate the inputs but never actually submit (unless the ajax allows it to). Can you give me an example of how I would do this? Or is this something that cannot be done? Should I do something similar to this Validate Form preventing form submission
Add an onsubmit event on the form, for example,
<form onsubmit = "DoSubmit(this);return false;">
DoSubmit: function()
{
//validate the form and decide submit or not
if($(form).valid())
{//if form valid, this is done by form validation itself
$(form)[0].submit();
}
else
{
//do nothing or do whatever
}
}

Calling PHP function from Javascript then change form action

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/

jQuery and Ajax combination confusion

I am a new user and I need help with JQuery and Ajax. I am good at PHP only.
I have a HTML Page which has a newsletter signup section,
<h4>Newsletter</h4>
<form id="main-news-contact-form" class="news-contact-form" name="news-contact-form" method="post" action="/scripts/xnews.php" role="form">
<div class="input-group">
<input type="text" class="form-control" required="required" placeholder="Enter your email" name="email"/>
<span class="input-group-btn">
<button class="btn btn-danger" type="submit">Go!</button>
</span>
</div>
</form>
And the relevant JQuery -
//newsletter form
var form = $('.news-contact-form');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
},'json');
return false;
});
I have a php script, that reads the form data and saves the email address received in the database table, but for some reason the data (email address) is not being received by the PHP Code, the code below is executed.
if(empty($_POST["email"]))
{
echo("failed");
}
I don't know what I am doing wrong, I have a 'contact us' form, which is working absolutely fine, but I don't know why this newsletter form is not working with jquery.
I assure that all the javascript files are included in the html page, the php page is running absolutely fine, it does not return any php or mysql errors, I am setting JSON headers correctly, it's just that I am not getting the email address entered into the form. Earlier it was working but Ajax was not working, now I managed to get Ajax to work but the JavaScript code is not sending the form data.
Can you please help or help me to debug this.
Thanks in advance !
Your code is not sending any data to the server. Try to add the data as a second parameter to the function.
// get the text from the input field with the id "email"
var email = $.("#email").val();
// get the url from the form
var url = $("#newsletter-send").attr('action');
$.post( url, { email: email }, function( data ) {
// The code that you want to execute after sending the ajax call
}, "json");
Please do not copy paste the code but try to find the reasoning behind it. You might need to check the url variable to make sure you are posting to the right place. Also try to add an id attribute to the input field that contains the email.
I hope this will help you.
Try with this:
var form = $('#main-news-contact-form');
form.submit(function(e) {
e.preventDefault(); // Prevent submitting the form
$this = $(this);
$.post($this.attr('action'), $this.serialize()).done(function(data) {
// Do something with data
$this.prev().text(data.message).fadeIn().delay(15000).fadeOut();
}, 'json');
});

How can I submit a form automatically (onevent) with javascript?

I'd like to be able to submit a form automatically on an event ( a generic form, for user tracking).
For example, create a POST to
http://www.example.com/index.php?option=track&variable=variable
application/x-www-form-urlencoded with stuff like
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2
The actual string will be preformatted, though, because all it is is like a 'ping'.
It needs to be submitted onevent, with external js ( http://example.com/scripts/js.js )
What the hay should I do? This is getting annoying.
Update: I guess I didn't really make myself clear; I have a premade form that isn't supposed to display on the page; it needs to submit on an event. The form fields do not exist on the page; all I do is link to the script on the page and it executes onLoad.
POST uri: http://www.example.com/index.php?option=track&variable=variable
The arguments above (option=track and variable=variable) are not the form details (postdata).
The content type is application/x-www-form-urlencoded , and has the following keys/values.
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2 (when encoded, the spaces get turned to %20's.)
I need a script that submits this when run.
You have to get the form object and call the submit(); function provided by HTMLFormObject.
document.getElementById('myForm').submit();
1) with the following, (while page is loaded), the form will be immediately autosubmited
<form action="post.php" name="FNAME" method="post">
<input type="text" name="example22" value="YOURVALUE" />
<input type="submit" />
</form>
<SCRIPT TYPE="text/JavaScript">document.forms["FNAME"].submit();</SCRIPT>
another formSubmit alternative - submits any script:
document.forms[0].submit();
2) or use button click after 2second:
<SCRIPT TYPE="text/JavaScript">setInterval(function () {document.getElementById("myButtonId").click();}, 2000);</SCRIPT>

Categories

Resources