post a form with many fields and JS var - javascript

I want to post my form by ajax to php then get values from inputs ( I did it and it works fine ) but I also want to post a JS variable i one ajax.
There is my FORM section.
<form action="new_alias.php" method="post" id="theForm">
<div class="form-group">
<label for="exampleInputEmail1">Wpisz nazwę aliasu</label>
<input type="text" name="alias" id="alias" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp" placeholder="Nazwa aliasu">
</div>
<div class="form-group">
<label class="col-form-label">Wybierz domenę</label>
<?php
if ($resultt->num_rows > 0) {
echo '<select name="name" class="custom-select">';
// output data of each row
while ($row = $resultt->fetch_assoc()) {
echo "<option value='$row[name],$row[id]'>$row[name]</option>";
}
echo '</select>';
} else {
echo "0 results";
}
?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Wpisz adresy docelowe</label>
<input type="text" name="source" id="source" placeholder="Adresy mailowe" autocomplete="nope"
autocomplete="off" class="typeahead tm-input form-control tm-input-info" />
</div>
<button type="submit" name="add" id="add" class="btn btn-primary mt-4 pr-4 pl-4">Utwórz</button>
</form>
and there is my script
<script>
$(document).ready(function () {
var tagApi = $(".tm-input").tagsManager({
hiddenTagListName: 'hiddenTagListA'
});
var x = '';
var test = '';
jQuery(".typeahead").typeahead({
name: 'source',
displayKey: 'source',
source: function (query, process) {
return $.get('ajaxpro.php', {
query: query
}, function (data) {
data = $.parseJSON(data);
console.log(data);
return process(data);
});
},
afterSelect: function (item) {
tagApi.tagsManager("pushTag", item);
x = document.getElementsByName("hiddenTagListA");
test = x[0].value;
console.log('to jest z afterSlect: ', test);
}
});
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
$("#theForm").serialize()
},
success: function () {
alert("Form Submitted: ");
},
});
});
});
</script>
I am using tagsManager which created hidden input with ID hiddenTagListA
I am trying to put all values from hiddenTagListA to var testand it works.
But now I want to post this variable also to my php because I want to put it into my DB. Taking all values from form woks but I must also post test variable.
In my console I am getting value from test like: something, something2, something3... ( tags separated by comma) It can be just string

If you use .serialize then you need to parse the string first to get posted data using AJAX. PHP function parse_str reads string & convert that into array.
Refer: http://php.net/manual/en/function.parse-str.php
You can use .serializeArray function instead of .serialize which make sure to give data in array format, which is easily retrievable in PHP using $_POST variable.
JS CODE
$(".btn").click(function (e) {
e.preventDefault();
var inputData = $("#theForm").serializeArray(); // .serializeArray gives data in array format instead of string format.
// you can insert new variables like below
inputData.push({"name":"hiddenTagListA", "value": document.getElementsByName("hiddenTagListA")[0].value});
$.ajax({
type: "post",
url: 'new_alias.php',
data: inputData,
success: function () {
alert("Form Submitted: ");
},
});
});

if you got the value in test, just put it in ajax
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
form: $("#theForm").serialize(),
hiddenTagListA: test
},
success: function () {
alert("Form Submitted: ");
},
});
});

Related

File type data not getting in the process page

I am adding the file type dynamically which is working but when I click on submit then I am getting only the first filename in the process page. how to get all the file name in process page? I tried var_dump($_FILES) to check but it is displaying only the first file name.
then I notice that if I remove numberIncr from the name ( name="workpic[]' + numberIncr + '" ) then it's working but my validation not working.
Process.php
if(isset($_FILES)){
echo"<pre>";
//var_dump($_FILES) ;
print_r($_FILES['workpic']['name']);
foreach($_FILES['workpic']['name'] as $key=>$val){
$fileName = basename($_FILES['workpic']['name'][$key]);
print_r($fileName);
}
}
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
//var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
// var addrm = '';
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
$(".medication_info").append(' <input type="file" name="workpic[]' + numberIncr + '" class="dynamicVal"><br />');
x++; //Increment field counter
numberIncr++;
}
// count++;
});
});
$('#register').on('submit', function(event) {
event.preventDefault();
// adding rules for inputs with class 'comment'
$('.dynamicVal').each(function() {
$(this).rules("add", {
required: true
})
});
// test if form is valid
if ($('#register').validate().form()) {
var formData = new FormData(this);
$.ajax({
//url:"process.php",
url: "process2.php",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("success");
},
}); // AJAX Get Jquery statment
}
//alert('hellow');
});
$('#register').validate({
errorPlacement: function(error, element) {
if (element.is("select")) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
<div id="clicktoadd">Add More</div>
<form action="#" method="post" id="register" name="register" enctype="multipart/form-data">
<div class="row">
<div class="medication_info">
<input type="file" name="workpic[]" class="dynamicVal"><br />
</div>
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
Can anyone help me out with this issue?
I am getting this output but I added 3 images and it's displaying only one.
Array
(
[0] =>bTml75QAfHo-unsplash.jpg
)
Would you help me out in this issue?
You shouldn't put numberIncr after name=workpic[]. Using a name ending in [] will automatically make it an array in PHP. So just do:
$(".medication_info").append(' <input type="file" name="workpic[]" class="dynamicVal"><br />');
If you need to give specific indexes, rather than letting them automatically increment from 0, you should put the index inside the [] rather than after it.
$(".medication_info").append(' <input type="file" name="workpic[' + numberIncr + ']" class="dynamicVal"><br />');
I inspected the form data being send when there are multiple input type="file" added with following code
var formData = new FormData(this);
console.log([...formData.entries()]);
Here's the structure
[
[
"workpic[]",
{
...
}
],
[
"workpic[]1",
{
...
}
],
[
"workpic[]2",
{
...
}
]
]
Based on that you can access files following way
print_r($_FILES['workpic[]']['name']);
print_r($_FILES['workpic[]1']['name']);
print_r($_FILES['workpic[]2']['name']);
Or
foreach($_FILES as $file){
echo $file['name'];
}

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>

Inserting data of multiple fields into database table using FormData Class of JS?

I need to insert data into MySql database table Using ajax and FormData Class. I can easily solve my this issue with declaring many variables for many <input> using jquery And then put these variables for checks in if-else syntax. But what I need is to use FormData class of JavaScript and I distribute my code in 3 files:
action_project.php
<?php
require_once("../config.php");
include(CLASSES_PATH.DS.'project.php');
$objProject = new Project();
if(isset($_POST)) {
$product = isset($_POST['product'])?$_POST['product']:'';
$customer = isset($_POST['cutomer'])?$_POST['cutomer']:'';
echo $objProject->AddProject($customer,$product);
?>
project.php
class Project
{
private $mysqli_lib;
function __construct()
{
global $obj_mysql;
$this->mysqli_lib = $obj_mysql;
}
function AddProject($customer,$product)
{
$query = "INSERT INTO tbl_project_detail(customer,product) VALUES ('$customer','$product')";
$response = $this->mysqli_lib->insert($query);
return $response > 0 ? "success" : "fail";
}
}
project_view.php (for the sake of clarity i get rid of some html element tags)
<form method="post" class="form-horizontal" id="fieldsform" enctype="multipart/form-data" action="" style="clear:both">
<input type="text" class="form-control" name="product" value="product"
id="product">
<input type="text" class="form-control" name="customer" value="customer"
id="product">
<button type="submit" class="btn btn-primary" name="btnQuoSave" id
="btnQuoSave">Save</button>
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '#btnQuoSave', function () {
var formdata = new FormData($('#fieldsform')); //I need to figure out this line of code to work, i think.
$.ajax({
type: "POST",
url: "../includes/ajax/action_project.php",
async: true,
contentType: false,
processData: false,
cache: false,
data: formdata,
success: function(data){
data = data.trim();
//console.log(data);
//alert(data);
if(data == 'success'){
alert('sucess');
}else if(data == 'fail'){
alert('fail');
}
}
});
});
});
So My Questing is How should i insert data into MySql database table Using ajax and FormData Class?

How to obtain response from form submitted by AJAX?

I want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com
In that case I have simple script
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize(),
success: function () {
swal('Great success!');
}
});
});
});
and form
<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
<div class="form-group">
<label class="sr-only" for="user_name">Email address</label>
<input id="user_name" type="text" name="user[name]" value="" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="user_email">Password</label>
<input id="user_email" type="text" name="user[email]" value="" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Sign Up!</button>
<input type="hidden" name="user[html]" value="1" />
<input type="hidden" name="acyformname" value="formAcymailing1" />
<input type="hidden" name="ctrl" value="sub"/>
<input type="hidden" name="task" value="optin"/>
<input type="hidden" name="redirect" value="https://example.com"/>
<input type="hidden" name="option" value="com_acymailing"/>
<input type="hidden" name="visiblelists" value=""/>
<input type="hidden" name="hiddenlists" value="1"/>
</form>
Everything works fine except success, error states...
Joomla Acymailing have sub.php file to handle ajax responses
if($config->get('subscription_message',1) || $ajax){
if($allowSubscriptionModifications){
if($statusAdd == 2){
if($userClass->confirmationSentSuccess){
$msg = 'CONFIRMATION_SENT';
$code = 2;
$msgtype = 'success';
}else{
$msg = $userClass->confirmationSentError;
$code = 7;
$msgtype = 'error';
}
}else{
if($insertMessage){
$msg = 'SUBSCRIPTION_OK';
$code = 3;
$msgtype = 'success';
}elseif($updateMessage){
$msg = 'SUBSCRIPTION_UPDATED_OK';
$code = 4;
$msgtype = 'success';
}else{
$msg = 'ALREADY_SUBSCRIBED';
$code = 5;
$msgtype = 'success';
}
}
}else{
if($modifySubscriptionSuccess){
$msg = 'IDENTIFICATION_SENT';
$code = 6;
$msgtype = 'warning';
}else{
$msg = $modifySubscriptionError;
$code = 8;
$msgtype = 'error';
}
}
if($msg == strtoupper($msg)){
$source = acymailing_getVar('cmd', 'acy_source');
if(strpos($source, 'module_') !== false){
$moduleId = '_'.strtoupper($source);
if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
}
$msg = acymailing_translation($msg);
}
$replace = array();
$replace['{list:name}'] = '';
foreach($myuser as $oneProp => $oneVal){
$replace['{user:'.$oneProp.'}'] = $oneVal;
}
$msg = str_replace(array_keys($replace),$replace,$msg);
if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);
if($ajax){
$msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
}elseif(empty($redirectUrl)){
acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
}else{
if(strlen($msg)>0){
if($msgtype == 'success') acymailing_enqueueMessage($msg);
elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
else acymailing_enqueueMessage($msg,'error');
}
}
}
And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub
message Subscribe confirmed
type success
code 3
{"message":"Subscribe confirmed","type":"success","code":"3"}
The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?
this simple change may do it for you:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize()
}
}).done(function (data) {
swal('Great success!');
});
});
});
I personally like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
swal('Great success!');
});
since your result is in JSON, that should be more like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
console.log(data); // shows full return object in console
swal('Great success!');
}, "json");
Try the following, I have explained the changes inside comments:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
$.ajax({
type: 'post',
dataType: 'json', //because your data is json
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: formdata,
success: function (d) {//d is the return/response of your url (your question answer)
swal(
d.type+': '+d.code ,
d.message,
d.type
);
},
error: function(d){
swal(
'Oops..' ,
'Something went wrong!', //your json must be in trouble
'error'
);
console.log(d); //delete this in production stage
console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
}
});
});
});
I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
}
to
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
header("Access-Control-Allow-Origin: *");
}
so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :
<input type="hidden" name="ajax" value="1" />
so to allow ajax request by your joomla controller file.
now in your success block of ajax you can make a check something like this :
success:function(data, status, xhr){
var json = $.parseJSON(data);
swal(json.message, json.type);
}
I hope this will help you in acomplishing what you want to, Happy coding.
I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.
e.g. success(html)
and
console.log(html)
this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .
Simple solution to your question is :
success: function (data) {
$("#<id_of_tag>").html(data);
}
data : Response returned from the server to your AJAX call
id_of_tag : where you want to display your returned output.
Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.
To answer your question: On Success parameter in function will contain your response.
As in my case, i am returning another JSP page, which i want to display in div tag.
Also check below link : I think it might help you
Best way to check if AJAX request was successful in jQuery

Pass view as data to js in symfony

I am tryng to implement a search function in my index page using java script. I hav got a form to enter the name and when apply serach, the index page will get updated and load the new index page with the search results
Here is the form in my index page
<div id="content">
<form id="myForm" action="{{path('index_search')}}" method="POST" >
Write your name here:
<input type="text" name="name" id="name_id" value="" /><br />
<input type="submit" value="Send" />
</form>
</div>
<div id="output">#current index</div>
Here is the action exexcuted
public function searchAction()
{
$request = $this->get('request');
$name=$request->request->get('formName');
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('SystemVmsBundle:VisitorsDetails')->findOneByfirstname($name);
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
$return=array("responseCode"=>200, "view"=>$view);
$return=json_encode($return);//jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));
}
Here is the js
$(document).ready(function() {
//listen for the form beeing submitted
$("#myForm").submit(function(){
//get the url for the form
var url=$("#myForm").attr("action");
$.post(url,{
formName:$("#name_id").val(),
other:"attributes"
},function(data){
//the response is in the data variable
if(data.responseCode==200 ){
$('#output').html(data.view);
$('#output').css("color","red");
}
else{
alert("An unexpeded error occured.");
}
});
return false;
});
});
However my js is working,but can not pass data as view to the js.How to pass the view 'index.html.twig' to the js?
When inspects with firebug,i got like
{"responseCode":200,"view":{"headers":{}}}
Any ideas?Thanks in advance!
Try to specify the dataType on your $.post function, like this:
$.post(url, {formName: $("#name_id").val(), other: "attributes"},
function(data) {
if(data.responseCode == 200){
$('#output')
.html(data.view)
.css("color","red");
} else {
alert("An unexpeded error occured.");
}
}, 'json');
But If you only need the html, not other data inside the json, you should change the logic, render a normal template and use dataType 'html'. goes like this:
// ...Controller.php
$view = $this->render('SystemVmsBundle:VisitorsDetails:index.html.twig',array(
'entities' => $entities,
));
return new Response($view);
// index.html.twig
$.ajax({
url: url,
dataType: 'html',
type: 'POST',
data: {formName: $("#name_id").val(), other:"attributes"},
success: function (data) {
$('#output').html(data).css("color","red");
}
});

Categories