I have a search function on my PHP (CodeIgniter) website. But I want to pass the query terms in the URL so Google Analytics can track that info. I think this is kind of basic but I'm just learning how to code.
This is my HTML:
<form class="navbar-form navbar-right mtop10 mright10 hidden-xs" role="search" method="post" action="<?php echo base_url('cursos/searchCourse'); ?>">
<div class="form-group">
<input class="form-control" type="text" name="search_course" placeholder="Busque um curso" />
<input type="hidden" name="url" value="<?php echo current_url(); ?>" />
</div>
<button class="btn btn-md btn-default" type="submit" value="">
<span class="glyphicon glyphicon-search"></span>
</button>
<?php if($this->session->flashdata('search_error')) : ?>
<?php $errors = $this->session->flashdata('search_error');echo $errors['search_course']; ?>
<?php endif; ?>
</form>
This is the function searchCourse:
public function searchCourse(){
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p class="alert alert-danger mtop5" role="alert">', '</p>');
$this->form_validation->set_rules('search_course', 'Busca', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_message('required', 'Campo de preenchimento obrigatório');
$this->form_validation->set_message('min_length', 'O campo precisa conter pelo menos 2 caracteres');
if ($this->form_validation->run()){
$search = $this->curso_model->getCoursesBySearch($this->input->post('search_course'));
if(!empty($search)){
$this->index($search);
}else{
$this->set_flashdata('search_empty', 'search_empty', $this->input->get('url'));
}
}else{
$errors = array('search_course'=>form_error('search_course'));
$this->set_flashdata('search_error', $errors, $this->input->get('url'));
}
}
And this is my model:
public function getCoursesBySearch($search){
$this->db->select('*');
$this->db->from('curso');
$this->db->group_by('curso_nome');
$this->db->like('curso_nome', $search);
//$this->db->or_like('curso.curso_descricao', $search);
//$this->db->or_like('curso.curso_categoria', $search);
$this->db->or_like('tags.tags_nome', $search);
$this->db->join('curso_tags', 'curso_tags.curso_id = curso.curso_id');
$this->db->join('tags', 'tags.tags_id = curso_tags.tags_id');
//$this->db->where('curso_status', 1);
//$this->db->distinct();
$this->db->distinct();
$query = $this->db->get();
print_r($search);
//exit;
return $query->result();
}
Can anybody give me a clue?
Cheers!
Use jquery to modify the action attribute dynamically. Assign id attritube to each of the form elements including form itself
HTML :
<form id="my_form" method="post" action="dummy.html">
<input id="search_text" type="text" name="search_course" placeholder="Busque um curso" />
<input type="hidden" name="url" value="sdff" />
<button id="my_button" type="submit" value="Submit"> </button>
</form>
Jquery: (Add below your form)
<script>
$('#my_button').click(function(){
var search_text = $("#search_text").val();
// Replace my_search.php with actual landing page
$('#my_form').attr('action', 'my_search.php' + '?search=' + search_text);
});
</script>
Note : Your search text will be decoded in URL (in case of spaces, etc) and you have decode the URL at the landing page.
Change the method from post to get, so the values will be in the URL :
<form class="navbar-form navbar-right mtop10 mright10 hidden-xs" role="search" method="post" action="<?php echo base_url('cursos/searchCourse'); ?>">
replace with :
<form class="navbar-form navbar-right mtop10 mright10 hidden-xs" role="search" method="get" action="<?php echo base_url('cursos/searchCourse'); ?>">
Related
I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');
html code
<form>
<div class="list">
<div class="list list-inset" >
<label class="item item-input" id="descriptions">
<input type="text" height:"90" class="description" placeholder="Description ..." ng-model="data.describe" required>
</label>
<label input="email" class="item item-input" id="email" ng-model="data.email" required >
<span class="input-label">Email</span>
<input type="email">
</label>
<label class="item item-input">
<span class="input-label">Date</span>
<input type="date">
</label>
</div>
<button class="button button-block button-balanced" type="submit" ng-click="AddItem(); submitForm()">
Add Item
</button>
<button class="button button-block button-assertive" ng-click="closeModal()"> cancel</button>
</div>
</form>
app.js
$scope.data = {
description: "default",
email: "default",
date: "default",
};
$scope.submitForm = function() {
console.log("posting data....");
$http.post('http://localhost:4400/api.php', JSON.stringify($scope.data)).success(function () {/*success callback*/ });
};
api.php
<?php
$name=$_POST['descriptions'];
$email=$_POST['email'];
$message=$_POST['date'];
if (($descriptions =="")||($email=="")||($date==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $descriptions<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form" + $date;
mail("testing#gmail.com", $subject, $message, $from);
echo "Email sent!";
}
?>
I am trying to send contents of a form to an email address provided. The problem is when I try and do this, I get an error: POST http://localhost:4400/api.php 404 (Not Found). I have looked on other posts and cannot resolve this issue thank you.
enter image description here
use http://localhost:4400/api.php instead of api.php at your code
and change submit like this
<form action="api.php" method="post" id="myform" name="myform">
and
<button onclick="document.getElementById("myform").submit()">SUBMIT</button>
You can link your php file with a relative url. If your file api.php is in app/, you can write in your app.js :
$scope.submitForm = function() {
$http.post('api.php', JSON.stringify($scope.data), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};
In api.php :
$descriptions = $_POST['descriptions'];
$email = $_POST['email'];
$date = $_POST['date'];
So I am making a function for file uploading in my project.
however, when I try it I get this error : Call to a member function isValid() on string
My code for the upload function :
public function upload(Request $request){
$file = array('profielfoto' => $request->input('profielfoto'));
$rules = array('profielfoto' => 'required',);
$validator = Validator::make($file,$rules);
if($validator->fails()){
return redirect('/profiel')->withInput()->withErrors($validator);
}
else{
if($request->input('profielfoto')->isValid()){ //<- gives error
$destinationPath = 'assets/uploads';
$extension = $request->input('profielfoto')->getClientOriginalExtension();
$fileName = rand(1111,9999).'.'.$extension;
$request->input('profielfoto')->move($destinationPath,$fileName);
Session::flash('alert-success', 'Foto uploaden gelukt');
return redirect('/profiel');
}
else{
Session::flash('alert-danger', 'Foto uploaden mislukt');
return redirect('/profiel');
}
}
}
The form in the blade view on the 4th line from down below is the location for the input!
<form method="POST" action="/profiel/upload" files="true">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" class="form-control id2" id="id2" name="id" value="{{$user->id}}">
<img src="assets/images/avatar.png" alt="gfxuser" class="img-circle center-block">
<div class="form-group center-block">
<label class="center-block text-center" for="fotoinput">Kies uw foto</label>
<input class="center-block" type="file" name="profielfoto" id="profielfoto">
</div>
<button type="submit" class="btn btn-success"><span class="fa fa-check" aria-hidden="true"></span> Verander foto</button>
</form>
You must ask isValid() to a file, not to the name of the file. That's why you get the error. You can get the file through $request->file() or through Input::file() :
else{
if( $request->file('profielfoto')->isValid()){ //<- gives error
Also your form should include the correct enctype to send files:
<form enctype="multipart/form-data">
I think you should use as this.
$file = $request -> file('Filedata');
if (!$file -> isValid()) {
echo Protocol::ajaxModel('JSEND_ERROR', 'not an valid file.');
return;
}
Add attribute on
enctype="multipart/form-data"
I want to create simple search function. I follow some example. but I was unable to get results. please help me.
//view page
<form class="navbar-form" role="search" action=" {{ base_url }}search/search_keyword" method = "post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name = "keyword"size="15px; ">
<div class="input-group-btn">
<button class="btn btn-default " type="submit" value = "Search"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
//controller
function search_keyword()
{
$keyword = $this->input->post('keyword');
$data['results'] = $this->mymodel->search($keyword);
$this->twig->display('result_view.php',$this->data);
//$this->load->view('result_view.php',$data);
}
}
//model
function search($keyword)
{
$this->db->like('item_name',$keyword);
$query = $this->db->get('bracelets');
return $query->result();
}
Change
$this->twig->display('result_view.php',$this->data);
TO
$this->load->view('result_view.php',$data);
Use This Function
function search_keyword()
{
$keyword=$this->input->post('keyword');
$data['results']=$this->mymodel->search($keyword);
$this->twig->display('result_view.php',$data);
}
I'm click my submit button freely without enter values in the form..then in my database a row inserted that columns contain zeros
controller
function submit_expense()
{
$exp_date=$this->input->post('expense_date');
$expense_ids= $this->input->post('expense');
$expense_ids=substr($expense_ids,0,strlen($expense_ids)-1);
$expense_id_array = explode(',',$expense_ids);
$id=$this->session->userdata('userid');
for($i=0;$i<count($expense_id_array);$i++)
{
$required_id = TRIM($expense_id_array[$i]);
$this->form_validation->set_error_delimiters('<div style="color:#B94A48">', '</div>');
$this->form_validation->set_rules('exp_amount_'.$required_id, 'Expense Amount', 'required|numeric');
$this->form_validation->set_rules('comment_'.$required_id, 'Comments', 'required|alpha');
if ( $this -> form_validation -> run() === FALSE )
{
$this->index();
}
else
{
$amount= $this->input->post('exp_amount_'.$required_id);
$comment=$this->input->post('comment_'.$required_id);
$expense_data=array(
'expense_id'=>$required_id,
'expense_amount'=>$amount,
'user_id'=>$id,
'date'=>$exp_date,
'comments'=>$comment,
);
$this->home_model->insert_expense($expense_data);
$this->session->set_flashdata('message', 'Successfully submitted.');
redirect(base_url().'home/index');
}
}
}
And also my validation is not working
footer_view
var new_String ='<div class="form-group" id="ex_'+unqid1+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="exp_amount_'+unqid1+'" id="id_'+unqid1+'" type="text" '+
'class="form-control" placeholder="Enter '+name+' expense amount" style="margin-right:20px;" required>'
+'<input name="comment_'+unqid1+'" type="text" id="comment" class="form-con" placeholder="Comments" style="margin-right:20px;" required ></div >' ;
$("#create_exp").append(new_String);
view
this is my view use the id create_exp in my footer
<form role="form" action="<?echo base_url()?>home/submit_expense" method="post">
<?$todays_date=date('Y-m-d');?>
<input id="expense_date" name="expense_date" value="<?echo $todays_date;?>" type="hidden" />
<div class="red">
<? echo $this->session->flashdata('message'); ?>
</div>
<div class="box-body" id="create_exp">
<?php echo validation_errors(); ?>
<span>Choose from the right which all you need to enter for today</span>
<!--here goes the input boxes-->
<!-- /.input boxes -->
</div><!-- /.box-body -->
<span id="errmsg1"></span>
<input id="expenseVal" name="expense" type="hidden" class="form-control">
<div class="box-footer" id="button_id">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
As the OP Wants to show the all the Errors inside a div
<div id="error">
<?php echo validation_errors(); ?>
</div>
As the OP Wants some additional info,
To include a view or common page
$this->load->view('yourownpage');
Then you should have yourownpage.php inside your views folder
To have pagination, Have this in your controller's function
$this->load->library('pagination');
$config['base_url'] = 'yourownpage';
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Note :
Make sure to place the error div in the place that didn't hurt your textbox