Error 400 when submitting a form with an input checkbox - html

I have this form:
<form id="formUpload" action="/php/upload.php" name="formUpload" method="post" enctype="multipart/form-data">
<div class="row mb-3">
<label for="target" class="col-sm-3 col-md-2 col-form-label">Type</label>
<div class="col-sm-4">
<select class="form-select" name="target" aria-label="Target" required>
<option value="config" selected>Configuration</option>
<option value="app">Application</option>
<option value="media">Content</option>
<option value="sys">System</option>
</select>
</div>
<div class="col-auto">
<div class="col-form-label form-check">
<input class="form-check-input" type="checkbox" name="incremental" value="true" checked >
<label class="form-check-label" for="incremental">Incremental</label>
</div>
</div>
</div>
<div class="row mb-3">
<label for="id-type" class="col-sm-3 col-md-2 col-form-label">Target ID</label>
<div class="col-sm-4">
<select class="form-select" name="id-type" aria-label="Mode">
<option value="broadcast" selected>Broadcast</option>
<option value="target">Target</option>
</select>
</div>
<div class="col-sm-4 col-lg-3">
<input type="text" class="form-control" name="id" disabled required>
</div>
</div>
<div class="row mb-3">
<label for="id" class="col-sm-3 col-md-2 col-form-label">Revision</label>
<div class="col-sm-4 col-md-3 col-lg-2">
<input type="number" class="form-control" name="revision" min="1" max="999" value="1" required>
</div>
</div>
<div class="row mb-3">
<label for="upload_file" class="col-sm-3 col-md-2 col-form-label">Package</label>
<div class="col-sm-9 col-md-10">
<input type="file" class="form-control" name="file" accept=".zip" required>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Upload"/>
</form>
and this JavaScript:
function uploadFile() {
const action = $("#formUpload").attr("action");
const bar = $("#progressUpload");
const dialog = $("#modalUpload");
const alertOk = $("#alertUploadOk");
const btnClose = $("#btnClose");
const btnAbort = $("#btnAbort");
dialog.modal("show");
btnClose.prop("disabled", true);
btnAbort.prop("disabled", false);
const formData = new FormData($("#formUpload")[0]);
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
$.ajax({
xhr: function() {
window.xhr = xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
console.log("progress");
const percentComplete = Math.floor(e.loaded / e.total) * 100;
const percentVal = percentComplete + '%';
bar.width(percentVal)
bar.html(percentVal).attr('aria-valuenow', percentVal);
}
}, false);
xhr.addEventListener('abort', function(e){
btnClose.prop("disabled", false);
btnAbort.prop("disabled", true);
}, false);
return xhr;
},
type: 'POST',
url: action,
data: formData,
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
let percentVal = '0%';
bar.width(percentVal)
bar.html(percentVal).attr('aria-valuenow', percentVal);
},
success: function(data, status, xhr) {
let percentVal = '100%';
bar.width(percentVal)
bar.html(percentVal).attr('aria-valuenow', percentVal);
alertOk.show();
},
complete: function(xhr) {
if (xhr.status !== 200) {
alert(xhr.status + xhr.responseText);
dialog.modal("hide");
} else {
btnClose.prop("disabled", false);
btnAbort.prop("disabled", true);
reloadTable();
}
}
});
}
I get an error "400 Bad Request".
But if I remove this line:
<input class="form-check-input" type="checkbox" name="incremental" value="true" checked />
I can submit my form successfully.
What's wrong in my code?
Here the content of the formData:
target config
incremental true
id-type broadcast
revision 1
file File { name: "generic_config_0001.zip", lastModified: 1651224479000, webkitRelativePath: "", size: 755, type: "application/zip" }

Related

How to get the text of selected option instead of value

Here's the body of my html:
<form class="p-3">
<div class="form-group">
<label>Full Name</label>
<input id="inputName" type="text" oninput="Update(this.value, 'namec')"
class="form-control"
placeholder="Robert">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Contact Number</label>
<input id="inputNumber" type="text" oninput="Update(this.value,
'numberc')" class="form-control"
placeholder="09*********">
</div>
<div class="form-group col-md-6">
<label>Email Address</label>
<input id="inputEmail" type="email" oninput="Update(this.value, 'emailc')"
class="form-control"
placeholder="email#gmail.com">
</div>
</div>
<div class="form-group">
<label>Full Address</label>
<input type="text" class="form-control" placeholder="1234 Main St"
oninput="Update(this.value, 'addressc')">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Mode of Payment</label>
<select id="inputMOP" class="form-control" oninput="Update(this.value, 'mopc')">
<option selected>Select Payment</option>
<option>GCash</option>
<option>Bank Payment</option>
<option>Cash On Delivery</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Shipping Option</label>
<select id="inputMOD" class="form-control" oninput="Update(this.value,
'modc')">
<option selected>Select Delivery</option>
<option>Standard Delivery</option>
<option>J&T Express</option>
<option>Ninjavan Express</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<label>Item Name</label>
<select id="inputItem" class="itemInput form-control"
oninput="Update(this.value, 'itemc')">
<option selected>Select Item</option>
<option value="155.00">Hygienix Alcohol 1L</option>
<option value="180.00">Protect Plus Alcohol 1 Gal</option>
<option value="215.00">Guardian Alcohol 1 Gal</option>
</select>
</div>
<div class="form-group col-md-4">
<label>Quantity</label>
<input id="inputQuantity" type="text" oninput="Update(this.value,
'quantityc')"
class="itemQuantity form-control" placeholder="0"><br>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<h6 class="mt-2">Total Price: ₱ </h6>
</div>
<div class="form-group col-md-3">
<input id="itemPrice" type="text" oninput="Update(this.value, 'pricec')"
class="form-control" placeholder="0" readonly>
</div>
<div class="form-group col-md-6">
<button id="placeOrder" class="btn btn-primary btn-block float-
right">Place Order</button>
</div>
</div>
</form>
Jquery to calculate the total price:
<script>
$(document).ready(function () {
$('select.itemInput').on('change', function () {
$('.itemQuantity').text($('#inputQuantity').val(0));
$('.itemQuantity').on('change', function () {
$('#itemPrice').val(
$('#inputItem').val() * $('#inputQuantity').val() + ".00"
);
});
});
});
</script>
Variable declaration to add to the database:
var cName = $('#inputName').val();
var cNumber = $('#inputNumber').val();
var cEmail = $('#inputEmail').val();
var cAddress = $('#inputAddress').val();
var cMop = $('#inputMop').val();
var cMod = $('#inputMod').val();
var cItem = $('#inputItem').find(":selected").text();
var cQuantity = $('#inputQuantity').val();
var cPrice = $('#itemPrice').val();
The problem is that I cant get the text of the selected option from the #inputItem. It only gets the value from the option. Another thing, I can't also get the total price which is under the ID of #itemPrice.
How can I get the text instead of value of #inputItem? Also, the value of #itemPrice?
EDIT:
Finally solved it!! But I have a new problem, I cant add data with a "#gmail.com" but it works when it does not have it. How can I do add data with "#email.com"?
Use the following script for the desired results. Also if you don't have any function to call onChange, kindly remove those from your input fields, from html. They will keep on throwing errors in console.
$(document).ready(function () {
$('.itemInput').on('change', function () {
// tempItemName stores the selected item name
var tempItemName = $('.itemInput option:selected').text();
totalPriceCalc();
});
$('.itemQuantity').on('change', function(){
totalPriceCalc();
});
function totalPriceCalc () {
var tempInputQty = $('#inputQuantity').val();
var tempItemPrice = $('#inputItem option:selected').val();
var tempTotalCost = (tempInputQty * tempItemPrice) + '.00';
$('#itemPrice').val(tempTotalCost);
}
});

how can i make unque id in jQuery and send to the html

id = menu_selected_id sending each value by loop but when i receiving the data in HTML it just showing the first value. i think because of the unique id it happening
My question is how can i make a unque id for this menu_id_selected in html and jquery
$(document).ready(function() {
$('select[name="menu_item_category_selected"]').on('change', function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
url: '/admin/menu/item/entry1/' + countryID,
type: "GET",
dataType: "json",
success: function(data) {
console.log(data);
$('select[id="menu_selected_id"]').empty();
$.each(data, function(key, value) {
$('select[id="menu_selected_id"]').append('<option value="' + key + '">' + value + '</option>');
});
}
});
} else {
$('select[id="menu_selected_id"]').empty();
}
}).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row">
<label for="menu_category" class="col-md-4 col-form-label text-md-right">{{ __('Menu Category') }}</label>
<div class="col-md-6">
<select class="form-select" name="menu_item_category_selected" id="menu_item_category_selected">
<option value="Menu Item" disabled> --Select Menu Category-- </option>
#foreach($menu_category as $role)
<option value="{{$role->id}}">{{$role->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label for="menu" class="col-md-4 col-form-label text-md-right">{{ __('Menu') }}</label>
<div class="col-md-6">
<select class="form-select" name="menu_id_selected" id="menu_selected_id">
<option value="" disabled>--Select Menu--</option>
</select>
</div>
</div>
```

Web application using the Slim API. I'm trying to get data from my SQL database to populate a modal when the edit link is clicked in the table

Whilst debugging; the id for each row is found when the edit button is clicked but it seems to get stuck at that point. The data for the said row will not populate the modal. I would appreciate any help at all! Here is a picture in chrome. I have exhausted all of my ideas. I do have an error for localhost failed to load resource for an image folder, could this be causing conflict? I don't see how.
HTML
<div class="tab-pane" id="admin">
<br>
<div class="container">
<table id="admin_table" class="display">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Platform</th>
<th>Score Phrase</th>
<th>Score</th>
<th>Release Year</th>
<th>Release Month</th>
<th>Release Day</th>
<th>Editors Choice</th>
<th>Edit</th>
<th>x</th>
</tr>
<tbody id="admin_table_body">
</tbody>
</table>
</div> <br><br><br><br>
</div>
</div>
>Modal
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Edit</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" method="post">
<div class="form-group">
<label class="col-sm-4 control-label"><strong>ID:</strong></label>
<input type="text" style="height:32px;" name="id" id="id" disabled/>
<label for="id" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Title:</strong></label>
<input type="text" style="height:32px;" id="title" name="title"/>
<label for="title" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Genre:</strong></label>
<input type="text" style="height:32px;" id="genre" name="genre"/>
<label for="genre" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Platform:</strong></label>
<input type="text" style="height:32px;" id="platform" name="platform"/>
<label for="platform" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Score:</strong></label>
<input type="text" id="score" name="score" style="height:32px;"/>
<label for="score" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Score Phrase:</strong></label>
<input type="text" id="score_phrase" name="score_phrase" style="height:32px;"/>
<label for="score_phrase" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Year:</strong></label>
<input type="text" id="release_year" name="release_year" style="height:32px;"/>
<label for="release_year" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Month:</strong></label>
<textarea id="release_month" name="release_month" style="height:32px;"></textarea>
<label for="release_month" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Day:</strong></label>
<textarea id="release_day" name="release_day" style="height:32px;"></textarea>
<label for="release_day" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Editors Choice:</strong></label>
<textarea id="editors_choice" name="editors_choice" style="height:32px;"></textarea>
<label for="editors_choice" class="error"></label>
</div>
</form>
</div>
Main.js
var rootURL ="http://localhost:4006/GamesAPI/api/games";
var currentGame;
//when the DOM is ready
$(document).ready(function(){
findAll();
//findById();
$(document).on("click","#admin_table_body a",function(){findById(this.id);});
// $(document).on("click","#addButton",function(){addGame();});
// $(document).on("click","#deleteButton",function(){deleteGame();});
});
var findAll=function(){
console.log('findAll');
$.ajax({
type: 'GET',
url: rootURL,
dataType: "json", // data type of response
success: renderList
});
};
var findById = function(id)
{
console.log('findById: '+id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
//Gets stuck here
success: function(data){
//$('#btnDelete').show();
console.log('findById success: ' +data.title);
currentGame = data;
renderDetails(currentGame);
}
});
};
function renderList(data){
list = data.games;
console.log("renderList");
$('#admin_table_body tr').remove();
$.each(list, function(index, games){
$('#admin_table_body').append('<tr><td>' +games.title+'</td><td>'+games.genre+'</td><td>'
+games.platform+'</td><td>' +games.score_phrase+'</td><td>'
+games.score+'</td><td>'+games.release_year+'</td><td>'+games.release_month+'</td><td>'
+games.release_day+'</td><td>'+games.editors_choice+'</td><td>\n\
Edit</td>\n\
<td id="'+games.id+'"><button type="button" id="deleteButton" class="btn btn-success">Delete</button></td></tr>');
});
$('#admin_table').DataTable();
// $('gameList').append('<div class="row">');
//The rest of this function is to populate a different client page
output='<div class="row">';
$.each(list, function(index,games){
var img="pics/"+games.picture;
output+=('<div class="col-sm-6 col-md-4 col-lg-3"><div class="card"><img src='+'"'+img+'"'+
'height="150"><p>Title: '+games.title+'</p><p>Genre: '+games.genre+'</p><p>Platform: '+games.platform+
'</p><p>Score: '+games.score+' '+games.score_phrase+'</p></div></div>');
// $('#gameList').append('<div class="col-sm-6 col-md-4 col-lg-3"><div class="card">'+game.title+'</div></div>');
});
// $('#gameList').append('</div>');
output+='</div>';
$('#productList').append(output);
};
var renderDetails = function(games)
{
$('#id').val(games.id);
$('#title').val(games.title);
$('#url').val(games.url);
$('#platform').val(games.platform);
$('#score').val(games.score);
$('#score_phrase').val(games.score_phrase);
$('#genre').val(games.genre);
$('#pic').attr('src', 'pics/' + games.picture);
$('#editors_choice').val(games.editors_choice);
$('#release_year').val(games.release_year);
$('#release_month').val(games.release_month);
$('#release_day').val(games.release_day);
};
DatabaseMethod.php
function getGame($id) {
$query = "SELECT * FROM games WHERE id = '$id'";
try {
global $db;
$games = $db->query($query);
$game = $games->fetch(PDO::FETCH_ASSOC);
header("Content-Type: application/json", true);
echo $query;
echo json_encode($game);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Your server-side PHP method is outputting data which is not valid JSON.
Remove
echo $query;
from your code, since it's just left over from debugging. This is preventing jQuery from seeing the whole response as JSON and parsing it accordingly.

how can I fix my inputs which are out of range?

I wanted to fix my html/bootstrap style,but at the moment when I clicked the event all my imputs are out of range as picture number 1 at the moment when I get some input wrong . however I want to fix my inputs and when I click my event and get error from jquery stay on the same place as the picture 2
html
<form id="new_product">
<div class="form-group">
<label for="description">Name: </label>
<input type="text" class="form-control" id="description" name="description" title="product description" required>
</div>
<div class="form-group form-inline">
<div class="form-group">
<div class="col-md-5">
<label for="cost_price">Cost Price: </label>
<input type="text" class="form-control" id="cost_price" name="cost_price" title="cost_price" required>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="selling_price">Selling price: </label>
<input type="text" class="form-control" id="selling_price" name="selling_price" title="selling_price" required>
</div>
</div>
</div>
<div class="form-group form-inline">
<div class="form-group">
<div class="col-md-5">
<label for="wprice">Wholeprice: </label>
<input type="text" class="form-control" id="wprice" name="wprice" title="wprice" required>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="min_stock">Min stock: </label>
<input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" required>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="stock">Stock: </label>
<input type="text" class="form-control" id="stock" name="stock" title="stock" required>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<label for="max_stock">Max stock: </label>
<input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" required>
</div>
</div>
</div>
</form>
form_view
form_view2
jquery validation
$('#add').on('click',function(){
$("#description").mask("(999) 999-9999");
$("#new_product").validate();
BootstrapDialog.show({
type: BootstrapDialog.TYPE_PRIMARY,
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
'pageToLoad': URL_GET_VIEW_PRODUCT
},
closable: false,
buttons:[{
id: 'btn-ok',
cssClass: 'btn-primary',
icon: 'glyphicon glyphicon-send',
label: ' Save',
action: function (e) {
var description = $('#description').val();
var cost_price = $('#cost_price').val();
var selling_price = $('#selling_price').val();
var wprice = $('#wprice').val();
var min_stock = $('#min_stock').val();
var stock = $('#stock').val();
var max_stock = $('#max_stock').val();
if($("#new_product").valid()){
$.ajax({
url: URL_GET_ADD_PRODUCT,
type: 'POST',
data: {description: description, cost_price: cost_price, selling_price: selling_price, wprice: wprice, min_stock: min_stock, stock: stock, max_stock: max_stock}
}).done(function (data) {
console.log(data);
if (data.msg == 'successfully added') {
$('#new_product')[0].reset();
table.ajax.reload();
}else if(data.min_stock == 'el stock no puede ser mayor al min'){
BootstrapDialog.show({
type: BootstrapDialog.TYPE_WARNING,
message: 'el stock no puede ser mayor al min'
});
}
});
return false;
}
}
},{
id: 'btn-cancel',
cssClass: 'btn-danger',
icon: 'glyphicon glyphicon-remove',
label: ' Cancel',
action: function (e) {
e.close();
}
}]
});
});

Record data: SyntaxError: Unexpected end of JSON input

I can record data in my db but ajax loading doesn't inter in success method. What's the problem?
error: "SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at n.parseJSON "
record_data.php
<?php
$type=getPar_empty("type",$_GET,"");
$new_nome=$_GET['new_nome'];
$new_cognome=$_GET['new_cognome'];
$new_email=$_GET['new_email'];
$new_lingua=$_GET['new_lingua'];
if ($type=="add_user"){
$stmt=null;
$stmt=$db->prepare("INSERT INTO newsletter_utenti(email,abilitato,nome,cognome,lingua,lista,data_creazione,unsubscribe) VALUES('$new_email',1,'$new_nome','$new_cognome','$new_lingua','manual',now(),0)");
if (!$stmt) {
log_msg($db->error);
die();
}
$stmt->execute();
$stmt->close();
$db->close();
}
?>
script
$("#salvaBtn").click(function(){
var nome = $('#nome').val();
var cognome = $('#cognome').val();
var email = $('#email').val();
var lingua = $('#lingua').val();
var dataString = 'nome='+nome+'&cognome='+cognome+'&email='+email+'&lingua='+lingua+'&type=add_user';
$.ajax({
type:'GET',
data:dataString,
url:"record_data.php",
success:function(result) {
$("#status_text").html(result);
$('#nome').val('');
$('#cognome').val('');
$('#email').val('');
},
error:function(xhr,status,error) {
console.log(error);
}
});
});
$('#adduser').submit(function (){
return false;
});
form
<form name="adduser" id="adduser" method="GET" action="#">
<div class="col-md-3">
<div class="form-group m-b-30">
<p>E-mail</p>
<input class="form-control" type="email" id="email" name="email" placeholder="indirizzo e-mail" email required>
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Nome</p>
<input class="form-control" type="text" id="nome" name="nome" placeholder="nome">
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Cognome</p>
<input class="form-control" type="text" id="cognome" name="cognome" placeholder="cognome">
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Lingua</p>
<select class="form-control" id="lingua" name="lingua">
<option value="it">IT</option>
<option value="en">EN</option>
</select>
</div>
<input type="submit" class="btn btn-embossed btn-primary m-r-20" id="salvaBtn" value="Aggiungi utente"></input>
<div id="status_text" /></div>
</div>
</form>
Your ajax method is POST, but you try to recive values from GET, could be this.
Another way is to use json_decode, from PHP.
$vars = json_decode($_POST['data']);
tell us, these changes will clear your code input.
thanks