AJAX form submission - No data returned - javascript

Form:
<form action="" id="register" method="post">
<input type="text" placeholder="eg. John">
<input type="text" placeholder="eg. Appleseed">
<input type="text" placeholder="youremail#domain.com">
</form>
JS:
$('form#register').on('submit',function (e) {
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
context: this,
data : $(this).serialize(),
success: function(json) {
console.log("json: " + json);
}
});
e.preventDefault();
});
PHP:
$formData = json_encode($_POST);
echo print_r($formData,1);
... after filling the form and hitting submit, it does submit the form without an error, but the data returned (JSON) is empty:
json: []
What am I doing wrong?

This is because you are not using name attribute in your fields
serialize()
Requires name field in your form

1:-
$formData = json_encode($_POST);
echo print_r($formData,1);
should be :-
$formData = json_encode($_POST);
echo $formData;
2.You are not having name attribute in your form fields. please provide that otherwise serialize() will not work correctly.

Related

Why jQuery.ajax() is not sending any data?

Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>

PHP Ajax Submit Form Return Data

I have the following form in my HTML page:
<form id="submission" action="testresponse.php" method="post">
<input id="URL" name="URL" type="text">
<button name="Submit" type="submit">Submit</button>
</form>
testresponse.php just contains <?php print_r($_POST); ?> to print all the post variables.
I am trying to submit the form and have it return the values on the same page that the page was submitted (i.e. return the POST variables somewhere above the form)
I used the following jQuery code:
$( document ).ready(function() {
var frm = $('#submission');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log(data.responseText);
}
});
ev.preventDefault();
});
});
But for some reason data.responseText always returns blank
Is there a way to have my form send a POST request to a PHP page and return the result?
Change from
console.log(data.responseText)
to
console.log(data)

files do not post when javascript submits form

I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.
<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data" method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>
<script>
$('#editphoto form').submit(function(){
var data=$(this).serialize();
$.post('editphoto.php', data , function(returnData){
$('#editphoto').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
Files cannot be serialized. You can use FormData To submit a file using jQuery.
$('#editphoto form').submit(function(){
var formData = new FormData();
formData.append('file2', $('input[type=file]')[0].files[0]);
// append other form-data to formData object
var otherData = $(this).serialize();
$.each( otherData , function(key, field){
formData.append(field.name, field.value);
});
// post form
$.ajax({
url: 'editphoto.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function( returnData ) {
$('#editphoto').html( returnData)
}
});
return false; // stops browser from doing default submit process
})

How can we send json encoded data through ajax via form text input

I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>

Ajax form submit flow is not correct

I submit the form when trigger submit. How ever I cannot create user record. I show you the code.
<form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate="novalidate">
<input type="text" name="name" id="name" value="Amy" readonly="readonly">
<input id="fileBox" class="fileUpload" type="file" name="img" accept="image/*" required>
<input type="hidden" name="isSubmit" value="1"/>
</form>
<a id="btnSubmit" href="javascript:void(0)">Submit</a>
In js file:
$('#form_1').submit(function(){
var formData = new FormData((this)[0]);
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "isSubmit", formData: formData},
processData:false,
contentType:false,
success: function(data){
$("#thankyou").show();
}
})
return false;
});
$("#btnSubmit").click(function(){
var name = $("#name").val();
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "checkInputData", name: name}
})
.done(function(data){
data = $.parseJSON(data);
if ( data.status == 0 ){
$('#form_1').trigger('submit');
}
api.php :
if( $action == "isSubmit"){
$name= isset($_POST["name"])?$_POST["name"]:null;
createUser($conn, $name);
}
I found the the flow of the submit is not correct.
The flow of the above code is when I trigger submit then fall into success show thankyou div, but didn't create user record.
however if I removed the "return false" in ajax, the flow will becomes : trigger submit then fall into success show thankyou div then redirected to api.php then finished. In this case I can create the user record.
My target result should be I trigger submit then fall into success show thankyou div and create user record. How can I do this? And what's the differnce between having and without the "return false".

Categories