I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console.
Note: I am not yet collecting form data to send until I can actually get the ajax to work.
HTML:
<form id="myForm" action="process.php" method="post">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
jQuery:
$('#myForm').on('submit', function(e){e.preventDefault()});
var request = $.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
});
request.done(function(response){
console.log(response);
});
request.fail(function(){
console.log('fail');
});
PHP:
<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
Your on submit function is not doing anything. You need to have the ajax call inside of it.
Try:
jQuery(document).ready(function ($) {
$('#myForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
})
.done(function(response){
console.log(response);
})
.fail(function(){
console.log('fail');
});
});
});
Also I do not know where you are loading the JS. But you might want to wrap it in a document ready function to make sure your form exist when it is called.
Lastly there is a very nice plugin for forms that will make this easier for you. JQuery.Form.
http://malsup.com/jquery/form/
Related
What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.
Example of my form:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>
Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.
function sendValues() {
var formElement = document.querySelector("form");
console.log(formElement);
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
formData.append("process_type", 'process_data');
request.send(formData); //want to send all form userid, email directly to php page
request.onreadystatechange = (e) => {
console.log(request.responseText)
}
}
Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables.
thanks
In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.
<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">
And now in your function sendValues() you could submit form like this:
function sendValues() {
document.getElementById("file-info").submit();
}
or you do not even need this function if you set your input button type to submit:
<input type="submit" name="submit" />
And then in your php file you can use your variables like:
if (isset( $_POST['submit']))
{
$userId = $_POST['userid'];
$email = $_POST['email'];
}
Try this one then
HTML CODE
<form enctype="multipart/form-data" method="post" class='submit_form' name="fileinfo">
<label>Your user name:</label>
<input type="text" name="name" id='name' placeholder="name" required /><br />
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" id='userid' placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" value="Stash the file!" class='submit' />
JQUERY CODE on the same page (include jquery)
$('body').on('click', '.submit', function(e) {
e.preventDefault();
$.ajax({
'url': 'mpay.php',
'type': 'POST',
'data': $('.submit_form').serialize(),
success: function(response) {
console.log(response);
}
});
});
PHP CODE The file name is mpay.php
$arr = [
'name' => $_POST['name'],
'email' => $_POST['email'],
];
echo "<pre>;
print_r($arr);
echo "</pre>";
Hope this helps.
I have a form as so, which submits data to an outside domain:
<form action="https://EXTERNALdomain.com/register" id="form_register" method="POST">
<input type="text" id="first-name" name="first-name" value="" placeholder="First Name" required/>
<input type="text" id="last-name" name="last-name" value="" placeholder="Last Name" required/>
<input type="email" id="email" value="" name="email" placeholder="Email Address" required/>
<input type="password" id="password" name="password" placeholder="Password" required/>
<input type="submit" value="Create Account" />
</form>
However, I'm trying to be able to submit the form AND redirect it to a different page, also externally. So far, my attempts have been unsuccessful with AJAX.
<script type="text/javascript">
function sform() {
$.ajax({
url: "https://EXTERNALdomain.com/home",
data: $('#request').serialize(),
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e) {
alert('Error: '+e);
}
});
}
I've then been calling the form as so:
<form onsubmit="sform()" id="request">
This isn't working. I just get a long URL, and the form doesn't actually post, the page just reloads
This is because you're letting the form submit, which changes the page url and POSTs data there.
From "submit the form AND redirect it to a different page" I assume you want to submit the form to https://EXTERNALdomain.com/register and redirect to https://EXTERNALdomain.com/home. To do this, you need to use $.ajax to submit the form, them change the location on success.
function sform() {
$.ajax({
url: $('#request').attr("action"),
data: $('#request').serialize(),
type: $('#request').attr("method"),
success: function (resp) {
location.href = "https://EXTERNALdomain.com/home"; // redirect
},
error: function(e) {
alert('Error: '+e);
}
});
return false; // cancel default action
}
Because my the totality of my page is a basic "name and email" registration form, I don't see why I can't do a good ole-fashioned
<form action="/Account/Register/" method="POST" id="registration-form">
<fieldset class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="pname" id="name" placeholder="Example input">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address</label>
<input type="text" class="form-control" name="eaddr" id="email" placeholder="Another input">
</fieldset>
<button class="btn btn-primary" type="submit">Take Survey</button>
</form>
It seems like the definition of overengineering to do
$.ajax({
url : '/Account/Register',
method : 'POST',
data : { pname : $('input[name="pname"]').val(),
eaddr : $('input[name="eaddr"]').val() },
});
After all, that's what a form is for in the first place!
But I do want one thing from the submission of the form and that is success and error callbacks. Is there any way to submit that form in an HTML manner and still hook up callbacks? If so, how?
Use $.submit(), this is the way you can do it with jQuery. As the other commenters wrote, you either post & refresh the page or use ajax:
$("#registration-form").submit(function(){
$.ajax({
url : '/Account/Register',
method : 'POST',
data : { pname : $('input[name="pname"]').val(),
eaddr : $('input[name="eaddr"]').val() },
success: function(data) {},
error: function() {}
});
return false;
});
let say i have the following form
<form action="post">
<label for="firstName">First name:</label>
<input id="firstName" type="text" aria-required="true" />
<input type="submit" value="submit">
</form>
and with jQuery i want to do $.post(), i use following jQuery script
jQuery(function($){
$(SUBMIT_BTN).on('click', function(e){
var data = $('form').serialize() + '&action=save_customer';
$.ajax({
url: MYRUL,
method: 'POST',
data: data,
success: function(response){
$('form').trigger('reset');
}
});
});
});
with that script the aria-required is not working any longer. how to trigger validation in this case?
PS: I want to use this aria-required, avoiding jQuery plugins
use required="required" instead of aria-required="true"
I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>
Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.
I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>