CodeIgniter incorrect URL when submitting form - forms

I just started using CodeIgniter today, and was following the tutorial at the CI website.
When I got to the final step for creating a new news item, I ran into an issue with the form submit. I would expect the URL to be jonhopkins.net/news/create when I press the form's submit button, but it is going to http://jonhopkins.net/news/jonhopkins.net/news/create instead, which is clearly very wrong, and I have no idea why this is happening. Does anyone know how to fix this?
Everything else on my site (the Pages part of the tutorial) works perfectly. This is the only thing that is breaking. All of my code is exactly as it appears in the tutorial, except for a change to what happens when an item is successfully submitted to the database, which currently is never happening.
News Controller
public function create() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
} else {
//$success will contain the slug of the created item, or FALSE if database insertion failed
$success = $this->news_model->set_news();
if ($success) {
$this->_doView($success);
} else {
echo "Something went wrong while trying to submit the news item.";
}
}
}
public function view($slug) {
$this->_doView($slug);
}
private function _doView($slug) {
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item'])) {
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
Create View
<h2>Create a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/create') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
And the resulting HTML...
<form action="jonhopkins.net/news/create" method="post" accept-charset="utf-8">
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Create news item" />
</form>
News Model I don't think it's ever getting here, but just in case
public function set_news() {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text'),
'date' => date("Y-m-d H:i:s")
);
if ($this->db->insert('news', $data)) {
return $slug;
} else {
return FALSE;
}
}
Routes
$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

The form_open('news/create') method uses the $CI->Config->site_url() method which, in turn, uses the base_url from your config file.
Make sure your $config['base_url'] is set to your domain (with trailing slash) in the application/config/config.php file.
$config['base_url'] = 'http://jonhopkins.net/';

Related

Codeigniter appears to always set validation->run to FALSE

Controller : User.php
public function index()
{
log_message('debug', ' Index User');
die("should never get here");
}
public function login()
{
log_message('debug', ' Login Entered');
echo '<pre> Printing Login data:';
print_r($_POST);
echo "</pre>";
$data['pageHeader'] = "Login";
$data['message'] = 'temporary message - This will be the login stuff';
$this->session->set_flashdata('flashInfo', 'Login form will go here');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() === FALSE)
{
log_message('debug', ' validation run FALSE');
$this->load->helper('form');
$this->render_page('user/login', 'public_header', 'footer', $data);
}
else
{
log_message('debug', ' validation run TRUE');
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember))
{
log_message('debug', ' redirect Dashboard');
redirect('dashboard');
}
else
{
$_SESSION['auth_message'] = $this->ion_auth->errors();
$this->session->mark_as_flash('auth_message');
log_message('debug', ' redirect user login');
redirect('user/login');
}
}
}
Known from log:
function login entered,
$_POST always 'empty',
form validation-> always FALSE thus debug message is logged and form redisplayed
Form user/login.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<div class="container">
<?php echo $message;?>
<h1>Login</h1>
<form action="#" method="post">
<div class="imgcontainer">
<img src="http://www.hdkumdo.com/smen/assets/crow2.png" alt="Swordsmen Martial Arts">
</div>
<div class="container">
<label for="username"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" required autofocus>
<label for="password"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<button type="submit" name="login" id="login" value"login" >Login</button>
<label>
<input type="checkbox" checked="checked" name="remember" id="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
Copied an example from https://www.codeigniter.com/user_guide/libraries/form_validation.html
and form posts data but if I change function index to login it does not work.
Menu link : Login works fine.
Everything seems to be connected...login form displays, Controller function login is entered but it seems like there is no POST data so the form is simply redisplayed. I have 2 simple validation rules so it seems that validation->run should return true if I just enter any data into the fields.
I am sure it's something simple but for the life of me I can't see what.
First of all make sure you have loaded form validation library
$this->load->library('form_validation');
//set field validation
$this->form_validation->set_rules('fieldname','Field Name','required');
if($this->form_validation->run())
{
//then process form
//redirect
}
else {
//load view
}

Laravel: Unable to redirect to get Route

Routes.php
Route::get("/", "MasterController#home");
Route::get("add/a/category", "MasterController#add_a_category");
Route::post("add/a/category", "MasterController#add_a_category_post");
MasterController.php
<?php
class MasterController extends BaseController {
public function add_a_category()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// viewing
return View::make("pages.add_a_category", $data);
}
public function add_a_category_post()
{
// titling
$data['title'] = "Price Soldier - Add a Category";
// controlling
CategoryModel::add();
}
}
?>
CategoryModel.php
<?php
class CategoryModel {
protected $fillable = array("category_name", "updated_at", "created_at");
public static function add()
{
// Validation
$rules = array("category_name" => "required|min:3|max:20");
$validation = Validator::make(Input::except("submit"), $rules);
if ( $validation->fails() )
{
return Redirect::to("add/a/category")->withErrors($validation);
}
else
{
$result = DB::table("categories")
->insert(
array(Input::except("submit"))
);
return Redirect::to("add/a/category");
}
}
}
?>
add_a_category.blade.php
#extends("layouts.master")
#section("content")
<h1>Add a Category</h1>
<form action="{{ URL::to("/") }}/add/a/category" method="POST">
<label for="category_name">Category Name</label>
<input type="text" name="category_name" value="">
{{ $errors->first("email", "<span class='error'>:error</span>") }}
<div style="clear: both;"></div>
<div class="submit">
<input type="submit" name="submit" value="Add">
</div>
</form>
#stop
Now when the validation passes or fails, I'm redirecting to add/a/category route. But I don't see anyhting except a blank page while the category_name field is getting added to the database.
You need to return the response of the model's add method to the Controller's response. Instead of:
ControllerModel::add():
Try
return ControllerModel:add();

Magento Admin form redirects to dashboard on ?post?

Magento 1.7.0.2:
I'm trying to get a form (in the backend) to upload a file(picture) to Post to itself if incomplete, or the adminhtml controller if complete. My JavaScript validation is working well, but when/if my form is POSTed I'm redirected to the dashboard. I've got a form key included and my url's are created with the special key, but still I can't get a POST through. Can anyone help me?
The phtml template file:
<script type="text/javascript">
function postSelf(){
form=document.getElementById('imgSel');
form.action='<?php Mage::helper("adminhtml")->getUrl("*/*/")?>';
form.submit();
}
function validateForm(){
var name=document.forms["imgSel"]["iName"].value;
var file=document.forms["imgSel"]["file_upload"].value;
if (!name){
alert("You must have an Image Name!");
postSelf();
}
else if (!file){
alert("You must have a File to upload");
postSelf();
}
else{
form=document.getElementById('imgSel');
form.submit();
}
}
</script>
<?php Mage::log(Mage::helper("adminhtml")->getUrl("*/*/"), null, ‘layout.log’ );?>
<h3 class="icon-head head-adminhtml-imagegrid">Add an Image:</h3>
<form name="imgSel" id="imgSel" action="<?php Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
enctype="multipart/form-data" method="POST">
<!--Form key-->
<input type="hidden" name="form_key" value="<? echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
<?php Mage::log(Mage::getSingleton('core/session')->getFormKey(), null, ‘layout.log’ );?>
<label for="iName">Image Name:</label>
<input type="text" name="iName">
<label for="style">Associated Style Name:</label>
<select name="style">
<?php
echo '<option value="-1">None</option>';
$styles = Mage::getModel('cartonplugin/cartonstyle')->getCollection();
foreach($styles as $style){
echo '<option value="'.$style->getId().'"';
echo '>'.$style->getData('style_name').'</option> ';
}
echo '</select><br />';
?>
<input type="hidden" name="MAX_FILE_SIZE" value="40" />
Upload Image: <input type="file" name="file_upload" />
<br>
<!--<input type="submit" value="submit">-->
<button onClick="validateForm()" class="UploadButton" >Upload</button>
</form>
Controller: Only the insertAction() function is for this form. The rest is gridview stuff for dealing with any already-uploaded images.
<?php
class Nationwide_Newcart_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
{
protected function _initAction()
{
$this->loadLayout()->_setActiveMenu('igrid/set_time7')
->_addBreadcrumb('image Manager','image Manager');
return $this;
}
public function indexAction()
{
$this->loadLayout();
$this->renderLayout();
//var_dump(Mage::getSingleton('core/layout')->getUpdate()->getHandles());
}
public function newAction()
{
$this->_forward('edit');
}
public function editAction()
{
$stId = $this->getRequest()->getParam('id');
$model = Mage::getModel('newcart/imagemodel')->load($stId);
if ($model->getId() || $stId == 0)
{
Mage::register('image_data', $model);
$this->loadLayout();
$this->_setActiveMenu('igrid/set_time7');
$this->_addBreadcrumb('image Manager', 'image Manager');
$this->_addBreadcrumb('Image Description', 'Image Description');
$this->getLayout()->getBlock('head')
->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()
->createBlock('newcart/adminhtml_imagegrid_edit'))
->_addLeft($this->getLayout()
->createBlock('newcart/adminhtml_imagegrid_edit_tabs')
);
$this->renderLayout();
}
else
{
Mage::getSingleton('adminhtml/session')
->addError('That Image does not exist');
$this->_redirect('*/*/');
}
}
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try {
$postData = $this->getRequest()->getPost();
$model = Mage::getModel('');
//Mage::log($this->getRequest()->getParam('id'), null, ‘layout.log’ );
if( $this->getRequest()->getParam('id') <= 0 )
$model->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate()
);
$model
//->addData($postData) //DO NOT! Includes a form key!
->setUpdateTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'));
$model->setData('image_name', $postData['image_name']);
$model->setData('style_name', $postData['style_name']);
$model->save();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->settestData(false);
$this->_redirect('*/*/');
return;
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->settestData($this->getRequest()
->getPost()
);
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if($this->getRequest()->getParam('id') > 0)
{
try
{
$model = Mage::getModel('newcart/imagemodel');
$model->setId($this->getRequest()
->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully deleted');
$this->_redirect('*/*/');
}
catch (Exception $e)
{
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
public function insertAction(){
$postData = $this->getRequest()->getPost();
Mage::log($postData, null, ‘layout.log’ );
//post checking
if(empty($postData)){
}
$this->_redirect('*/*/');
}
}
There are few things you need to check:
You have echo missing here:
action="<?php Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
Should be
action="<?php echo Mage::helper("adminhtml")->getUrl("*/*/insert")?>"
Make sure you're using only normal PHP tags (<?php ?>). Short tags have proven to be a bad practice, so change
<input type="hidden" name="form_key" value="<? echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
to
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Along with that make sure you have all data correctly populated in your HTML using browse source feature in your browser.
Try to add this string to your form.
<input type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey()?>" name="form_key"/>
This creates a hidden parameter for the request, which contains the form_key used by Magento. This form_key is used to make sure the submitted form originated from your magento-instance (as a security measure). Without supplying this form_key, your form will not work.
Eric, your .phtml look fine....
Now you need see if the action url of your form are pointing to the right place, and do your controller like this one:
class controller_name extends Mage_Core_Controller_Front_Action{ // must extends this one for frontend controllers and Mage_Adminhtml_Controller_Action to backend controller.
public function insertAction(){
$_POST['elementName']; //to this to get post information.
$this->getRequest()->getPost('elementName'); //or this way.
}
}

cakephp two submit buttons and redirect

trying to create a form that has two submit buttons in cakephp.
task_1 submit button when clicked creates this in the address bar '/fields/add' and sends the information added to the database.
task_2 submit button when clicked creates this in the address bar '/fields/add/add' and sends the entered information to the database`.
task_1 is meant to allow users to keep creating new fields, where task 2 is meant to take them to a different page, at the moment we just chose a page at random.
here is the code for the add function in controller
function add(){
$this->set('title_for_layout', 'Please Enter Your Invoice Headings');
$this->set('stylesheet_used', 'style');
$this->set('image_used', 'eBOXLogo.jpg');
$this->Session->setFlash("Please create your required fields.");
if($this->request->is('post')){
$this->Field->create();
if ($this->Field->save($this->request->data))
{
if($this->params['form']['task_1'] == "task_1")
{
$this->Session->setFlash('The field has been saved');
$this->redirect( array('controller' => 'Fields','action' => 'add'));
}
if($this->params['form']['task_2'] == "task_2")
{
$this->Session->setFlash('The template has been saved');
$this->redirect( array('controller' => 'Invoices','action' => 'add'));
}
}
else
{
$this->Session->setFlash('The field could not be saved. Please, try again.');
}
}
}
here is the code for the add view
<form enctype="multipart/form-data" method="post" action="add/">
Name: <input type ="text" name="name" /> <br />
Description: <input type ="text" name="description" /> <br />
Account ID: <input type ="number" name="accounts_id" /> <br />
<br />
<input type="submit" name="task_1" value="Continue adding fields" />
<input type="submit" name="task_2" value="Finish adding fields" />
</form>
echo $this->Form->create('Field');
echo $this->Form->input('name');
echo $this->Form->input('description');
echo $this->Form->input('account_id');//this would be the conventional fk fieldname
echo $this->Form->button('Continue adding fields', array('name' => 'type_1'));
echo $this->Form->button('Finish adding fields', array('name' => 'type_2'));
echo $this->Form->end();

Contact form with file attachment?

I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.