Submit a form which is in for loop - php

A form within for loop, in this form user add a excel file using input type file,
for ($i = 0; $i < 4; $i++) {
<form id="TypeValidation" method="" enctype="multipart/form-data">
<input type="hidden" id="pii_categoryid" name="pii_categoryid" value="<?php echo $i;?>" />
<div>
<span class="btn btn-rose btn-round btn-file">
<span class="fileinput-new">Select File</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="<?php echo $i;?>_attachment" id="<?php echo $i;?>_attachment" accept=".xlsx, .xls, .csv" />
</span>
<i class="fa fa-times"></i> Remove
<button type="submit" name="add_file" id="add_file" value="<?php echo $i;?>_file" class="btn btn-success btn-round fileinput-exists">Upload</button>
</div>
</form>
}
This form is submit using jquery here is code
$("#TypeValidation").on('submit',(function(e)
{
var pii_categoryid = $(this).find('input[name="pii_categoryid"]').val();
var fileUploadID = $(this).find('button[name="add_file"]').val();
e.preventDefault();
$.ajax({
url: "fn_dsr_wizard_submit.php?submitid="+fileUploadID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType: "html",
success: function (result) {
alert(result);
//prompt("Copy to clipboard: Ctrl+C, Enter", result);
location.reload();
if(result=='1'){
location.replace("ds_dashboard.php");
}else {
location.replace("ds_dashboard.php");
}
}
});
}
));
My form show like this
When user add client excel file then it is submitted but issue is that when user add donor file or other except client excel then its not submitted.

Try assign different ID and add a class name for each form like:
<form id="TypeValidation<?php echo $i; ?>" class="my-form" method="" enctype="multipart/form-data">
In javascript:
$(".my-form").on('submit',(function(e) { ...

Related

AJAX doesn't insert data into database

I have several advertisements. Each of them has a 'garage' button. If I click this button, it should insert his own userid and motorcycle id into the database. I think the insert method is good but something isn't good with the ajax. I get the success message back, but the data doesn't get inserted to my database.
<form action="" method="POST" id="upload-to-garage<?php echo $row['id']; ?>">
<div class="float-right">
<input type="hidden" value="<?php echo $row['id']; ?>" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage"></i></button>
</div>
</form>
$(document).ready(function() {
$("#upload-to-garage<?php echo $row['id']; ?>").submit(function(e) {
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function() {
alert('success');
}
});
});
});
upload-to-garage.php
<?php
session_start();
require_once("config.php");
// Add to garage
if (isset($_POST['garage'])) {
$advertId = $_POST['advert-id'];
$userid = $_SESSION['id'];
$stmt = $link->prepare("INSERT INTO garage (userid, motorcycleid) VALUES (?, ?)");
$stmt->bind_param('ii', $userid, $advertId);
$stmt->execute();
$stmt->close();
}
?>
Just checked and if I skip the AJAX part and using the simple PHP, it works fine. So the problem is with the AJAX for sure, but can't see what.
You can change your event handler like this $("form[id*=upload-to-garage]") instead of using php code for ids and then use $(this) to refer current form.Also, when you use serialize function submit button value doesn't get send so you can attach that as well using &parametername=somevalue
Demo Code :
$(document).ready(function() {
//form when submit
$("form[id*=upload-to-garage]").submit(function(e) {
console.log($(this).serialize() + "&garage=somevalue")
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $(this).serialize() + "&garage=somevalue", //use this here
dataType: "text",
success: function() {
alert('success');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" id="upload-to-garage1">
<div class="float-right">
<input type="hidden" value="1" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>
<form action="" method="POST" id="upload-to-garage2">
<div class="float-right">
<input type="hidden" value="2" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>

AJAX post form with file upload

I have this problem that i cant seem to solve, for sure is a noob thing but here it goes, i'm trying to past values and upload file using the same form, but the file is not passing to the php function.
my html with ajax:
<form name="create_batch" method="post" role="form">
<input type="hidden" name="token" value="<?= \Middlewares\Csrf::get() ?>" required="required" />
<input type="hidden" name="request_type" value="create" />
<input type="hidden" name="project_id" value="<?= $data->project->project_id ?>" />
<input type="hidden" name="type" value="batch" />
<div class="notification-container"></div>
<div class="form-group">
<label><i class="fa fa-fw fa-signature fa-sm mr-1"></i> <?= $this->language->create_link_modal->input->location_url ?></label>
<input type="text" class="form-control" name="location_url" required="required" placeholder="<?= $this->language->create_link_modal->input->location_url_placeholder ?>" />
</div>
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<label><i class="fa fa-fw fa-link"></i> <?= $this->language->create_link_modal->input->url ?>
</label>
<input type="text" class="form-control" name="url" placeholder="<?= $this->language->create_link_modal->input->url_placeholder ?>" />
</div>
<div class="text-center mt-4">
<button type="submit" name="submit" class="btn btn-primary"><?= $this->language->create_link_modal->input->submit ?></button>
</div>
</form>
<script>
$('form[name="create_batch"]').on('submit', event => {
$.ajax({
type: 'POST',
url: 'link-ajax',
data: $(event.currentTarget).serialize(),
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
dataType: 'json'
});
event.preventDefault();
})
</script>
this will post the data to the php file and the respective funtion, but only the fields are passing through. The file, that is a csv, is not passing. for sure i have something wrong on my ajax script that is only allow to pass the values of the form via post but not the file.
my php is something like this:
<?php
if(!empty($_FILES)){
$fh = fopen($_FILES['file']['tmp_name'], 'r+');
$i=0;
$lines = array();
while( ($row = fgetcsv($fh, 8192)) !== FALSE ) {
$lines[] = $row;
$location_url = $lines[$i][0];
$url = $lines[$i][1];
$umt_source = $lines[$i][2];
$utm_medium = $lines[$i][3];
$utm_campaign = $lines[$i][4];
$utm_term = $lines[$i][5];
$utm_content = $lines[$i][6];
$i=$i+1;
}
fclose($fh);
}
$_POST['project_id'] = (int) $_POST['project_id'];
$_POST['location_url'] = trim(Database::clean_string($_POST['location_url']));
$_POST['url'] = !empty($_POST['url']) ? get_slug(Database::clean_string($_POST['url'])) : false;
...........
Any help? Many thanks.
In order to send multipart form data, you need to create and send a form data object.
see example below -
var formdata = new FormData($('#formId')[0]);
$.ajax({
url: URL,
type: 'POST',
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function (response) {
$('#responseMsg').html(response.msg);
}
});
On server end you can get your data by $_POST and files by $_FILES
the solution.
$("form#create_batch").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'link-ajax',
type: 'POST',
data: formData,
dataType: 'json',
success: (data) => {
if(data.status == 'error') {
let notification_container = $(event.currentTarget).find('.notification-container');
notification_container.html('');
display_notifications(data.message, 'error', notification_container);
}
else if(data.status == 'success') {
/* Fade out refresh */
fade_out_redirect({ url: data.details.url, full: true });
}
},
cache: false,
contentType: false,
processData: false
});
});

Ajax Jquery form submit

Hello I am running a form using ajax submit functions using PHP and JS
bellow is my code
submit.php
<?php
if(isset($_POST['add_data'])){
echo "add id";
}
if(isset($_POST['update_data'])){
echo "update_id";
}
?>
Form.js
$('form.data').on('submit',function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
form.php
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
however the result I am getting is not correct if I click one of the button the console replies:
add idupdate_id
instead of one of the following
add id
or
update_id
On submit you are going to have the value set so isset will always return true. What you must do is:
if(!empty($_POST['add_data'])){
echo "add id";
}
The problem is that your form contains both add_data and update_data, so they will be always set in $_POST. If you want different action for each button, you could assign a function to the onClick event to both buttons, check which caused the event and pass it to your AJAX data.
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button" name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
Then in your JS:
$("button").click(function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data["action"] = ($(this).attr("name") === "add_data") ? 0 : 1; //If add_data -> 0 else -> 1
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
And then in your PHP, you look for $_POST["action"] variable
if($_POST["action"] == 0) {
echo "add_data";
} else {
echo "update_data";
}
EDIT: If you would like to, you don't have to check it in a condition, and just past the name attribute to data["action"] and then check in PHP, if $_POST["action"] is equal to add_data or update_data
Use next code for separating your button actions:
HTML:
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button value="add" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>Add</button>
<button value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
JS:
$('form.data > button').on('click',function(){
var info = $(this).parent(),
url = info.attr('action'),
method = info.attr('method'),
task = $(this).val(),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data['task'] = task;
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
PHP:
if(isset($_POST['task']) && $_POST['task'] == 'add'){
echo "add id";
}
if(isset($_POST['task']) && $_POST['task'] == 'update'){
echo "update_id";
}

Laravel + jQuery AJAX file upload?

I've been trying to get this done for over a week now and nothing seems to work. Users are supposed to be able to upload a file to the server with a name, but somehow AJAX is not sending anything.
This is the form where a user uploads the file:
<div class="data-attachment" data-id="">
<div class="new-attachment">
<form id="form-attachment" name="newAttachment">
<input type="text" class="attachment-name" name="name" placeholder="Name">
<input id="file" type="file" name="file" class="attachment-name">
<input type="submit" name="submit" value="Add attachment" id="submit">
</form>
</div>
<button class="btn-del">
<i class="fa fa-times"></i>
</button>
</div>
This is the function being called upon submission of the form:
$('#form-attachment').on('submit', function (e) {
e.preventDefault();
form = document.forms.namedItem('newAttachment');
formData = new FormData(form);
reader = new FileReader();
// data = {
// 'name': formData.get('name'),
// 'file': reader.readAsText($('#file')[0].files[0], 'UTF-8'),
// 'task': $('#holder').data('id')
// };
console.log(formData.get('file'));
$.ajax({
method: 'POST',
url: '/ajax/tasks/attachments/add',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function (response) {
alert(response);
// window.location.reload();
},
error: function (xhr, response, error) {
console.log(error);
}
})
});
This is the PHP code that recieves the form:
/**
* #param Req $request
*
* #return void
*/
public function addAttachment(Req $request)
{
if ($request->ajax()
&& $_SERVER['REQUEST_METHOD'] == 'POST'
&& $request->exists('file')
&& $request->exists('name')
&& $request->exists('task')
&& Auth::user()->hasRight('projects.tasks.attachments.add')
) {
$oTask = Task::find($_POST['task']);
if ($oTask) {
Request::file('file')->store(
'/'.$oTask->project->id, 'local'
);
$oTask->attachments()->create([
'name' => $request->input('name'),
'file' => $request->file('file')
]);
$oTask->project->logs()->save(
new Log(['description' => 'User ' . Auth::user()->nameFormatter() . ' added attachment ' . $_POST['name'] . ' to task ' . $oTask->name . ' in project ' . $oTask->project->name])
);
}
}
}
The files serve as attachments to tasks, hence the 'task' index.
I've searched through multiple similar questions and tried to apply codes from the answers but nothing seems to work. Any help or a point to the right direction is appreciated!
I see it didnt submit the file because your form is locking of enctype="multipart/form-data"
<div class="data-attachment" data-id="">
<div class="new-attachment">
<form id="form-attachment" name="newAttachment" enctype="multipart/form-data">
<input type="text" class="attachment-name" name="name" placeholder="Name">
<input id="file" type="file" name="file" class="attachment-name">
<input type="submit" name="submit" value="Add attachment" id="submit">
</form>
</div>
<button class="btn-del">
<i class="fa fa-times"></i>
</button>
</div>
also try just appending into your formData
if ($("#file")[0].files > 0) {
var file = $("#file")[0].files[0];
formData.append("file", file, file.name);
}

submitting two forms via javascript without click

i am using the following code to auto-submit a form
<script type="text/javascript">
$(function () {
$('#submit').click();
});
</script>
<div style="display:none">
<form method="post" action="http://mydomain/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form>
</div>
i want to submit the same data to two urls ...
http://mydomain/texting/register.php?list_id=15
http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>
how can edit my code to submit same form data automatically?
i tried this code
<script type="text/javascript">
function submitTwice(f){
f.action = 'http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>';
f.target='ifr1';
f.submit();
f.action = 'http://mydomain.com/texting/register.php?list_id=15';
f.target='ifr2';
f.submit();
}
</script>
*/
<script type="text/javascript">
$(function () {
$('submitTwice(f)').click();
});
</script>
<div style="display:none">
<iframe name="ifr1" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
<div style="display:none"><iframe name="ifr2" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
but it is not working, any suggestion to make it happen, the same data is to be sent to both the urls automatically using javascript
You can use jQuerys ajax and send the data with post, to both the urls.
first save all data you want to send in an valid data array. if you want it automated, you can do something like this:
var sendData = {};
$("#formId").find("input").each(function(i, item){
sendData[item.name] = item.value;
});
or as a simple string:
var sendData = "name=value&email=value";
then send the form data to both urls with ajax, as post type:
$.ajax({ url: "http://url1/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
$.ajax({ url: "http://url2/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
Note: make sure to return false to the button or sending form, you can do that something like:
$("formId").submit(function(){
// do ajax send data
return false;
}
EDIT: added unchecked code for this, with comments
$(document).ready(function(){
// grab the form and bind the submit event
$("#formId").submit(function(){
// collect all the data you want to post
var sendData = {};
this.find("input").each(function(i, item){
sendData[item.name] = item.value;
});
// send the request to both urls with ajax
$.ajax({ url: "url1", type: "POST", data: sendData,
success: function(response){
// handle response from url1
alert(response);
}
});
$.ajax({ url: "url2", type: "POST", data: sendData,
success: function(response){
// handle response from url2
alert(response);
}
});
// return false, to disable default submit event
return false;
});
});
just send name and email to the server script in a regular form,
then do two requests from within your register.php with something like HttpRequest or the like...
some freehand code:
client:
<form id="autoSubmitForm" method="post" action="/register.php?list_id=15">
<input type="hidden" name="name" value="<?php data['name2']; ?>" />
<input type="hidden" name="email" value="<?php data['email2']; ?>" />
<input type="submit" name="submit" value="Sign Up" style="visibility:hidden;" />
</form>
<script>
$(document).ready(function(){
$('#autoSubmitForm').submit();
});
</script>
server:
<?php
$name = $_POST["name2"];
$email = $_POST["email2"];
$url1 = 'http://lala'; //or relative to server root: '/lala'
$url2 = 'http://other';
sendRequest($url1, $name, $email);
sendRequest($url2, $name, $email);
?>
The implementation of sendRequest is worth another question (or reading the documentation of HttpRequest mentioned above)
Good luck, I see your duplicate question got closed...

Categories