How to get data from html form? - html

What is the most modern way to get data from an html form and email it to yourself?

One way could be to have a JQuery .sumbit() event handler on your submit button which would gather all the info from the form and send them to a backed controller which would actually send the email.
JQuery example:
$('form').submit(function(event) {
// get the form data
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'phone' : $('input[name=phone]').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode: true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
});
event.preventDefault();
});
The server side could look something like:
<?php
// process.php
$errors = array();
$data = array();
// Validation
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['phone']))
$errors['phone'] = 'phone is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
// Send email here
$data['success'] = true;
$data['message'] = 'Success!'
}
?>
In this way you would decouple client side logic (gather form data) and backend logic (send the email).

Related

Symfony form & Ajax

I am working on Symfony 4.4.
To refresh a table, users select three options with an input:
InProgress
Finished
All
Then they must press a validate button.
I want to improve the use of this page by automating the refresh of the table.
Currently on my model I have AJX which allows me to retrieve the value of my entry:
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data[$field.attr('name')] = $field.val()
console.log(data)
// On soumet les données
// $.post($form.attr('action'), data).then(function (data) {
// // On récupère le nouveau <select>
// $('#planningsms_client_label').val($(data).find('#planningsms_client option:selected').text());
// let $input = $(data).find(target)
// // On remplace notre <select> actuel
// $(target).replaceWith($input)
// })
});
</script>
I am now stuck because I cannot figure out how to get information back to my Controller, allowing me to modify a PreSelect variable with the value of the input and change the structure of the SQL query.
Create a route? Call a route in an Ajax POST?
Use this route in my Controller?
I think it's more or less that, but on the other hand I have no idea how to implement it.
EDIT :
It has moved forward a bit.
I manage to recover the data of the change of the input in my controller.
On the other hand I try to recall the function which will allow me to make a new SQL query with the selected filter, but that does not seem to work.
Ajax :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
And function in my controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if(isset($request->request)) {
$preSelect = $request->request->get('isAttending');
return $this->queryFollowingFilter($preSelect);
}
// return $this->queryFollowingFilter($preSelect);
return new JsonResponse(array(
'status' => 'OK'),
200);
}
Error :
The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned an array
As the error message states:
The controller must return a "Symfony\Component\HttpFoundation\Response" object
A JsonResponse meets that requirement and suits your needs. Try this:
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200
);
}

My Ajax script not work with datatype json

In my codes, i could post data without error. but i cant return data from php file to show in my html tag. If i delete dataType: 'json', it works fine but as you know i cant get data. I get this error while datatype = json
error : {"readyState":4,"responseText":"<head>\n<meta charset=\"UTF-8\">\n</head>\n-1","status":200,"statusText":"parsererror"}
My ajax;
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like"){
type = 1;
}else{
type = 0;
}
// AJAX Request
$.ajax({
url: 'likeunlike.php',
type: 'post',
data: {baslikid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likesonuc'];
$("#sonuc_"+postid).text(likes); // setting likes
if(type == 1){
$("#like_"+postid).css("color","#ffa449");
$("#unlike_"+postid).css("color","lightseagreen");
}
if(type == 0){
$("#unlike_"+postid).css("color","#ffa449");
$("#like_"+postid).css("color","lightseagreen");
}
},
error: function(data){
alert("error : " + JSON.stringify(data));
}
});
});
});
My php file(I didnt share above to avoid confusion. I get int result from $likesonuc)
$likesonuc= $total_likes - $total_unlikes;
echo json_encode($likesonuc);
In your response, you can see that the body you're returning from PHP:
<head>\n<meta charset=\"UTF-8\">\n</head>\n-1
...is not JSON. It looks like you're writing out the head of the HTML somewhere and then the JSON number -1. You need to send just the JSON in your response or it can't be parsed as JSON.

Submitting Serialized JSON to a Servlet

I can successfully serialize the form and submit it to a text area in the form, but don't know how to send it to a Servlet that I have already created/defined:
// Prepare form for Serialize
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// Send JSON Data to ResultSet
$(function() {
$('form').submit(function() {
//submitting to textarea "resultset"
//needs to submit to servlet "SftpConnTest" as defined in web.xml
//$('#ResultSet').text(JSON.stringify($('form').serializeObject()));
//?? HOW DO I SEND TO "SftpConnTest" SERVLET instead??
return false;
});
});
Use following to send form data via ajax to server:
$.post("path/to/servlet", $("#formId").serializeArray(), function (result) {
// do something
});
By the way:
serializeArray() will convert a form to an array, which could be used directly as the "data" param of a jquery ajax request, only element that has a name property in the form will be included into the data,for details please check jquery api, it's very clear there.
Assuming you are sending this to the servlet using an HTTP POST, you can use ajax:
$(function() {
$('form').submit(function(evt) {
evt.preventDefault(); // prevent the default form submit behavior
var data = $('form').serializeObject();
$.post(
'/',
data,
function(resData, status, req) {
$('#ResultSet').text(JSON.stringify(resData));
}
);
}
}
If the servlet is not mapped to be located at the root of the web app, replace 'SftpConnTest' in the $.post function with the relative path to the servlet. For example, if the servlet is mapped to /foo/bar/SftpConnTest, then you should have '/foo/bar/SftpConnTest' instead of 'SftpConnTest'.
See the jQuery docs for more information on the $.post function.

How to access JSON object property from data returned by AJAX call?

I'm making an AJAX call to this php file:
<?php
$result = array('error' => "Please enter a valid name");
echo json_encode($result)
?>
In my javascript file, I have:
$.ajax({
type:"POST",
url:"/controller/common/review_processing.php",
data:dataString,
success:function (data) {
var returned_data = data;
console.log(returned_data); <---This outputs {"error":"Please enter a valid name"}
console.log(returned_data.error); <---This outputs undefined
}
});
My data seems to be encoded as a JSON object correctly but when I try to access a specific property, I get an undefined result.
What I want is for console.log(returned_data.error) to output:
Please enter a valid name
What am I doing wrong?
Please try :
$.ajax({
type:"POST",
url:"/controller/common/review_processing.php",
data:dataString,
dataType: "json", <--response itself will be handled as JSON
success:function (data) {
var returned_data = data;
console.log(returned_data); <---This outputs {"error":"Please enter a valid name"}
console.log(returned_data.error);
}
});
Try using this...
$.map(data.d, function (item) {
console.log(item.error);
});

Post array is missing json from ajax request

I'm trying to make a dynamic document previewer. The user can input certain document header options and based on their account information it will generate a document with a dynamic header. I eventually want to preview a full pdf but I am working on just the header right now.
What I am trying to do is make a page with a form that the user can fill out, then press a button to preview the header.
$.ajaxSetup({
type: 'POST',
timeout: 10000
});
$("#preview_header").click(function(){
var full_url = //appropriate URL
var preview_data = {
"wsid": "default",
"page": "default",
"banner_area1": "default",
"banner_area2": "default",
"banner_area3": "default",
"uid": "default",
"fid": "default",
"cid": "default",
"assignment_type": "default"
};
preview_data.wsid = $("#worksheet_picker").val();
preview_data.page = $("#page_picker").val();
preview_data.banner_area1 = $("#banner_area1").val();
preview_data.banner_area2 = $("#banner_area2").val();
preview_data.banner_area3 = $("#banner_area3").val();
preview_data.uid = $("#member_uid").val();
preview_data.fid = $("#family_id").val();
preview_data.assignment_type = 'family';
preview_data.cid = $("#class_id").val();
var JSONText = JSON.stringify( preview_data );
alert('Full JSON - ' + JSONText);
$.ajax({
async: true,
url: full_url,
data: { previewInfo : JSONText }, //Passes necessary form information
dataType: 'json',
success: function(output){
var reply = output;
if ( reply.status == "success" ){
$("#preview").attr("src", reply.image );
} else {
alert('Failed to create image preview of the assignment.');
}
}
});
});
As far as I can tell, the above method is working fine. It hits the right Codeigniter page and when the ajax method is set to return a hard coded image it works just fine. The AJAX seems to be well formatted but just in case here is what it outputs when I fill out forms with the corresponding values:
Full JSON - {"wsid":"4","page":"1","banner_area1":"link1",
"banner_area2":"link2","banner_area3":"link3",
"uid":"1","fid":"1","assignment_type":"family"}
So first off, let's start with what is working in the corresponding controller method for the ajax reply:
$data = array(
'status' => 'success',
'image' => //static image link
);
$this->output->set_content_type('text/javascript;charset=UTF-8');
echo json_encode($data);
But whenever I try to modify it like so:
$preview_data = json_decode($this->input->post('previewInfo'));
//Got this one
mail('me#gmail.com', 'Start Email', 'Some email' );
//Empty email
mail('me#gmail.com', 'Dump Post', var_dump($_POST));
//Empty email
mail('me#gmail.com', 'Post data', var_dump($preview_data) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data', print_r($this->input->post()) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data',
print_r($this->input->post('previewInfo')) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data', print_r($preview_data) );
$data = array(
'status' => 'success',
'image' => //static image link
);
$this->output->set_content_type('text/javascript;charset=UTF-8');
echo json_encode($data);
The modified one doesn't return the static data either. So it would seem that the post array is not being intialized properly. Anyone see the bug?
If you want to send your Ajax request with the post method, you need to set type to POST in your $.ajax options.
Also, async is true by default, so setting it is not necessary. Additionally, you should consider using .done and .fail as opposed to success and fail, as they are slated to be deprecated very soon.
Like so:
$.ajax({
type: "POST",
url: full_url,
data: { previewInfo : JSONText }, //Passes necessary form information
dataType: 'json'
}).done(function (output, textStatus, jqXHR) {
var reply = output;
if ( reply.status == "success" ){
$("#preview").attr("src", reply.image );
} else {
alert('Failed to create image preview of the assignment.');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// now you have the XHR, text status, and error to debug with
});
There was 2 problems that lead to the solution to this problem:
1)
As Austin and Gavin said: var_dump and print_r should not be outputting to the browser.
The solution was to debug with firefox extensions / chrome.
2)
$preview_data = json_decode($this->input->post('previewInfo'));
was changed to
$preview_data = json_decode($this->input->post('previewInfo'), true);
The secondy optional parameter of json_decode is to tell the method whether you are expecting an associative object or a list of things. As it happens, I was reading in and wanted an associative array.