This is my form:
<form id='forma' action="index1.php" method="post">
<input name="name1" type="text">
<input class="s_submit" value="ЗАКАЗАТЬ" type="button" onclick="send1()">
</form>
This is my javascript:
function send1(){
$('#forma').submit(function(event){
var formData = {
'fio' : $('input[name=name1]').val(),
};
$.ajax({
type : 'post',
url : 'index1.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
}
This is my index1.php:
$fio=$_POST['name1'];
$mail_to="_______my_email_________";
$msg="Your name is: $fio
mail($mail_to, $thm, $msg, $headers);
On my e-mail only "Your name is:" message is sent, without the name someone submitted. Code works as expected when I set input type to submit and get rid entirely of send1() function. But input must be the button type and never go to another page on press. I suppose I should get rid of some of variable assignments, but which ones?
Your variable in the POST data is defined in formData object with the key of fio. Your PHP to retrieve it should therefore be:
$fio = $_POST['fio'];
On the form submission, you are overriding the actual form (containing your text field) from being submitted, and submitting your own formData object.
You can quite easily get the data from your HTML form by using
$("#forma").serializeArray()
Related
This would be a follow-up of question [A form's “action” and “onsubmit”: Which executes first?][1]
where it's concluded that onSubmit runs first, and then the action to submit a form is done.
I would like to compose my onSubmit method to clean up the POST submission that will be sent; is there a way to modify said POST message that will be sent to the server, not by changing the values of the fields, but rather the composition of it?
As an example, my form consists of two fields, name and surname. The submit action ends up sending a POST body like:
name=John&surname=Doe
But I'd like the POST body to be
fullname=John_Doe
I am actually stuck without an idea of how to approach this problem, so any hint on where to look for documentation about this is appreciated - I don't want to leech the code that will do it, but some hint of where to start.
Thanks!
[1]: A form's "action" and "onsubmit": Which executes first?_
You can achieve this by modifying form-data before sending the request.
But you need to send the request yourself.
const form = document.querySelector("form");
form.addEventListener("submit", e => {
e.preventDefault();
let preparedData = new FormData(form);
preparedData.append(
"fullName",
`${preparedData.get("firstName")} ${preparedData.get("lastName")}`
);
console.log("Fullname: " + preparedData.get("fullName"));
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(preparedData);
});
Example:
https://stackblitz.com/edit/js-yia2yg?file=index.js
To stop the form action you can call a onSubmit method:
<form action="/action_page.php" onsubmit="myFunction()">
Enter first name: <input type="text" name="fname">
Enter last name: <input type="text" name="lname">
<input type="submit" value="Submit">
</form>
function myFunction(evt) {
evt.preventDefault();
let data = {
fullname: //place the data you need to send here
};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
};
I want to send an image and a number when the user perform an upload.
My Javascript
form.append('file', $(uploader).get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
$.ajax({
method: 'POST',
url: '/images/send',
data: form,
form: false,
processData: false
});
In my action what should I do?
With this I only receive the image.
[HttpPost]
public string send(IFormFile file) // What argument should I use
{
How do I get the number and file?
}
You can add a new parameter of type int to your action method. The parameter name should match with the formdata item name you are sending (id)
[HttpPost]
public string send(IFormFile file,int id)
{
// to do : return something.
}
You need to have the contentType property on your $.ajax method set to false
This should work.
var form = new FormData();
form.append('file', $('#File').get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
var urlToPost ="/images/send";
$.ajax({
method: 'POST',
url: urlToPost ,
data: form,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
}).fail(function(a, b, c) {
alert("error");
});
If you want to send multiple input values with the file input, i suggest you create a view model and use that as explained in this post.
Also it might be a good idea to keep your form elements inside a form and set it's action value to the url you want to send and read that in your javascript code that hard coding it there.
<form asp-action="send" asp-controller="images" method="post">
<input type="file" name="File" id="File" />
<input type="text" id="id" value="0" />
<input type="submit" />
</form>
Now in your javascript you can read it from the form. For example, if you are wiring up the submit event of the form
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var urlToPost = $(this).attr("action");
//your existing code for ajax call
});
});
This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})
My form function is written in PHP and is expecting two variables to be passed. I have to submit the form and the variables using Javascript though. I understand I can use .submit() to actually submit the form using JavaScript but the variables that need to be passed to my form function are stored in two variables within my JavaScript. I'm having trouble understanding how to pass those JavaScript variables when I submit the form using .submit().
One idea that I have is adding hidden fields to my html form and setting the value of those hidden input values to what I have in my JavaScript variables.
I'm wondering if there is a way to to use .submit() and pass the variables via JavaScript?
Checkout FormData for a plain vanilla JS solution without jQuery:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
There are examples how to use it with an existing form:
JS:
var docFormElement = document.getElementById('myForm');
var docFormData = new FormData(docFormElement);
docFormData.append("product_license","Enterprise");
var xhrObject = new XMLHttpRequest();
xhrObject.open("POST","postform.cfm");
xhrObject.send(docFormData);
HTML:
<form id="myForm">
<input name="product_name" type="text" value="ColdFusion" />
<input name="product_codename" type="text" value="Zeus" />
</form>
You can either keep a hidden input or a javascript variable to keep track of values. You can then use AJAX to submit values to PHP page :
<input id="name" type="hidden" .....
....
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
success: function() {
//do something
}
});
details:
http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
Alternatively you can just update the hidden input values and submit the form:
<script type="text/javascript">
function submitform()
{
document.forms["formID"].submit();
}
</script>
<form id="formID" action="somepage.php">
Search: <input type='hidden' name='email'>
Submit
</form>
after submit the form using ajax i cant set the value on the multiple textbox correctly, here's my form
<form id="searchForm" action="process.php" method="post">
<input id="cust_code" name="cust_code" required>
<input id="cust_code1" name="cust_code1" disabled>
<input id="cust_name" name="cust_name" disabled>
<button type="submit">Search</button>
</form>
process.php
$cust_code = $_POST['cust_code'];
$result = mysql_query("SELECT code,cust_name FROM information WHERE code=$cust_code") or die(mysql_error());
$data = mysql_fetch_array($result);
javascript:
var formData = {
'cust_code': $('#cust_code').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true,
success: function(data) // recieved data from process.php
{
var code = data[0];
var cust_name = data[1];
// Update id value
document.getElementById('cust_code').value = code;
document.getElementById('cust_code1').value = code;
document.getElementById('cust_name').value = cust_name;
}
})
the value of cust_code and cust_code1 changed after submit, but not for cust_name
any ideas?
EDIT: the id's has been use on another page(php include) so that make the input wont change, solved!
You can assign value by this way also in JQuery:
document.getElementById('cust_code').val(code);
or
document.getElementById('cust_code').attr('value',code);
The same IDs have been used on another page(php include) so the input value won't change, changing the ID to cust_names seems to do the trick