Form append just VALUES not variables to URL - php

I need to send a Form with just the values append to the URL, like this:
http://thisistheurl.com/serv#search/VALUE1/VALUE2/VALUE3/VALUE4
I could send like this:
http://thisistheurl.com/serv?variable1=value&variable2=value&variable3=value&variable4=value#search/
The form is very simple.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search/" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
</div>
</div>
<!-- Here goes the rest of the form -->
<a type="submit" class="btn btn-warning waves-effect btn-block" href="javascript:{}" onclick="document.getElementById('consultatickets').submit();">Buscar <i class="fa fa-search" aria-hidden="true"></i></a>
</div>
I don't know how to extract the just the values from the variables and append to the URL.

If the order doesn't matter, you can achieve this by serializing the values of the form and appending it to the action attribute of the form to build the final url.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
<label for="campo_adicional">Campo adicional</label>
<input id="campo_adicional" type="text" name="campo_adicional" />
</div>
</div>
<input type="submit" value="search"/>
</form>
$("#consultatickets").on('submit',
function(e) {
e.preventDefault();
var values = $(this).serializeArray();
var baseUrl = $(this).prop("action");
$.each(values, function(i, v) {
baseUrl += "/" + encodeURIComponent(v.value);
});
alert(baseUrl);
}
);
https://jsfiddle.net/kb3rvLjs/

Untested and I'm not sure if I got your question correctly but it seems you look for something like this:
// your form submit event handler
function formSubmit() {
var form = $('#consultatickets');
// build your url
var url = 'http://thisistheurl.com/serv#search/' +
getValues(form).join('/');
// redirect to your new location
location.href = url;
};
// function to get the values from the form elements
function getValues(form) {
// get all form fields in the form
var fields = $( "input, select", form);
var values = [];
// loop over the fields, add them to array
jQuery.each( fields, function( field ) {
values.push(encodeURI(field.val()));
});
return values;
}
In case you want to trigger the form submit with the a tag, simply change your onclick attribute to: onclick ="formSubmit();".

Related

How to dicard GET values in show method (laravel)

In my ClientController#index, I have a form with a select input to list every client in the database.
After submitting the form to list detailed client information, the URL is like /clients?client_id=id.
The routes are the defult with route::resource().
<form name="show_client" id="show_client">
<div class="form-group">
<label for="branch"><b>Selectione o Cliente</b></label>
<select class="form-control select2" name="client_id" id="client_id" required>
<option value="">Selecione o Cliente</option>
#foreach ($list as $client)
<option value="{{ $client->client_id }}">{{ $client->name }} </option>
#endforeach
</select>
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-primary btn-rounded">Listar Cliente</button>
</div>
</form>
<script>
$(function() {
$('#show_client').submit(function(){
var client_id = $('#client_id').val();
$(this).attr('action', "/clients/" + client_id);
});
});
</script>
Is there any way to work the url to be /clients/id?
I accomplish that by using an js function but it's clearly not the solution.
You should listen to the change event on the select list:
<script>
$(function() {
$('#client_id').change(function(){
var client_id = $(this).val();
$('#show_client').attr('action', "/clients/" + client_id);
});
});
</script>
You do know you can make the parameter in the route optional. That way, it can accept the route without a parameter. You then append the parameter on submit of the form

Jquery not sending textarea name="post_description"

My jQuery code is not sending a value from the textarea name="post_description"
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
</form>
$(document).ready(function() {
$("#share").click(function(e) {
e.preventDefault();
var postimg = $("#post").serialize();
$.post("posts/post_image.php", postimg).done(function(data) {
$("#share_result").html(data);
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
On the backend:
$post_description = $_POST['post_description'];
It's returning as undefined index but the names do match
May be because you prevent event onclick you have to set event prevent on form submit like this :
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
<button type="submit" id="postform">Submit form</button>
</form>
When you click on submit button your form will submit and then
$("#post").submit(function (e) {
e.preventDefault();
// here is your code
});
Or if you don't want to add this button you have to change from
var postimg = $("#post").serialize();
to
var postimg = {post_description:$("textarea[name='post_description']").val()};
It was the Angular js conflict so I had to write my own jquery function to replace the angular and keep the same angular beraviour on the page, here is my jquery solution for angular replacement:
<script type="text/javascript">
$(document).ready(function(){
$("#post_description").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$("#text_output").text(currentText);
//$("#text_output").value(currentText);
$("#text_output").attr("value", currentText);
});
});
</script>

I want to handle dynamic inputs in a form using jQuery and PHP. I'm able to add and delete input fields but failed to store them

these are the javascript functions i'm using
function addFac() {
$("<div>").load("includes/facility.php", function() {
$("#fac").append($(this).html());
});
}
function deleteFac() {
$('div.facility-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
here is the HTML code:
<div class="facility-item well" style="clear:both;">
<div class="row">
<div class="col-lg-1 col-sm-1 col-xs-3 padder-col">
<input type="checkbox" class="chk-lg">
</div>
<div class="col-lg-10 col-lg-offset-1 col-md-9 col-md-offset-2 col-sm-11 col-xs-9">
<input class="form-control" type="text" placeholder="Describe facility" name="faci[]" >
</div>
</div>
</div>
This code of html is written in a file named facilities.php and the file is included into the index.php. This is how i'm able to add and remove the dynamic input fields. But
when I wrote the PHP file:
$facilities = "0";
$faci = $_POST["faci"];
var_dump($faci);
even after having multiple facilities, it showed only one value in array.
Here is the working code Paste and run.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><img src="remove-icon.png"/>remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<form name="karan" action="" method="post">
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value="">
add
</div>
</div>
<input type="submit" name="submit" value="SUBMIT">
</form>
<?php
print '<pre>';
print_r($_REQUEST['field_name']);
print '</pre>';
//output
?>
<?php
$field_values_array = $_REQUEST['field_name'];
foreach($field_values_array as $value){
//your database query goes here
}
?>

want to show selected divs after form submission also

Bellow shown code does these things
when i select Scholership Programs from select list the div element with class="mystaff_hide mystaff_opt1" will be shown
and then i select Family Income now div with class="mystaff_hide mystaff_opt2" will be shown. Now both are there on my window.
Up to this the code works fine
What i want is after submission of my form i want both of them are must be there on my window
<div class="row">
<div class="col-md-6 col-sm-6 pull-left">
<div class="form-group">
<legend>Options to Search</legend>
<select class="form-control firstdropdown" name="sel_options" id="mystuff">
<option>Select Options</option>
<option value="opt1">Scholership Programs</option>
<option value="opt2">Family Income</option>
</select>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt1">
<div class="form-group">
<label for="LS_name">Scholarship</label>
<select class="form-control" name="LS_name[]" id="LS_name" multiple="multiple">
<option value="opt1">Scholership1</option>
<option value="opt2">Scholership2</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6 mystaff_hide mystaff_opt2">
<div class="form-group">
<label for="Family Income">Family Income</label>
<select multiple class="form-control" name="FamilyIncome[]" id="FamilyIncome">
<option value="opt1">Family Income1</option>
<option value="opt2">Family Income2</option>
</select>
</div>
</div>
This is my script
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script>
<script>
$( document ).ready(function() {
$('.mystaff_hide').addClass('collapse');
$('#mystuff').change(function(){
var selector = '.mystaff_' + $(this).val();
$(selector).collapse('show');
});
});
</script>
After lot of search i got this code which is shows only recent related selected option's div
<?php if(isset($_POST['sel_options']) &&
!empty(isset($_POST['sel_options']))){
?>
<script>
var selected_option = "<?php echo $_POST['sel_options']; ?>";
var selector = '.mystaff_' + selected_option;
//show only element connected to selected option
$(selector).collapse('show');
</script>
<?php } ?>
Take a look at localStorage or sessionstorage to store information about the state of webpage and read them after reload to restore the UI state
Example:
Localstorage
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Sessionstorage
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Or you may want to use AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
As you are using jquery, you may want to look at using Ajax in jquery.
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Print success notice in their own div depending on the form that I sent

I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>

Categories