Detect if a form has been sent - php

In my controller, i need some instructions to be launched only if a form has been sent.
This is my controller:
public function indexAction()
{
$form = array();
$submit = $this->getRequest()->getParam('submit');
if (!empty($submit))
{
$lastname = $this->getRequest()->getParam('last-name');
$name = $this->getRequest()->getParam('name');
$email = $this->getRequest()->getParam('email');
$form = array(
'lastname' => $lastname,
'name' => $name,
'email' => $email);
$confirm = Tools::checkInscription($form);
var_dump($confirm);
exit();
if ($confirm === true)
{
Tools::saveUser($form);
}
else
{
// Mets une variable a true pour savoir dans ta vu que tu as une erreur.
$this->_redirect('/inscription');
}
}
}
the problem is $submit always seems returning null.
My view:
<form id="formulaire">
<div class="msg">
<p class="error">Merci de vérifier les champs en rouge</p>
</div>
<div class="last-name">
<input type="text" class="error" id="last-name" name="last-name" placeholder="Votre nom" />
</div>
<div class="name">
<input type="text" id="name" name="name" placeholder="Votre prénom"/>
</div>
<div class="email">
<input type="text" id="email" name="email" placeholder="Votre email"/>
</div>
<button type="submit" title="Valider"></button>
</form>
Can anyone help to find what i'm doing wrong
thanks in advance

If you set your form method to POST you can check it with this:
if ($this->getRequest()->isPost()) {
}

Your submit button should be an input :
<input type="submit" title="Valider" />
And your form should have an action :
<form id="formulaire" method="POST" action="some_page.php">

Try
<input type="submit" title="Valider">
instead of
<button type="submit" title="Valider"></button>
And change
<form id="formulaire" action="" method="post">
instead of
<form id="formulaire">

Related

Too few arguments, 0 passed

I'm currently in an intership for a restaurant. I'm coding a website for them and I'm starting the CRUD on it.
The problem is that no data is passed to the controller, and so it doesn't update the drink.
Hope someone can help me.
I use a form to update a drink, here it is.
<div class="col-lg-6 order-lg-2">
<div class="p-5">
<p>Veuillez renseigner tous les champs !</p>
<p>Si un champ ne change pas, copier-coller ce champ depuis le tableau juste au-dessus.</p>
<form action="<?php base_url().'index.php/boissons/resp_modif_boisson/'.$son['id_boisson'] ?>" method="post">
<div class="form-group">
<label for="nom">Nom :</label>
<input type="text" class="form-control" id="nom" name="nom" maxlength="60" required>
</div>
<div class="form-group">
<label for="desc">Descriptif :</label>
<input type="text" class="form-control" id="desc" name="desc" maxlength="500" required>
</div>
<div class="form-group">
<label for="prix">Prix :</label>
<details>Si prix décimal, utilisez le "." ! (exemple : 1.99)</details>
<br>
<input type="number" class="form-control" id="prix" name="prix" min="0" step="0.01" value="0.00" required>
</div>
<button type="submit" class="btn btn-warning">Modifier</button>
</form>
</div>
</div>
And here is the controller.
public function resp_modif_boisson($num){
$this->load->helper('form');
$this->load->library('form_validation');
if($this->session->statut=="R"){
$this->form_validation->set_rules('nom', 'nom', 'required');
$this->form_validation->set_rules('desc', 'desc', 'required');
$this->form_validation->set_rules('prix', 'prix', 'required');
$nom = htmlspecialchars(addslashes($this->input->post('nom')));
$desc = htmlspecialchars(addslashes($this->input->post('desc')));
$prix = htmlspecialchars(addslashes($this->input->post('prix')));
var_dump($nom);
var_dump($desc);
var_dump($prix);
echo "test";
if ($this->form_validation->run() == FALSE){
$data['boi'] = $this->db_model->get_boisson($num);
echo "false";
$this->load->view('templates/haut_administrateur.php');
$this->load->view('resp_modif_boisson',$data);
$this->load->view('templates/bas');
}else{
$this->db_model->modif_boisson($num, $nom, $desc, $prix);
$data['boi'] = $this->db_model->get_boisson($num);
echo "true";
$this->load->view('templates/haut_administrateur.php');
$this->load->view('resp_modif_boisson',$data);
$this->load->view('templates/bas.php');
}
}else{
$data['boi'] = $this->db_model->get_all_boissons();
$this->load->view('templates/haut_accueil.php');
$this->load->view('boissons_afficher',$data);
$this->load->view('templates/bas.php');
}
}

404 NOT FOUND with LARAVEL6 [duplicate]

This question already has an answer here:
404 Not found with laravel 6
(1 answer)
Closed 2 years ago.
i have a problem while passing a variable into the URL , the route exists but still" 404 NOT FOUND" .
Form :
<form action="/rdv_{{$go->ID}}" method="post" role="form" data-aos="fade-up">
#csrf
<input placeholder="Email" type="email" class="form-control" name="email" id="email" />
<input placeholder="Votre numéro de téléphone " type="text" class="form-control" name="tel"
id="subject" />
<div id="buttons">
<button type="submit" class="btn btn-primary"> Prendre un rendez-vous </button>
</div>
</form>
Controller :rendezv.php:
public function rdv ($ID) {
$nm=request('email');
$tel=request('tel');
$ID=request('{{$go->ID}}');
$doctor=doc::findOrFail($ID);
$rdv = new rendezvous() ;
$rdv->Email=$nm;
$rdv->Numéro_de_téléphone=$tel;
$rdv->IDD=$doctor->ID;
$rdv-> save();
return redirect('/index') ;
}
}
Web.php
Route::post('/rdv_{ID}','rendezv#rdv');
The error is only "404 | Not Found". When I click the button for " Prendre un rendez-vous" the address became: " http:/ /localhost:8000/ rdv_1032569" and the error is probably there.
I re-modified the code as follows:
View: I updated the form action and added an hidden input field which has the value "$go-ID".
<form action="/rdv" method="post" role="form" data-aos="fade-up">
#csrf
<input placeholder="Email" type="email" class="form-control" name="email" id="email" />
<input placeholder="Votre numéro de téléphone " type="text" class="form-control" name="tel" id="subject" />
<input type="hidden" class="form-control" name="goID" value="{{$go->ID}}" />
<div id="buttons">
<button type="submit" class="btn btn-primary"> Prendre un rendez-vous </button>
</div>
</form>
Controller: I assumed that $go->ID in the view is the same as $doctor->ID in the controller. So, I assigned the value of $rdv->IDD to be $ID;
public function rdv () {
$nm=request('email');
$tel=request('tel');
$ID=request('goID');
$rdv = new rendezvous() ;
$rdv->Email=$nm;
$rdv->Numéro_de_téléphone=$tel;
$rdv->IDD=$ID;
$rdv-> save();
return redirect('/index') ;
}
Route: I removed '_{ID}' from the route.
Route::post('/rdv','rendezv#rdv');
The error is most likely from this $doctor=doc::findOrFail($ID);
If there's no doc model with the ID specified, laravel automatically returns a 404.
To change this behaviour, use find() and handle the return manually e.g
$doctor=doc::find($ID);
if(!$doctor) {
// return here
}
Change route
Route::post('/rdv/{ID}','rendezv#rdv')->name('rdv');
and form route
actions="{{ route('rdv', [$go->ID]) }}"

Send data array or object from ajax jquery post to php method

There is my JQuery function that get all form fields value and push them in array:
$(document).ready(function() {
$('#details_form').submit(function(e) {
e.getPreventDefault();
var result = $(this).serializeObject();
$.post($(this).prop('action'), {
'data': result
},
function(data) {
alert(data.msg);
},
'json'
);
return false;
});
});
it works really good (it send all of data):
{"_token":"w35HLqCZi61ki9QOlu6MFwWxYNbBoiEJkcQ58G2b","id":"contact_1","name":"t","surname":"fg","address":"iiiiiiiiiiiiiiiiiiiii","contact[]":["16151515","2325556"]}
but loading the page that i target $(this).prop('action') instead send back json response immediatelly via alert.
But, if i remove e.getPreventDefault(); the JQuery script returns error 500 with this response: {"error":{"type":"ErrorException","message":"array_filter() expects parameter 1 to be array, null given","file":"C:\\xampp\\htdocs\\rubrica\\app\\controllers\\ContactController.php","line":145}} like if PHP can't get nothing......
This is my PHP function in ContactController of Laravel Framework:
public function contact_process() {
$contact_id = trim(Input::get('id'));
$contact_name = trim(Input::get('name'));
$contact_surname = trim(Input::get('surname'));
$contact_address = trim(Input::get('address'));
$telephones = array_filter(Input::get('contact'));
if ($contact_id !== '' && $contact_name !== '' && $contact_surname !== '' && $contact_address !== '' && $telephones !== '') {
if ($contact_id == 'new') {
$new_contact = new Contact;
$new_contact->name = $contact_name;
$new_contact->surname = $contact_surname;
$new_contact->address = $contact_address;
$new_contact->save();
$LastInsertId = $new_contact->id;
foreach ($telephones as $value) {
$new_detail = new Detail;
$new_detail->telephone = $value;
$new_detail->contact_id = $LastInsertId;
$new_detail->save();
}
$response = array(
'status' => 'success',
'msg' => 'Nuovo contatto aggiunto'
);
return Response::json($response);
} else {
list($tmp, $id_temp) = explode("_", $contact_id);
$get_contact = Contact::find($id_temp)->first();
if ($get_contact) {
$get_contact->name = $contact_name;
$get_contact->surname = $contact_surname;
$get_contact->address = $contact_address;
$get_contact->save();
$delete_details = Detail::where('contact_id', '=', $id_temp)->delete();
foreach ($telephones as $value) {
$new_detail = new Detail;
$new_detail->telephone = $value;
$new_detail->contact_id = $id_temp;
$new_detail->save();
}
$response = array(
'status' => 'success',
'msg' => 'Contatto aggiornato'
);
return Response::json($response);
}
}
}
$response = array(
'status' => 'error',
'msg' => 'Compila tutti i campi ed inserisci almeno un numero di telefono'
);
return Response::json($response);
}
This is my form (Telephone inputs are dinamic):
<form method="POST" action="http://localhost/rubrica/public/contact_process" accept-charset="UTF-8" class="form-bootstrap" id="details_form" autocomplete="off">
<input name="_token" type="hidden" value="HeC6RwznFYuemIvP68pHYuET634fgQoZQCtL7ed3">
<input id="contact_id" name="id" type="hidden" value="contact_1">
<div class="bg_contact">
<div class="image_contact">
<label for="immagine" id="" class="">Add Image</label>
<input name="image" type="file" id="immagine"> </div>
<div class="rif_contact">
<div class="name_contact">
<input placeholder="Name" id="name" name="name" type="text" value="John"> </div>
<div class="surname_contact">
<input placeholder="Surname" id="surname" name="surname" type="text" value="Wayne"> </div>
</div>
</div>
<div class="address">
<div class="label_address">
<label for="address">Address</label>
</div>
<input placeholder="Address" id="address" name="address" type="text" value="2nd street"> </div>
<div class="bg_details">
<label for="contacts">Contacts</label>
<div class="content_detail">
<input type="text" name="contact" class="contact_details" placeholder="Telephone" value="656346843" id="detail_161">
<button onclick="delete_detail_exist(this,161)" id="remScnt" type="button">Remove</button>
</div>
<div class="content_detail">
<input type="text" name="contact" class="contact_details" placeholder="Telephone" value="56196856" id="detail_160">
<button onclick="delete_detail_exist(this,160)" id="remScnt" type="button">Rimuovi</button>
</div>
<div class="content_detail">
<input placeholder="Telephone" class="contact_details" id="p_scnt" name="contact" type="text">
<button id="addScnt" onclick="add_detail_field(this)" type="button">Add</button>
</div>
</div>
<input id="save" type="submit" value="Save"> </form>

Contactform.php not sending all inputs

I have a contact form that is working fine, it sends the email except that it doesn't post the email address of the person that sends it. I have no idea why, I tried changing the $from variable and nothing changes. Is there something obvious I am missing?
It is the input with the id c_email which is put into the $from variable that I do not receive in the emails sent by this form.
My contactform.php:
<?php
// Contact
$to = 'myemail#gmail.com';
$subject = 'Portfolio ContactForm';
if(isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_message'])){
$name = $_POST['c_name'];
$from = $_POST['c_email'];
$message = $_POST['c_message'];
if (mail($to, $subject, $from, $name, $message)) {
$result = array(
'message' => 'Sent, thanks!',
'sendstatus' => 1
);
echo json_encode($result);
} else {
$result = array(
'message' => 'Ooops, problem..',
'sendstatus' => 1
);
echo json_encode($result);
}
}?>
On my html page:
<form id="contact-form" role="form">
<div class="form-group">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Nom">
</div>
<div class="form-group">
<label class="sr-only" for="c_email">Email address</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Votre message"></textarea>
</div>
<button type="submit" class="btn btn-custom-1">
<i class="fa fa-bullhorn icon-before"></i> Envoyer
</button>
</form>
Your values is not posting because in your form you not mention method="POST".Just try like this.it should work
<form id="contact-form" role="form" action="" method="POST">
<div class="form-group">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Nom">
</div>
<div class="form-group">
<label class="sr-only" for="c_email">Email address</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Votre message"></textarea>
</div>
<button type="submit" class="btn btn-custom-1">
<i class="fa fa-bullhorn icon-before"></i> Envoyer
</button>
</form>
<script>
$('button').click(function() {
var c_name = $("#c_name").val();
var c_email = $("#c_email").val();
var c_message = $("#c_message").val();
$.ajax({//create an ajax request to load_page.php
type: "POST",
url: "assets/php/contactForm.php",
data:{"c_name":c_name,"c_email":c_email,"c_message":c_message},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
});
</script>

codeigniter validation error with field "required"

i have a problem with the validation form. It does not work if i put "required", example:
controller:
public function updateBenefit(){
$result = array();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('beneficio', 'Nombre del Beneficio', 'required|alpha');
$this->form_validation->set_rules('info', 'Info', 'alpha');
$this->form_validation->set_rules('descrip', 'Descripción', 'alpha');
$this->form_validation->set_rules('orden', 'Orden', 'integer');
// $this->form_validation->set_rules('fecha', 'Fecha', 'date_valid');
$this->form_validation->set_message('required', 'El campo %s es requerido');
if ($this->form_validation->run() == TRUE){
if (isset($_POST['id'])){
$idb = $_POST['id'];
$benefit = BeneficiosManager::getInstance()->getHome($idb);
$result['message'] = "Se ha modificado el Beneficio con éxito";
} else{
$benefit = BeneficiosManager::getInstance()->create();
$result['message'] = "Se ha cargado el Beneficio con éxito";
}
$benefit->nombre = ucfirst(strtolower($_POST['beneficio']));
$benefit->content = ucfirst(strtolower($_POST['descrip']));
$benefit->intro = ucfirst(strtolower($_POST['info']));
$benefit->active = $_POST['optionsRadios2'];
$benefit->orden = $_POST['orden'];
// $benefit->date = $_POST['fecha'];
BeneficiosManager::getInstance()->save($benefit);
}else{
//no se validaron los datos ingresados
$result['message'] = "Error validación";
}
echo json_encode($result);
}
view:
{extends file='admin/base/base.tpl'}
{block name='content'}
<h3>Cargar Beneficio </h3>
</br>
<form action="{site_url()}admin/updateBenefit" class="form-horizontal" method="post" id="" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Beneficio</label>
<div class="controls">
<input type="text" name="beneficio" value="" class="m-wrap medium" />
<span class="help-inline">Nombre del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Info</label>
<div class="controls">
<textarea name="info" class="medium m-wrap" rows="3"></textarea>
<span class="help-inline">Información Clave</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Descripción</label>
<div class="controls">
<textarea name="descrip" class="large m-wrap" rows="3"></textarea>
<span class="help-inline">Descripción del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Activo</label>
<div class="controls">
<label class="radio line">
<input type="radio" name="optionsRadios2" value="1"/>Si</input>
</label>
<label class="radio line">
<input type="radio" name="optionsRadios2" value="0"/>No</input>
</label>
<span class="help-inline">Ofrecer Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Orden</label>
<div class="controls">
<input type="text" name="orden" value="" class="m-wrap small" />
<span class="help-inline">Prioridad del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Fecha</label>
<div class="controls">
<input type="text" name="fecha" value="{$smarty.now|date_format}" class="m-wrap medium" />
<span class="help-inline"></span>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn blue"><i class="icon-ok"></i> Guardar</button>
<button type="button" class="btn">Cancelar</button>
</div>
</form>
{/block}
what might the problem be?
if i remove the "required" field, the form validates... but if i put it, it doesn't... i don't know what else to try, can't understand why this is happening
the code is working now, thanks to #Jonathan that corrected me, and i was also making an imput mistake when i was trying this method. I was trying to put two words in the same field (i.e: bon vivir); so the correct input would be: bonvivir.
I'm not sure you are using "title" as the name of your real title input element. Because I found you use this code to assign your title.
$benefit->title = ucfirst(strtolower(trim($_POST['beneficio'])));
So you may want to try to use
$this->form_validation->set_rules('beneficio', 'Nombre del Beneficio', 'required|alpha');
instead.
I am not sure I had the right guess. Just give it a go. Hope this helps.

Categories