I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}
Related
I am trying to add some custom logic to my semantic ui validation but can't figure out what I am doing wrong.
Basically, when the user selects "Yes" from the drop-down, I would like to make the "input_field" mandatory. If the user selects "No", the "input_field" becomes optional and the form can be submitted.
I tried searching for examples and followed some code from the Semantic Ui website but can't figure out what I am missing. Any advice would be appreciated as I am on a deadline for a project I am working on.
Form:
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
Validation:
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
},
input_field: {
identifier: 'input_field',
depends: 'select',
rules: [
{
type: 'empty',
prompt: function() {
$('.select').on('change', function() {
if( this.value == 'Yes') {
return "Custom Validation";
}
return false;
}).trigger("change");
}
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
});
</script>
Figured out a solution for this! It might not be the best answer but it works and does what I am looking for.
<div class="ui dimmer">
<div class="ui huge text loader">Loading</div>
</div>
<form method="post" action="" class="ui form" autocomplete="on">
<div class="ui segment">
<div class="ui two fields">
<div class='field'>
<div class="ui selection dropdown">
<input type="hidden" class="selectOption" name="select">
<i class="dropdown icon"></i>
<div class="default text">Select an option</div>
<div class="menu">
<div class="item" data-value="Yes">Yes</div>
<div class="item" data-value="No">No</div>
</div>
</div>
</div>
<div class="field">
<input id="input_field" name="input_field" type="text"/>
</div>
</div>
</div>
<button id="submit" class="ui green button" name="submit" type="submit">Submit</button>
</form>
<script>
$('.ui.form').form({
keyboardShortcuts: false,
on: 'blur',
inline: 'true',
fields: {
selectOption: {
identifier: 'select',
rules: [
{
type: 'empty',
prompt: 'Please select an option'
}]
}
},
onSuccess: function() {
$('.ui.dimmer').dimmer('show');
},
onFailure: function() {
event.preventDefault();
}
}
);
$('.selectOption').on('change', function() {
if ( this.value == 'Yes' ) {
$('.ui.form').form('add rule', 'input_field', ['empty', 'integer']);
$('.ui.form').form('add prompt', 'input_field', 'Enter an integer');
}
if ( this.value == 'No' ) {
$('.ui.form').form('remove prompt', 'input_field');
$('.ui.form').form('remove rule', 'input_field');
}
}).trigger("change");
});
</script>
I was able to implement the validation rule by extending Semantic UI setting rules.
See below example:
$.fn.form.settings.rules.dependsOnFieldValue = function (value, dependFieldValue) {
var identifier = dependFieldValue.split('[')[0];
var dependValue = dependFieldValue.match(/\[(.*)\]/i)[1];
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? !( dependValue.toString() === matchingValue.toString() && value === '')
: false
;
};
Then in the form validation initializer you will pass the desired values as below:
$(".ui.form").form({
fields: {
select: {
identifier: 'select',
rules : [
{
type : 'empty'
}
]
},
input_field: {
identifier : 'input_field',
rules : [
{
type : 'dependsOnFieldValue[select[Yes]]',
}
]
},
...
}
});
Notice that we pass the <select> identifier (in this case also called select) within the first [] and then the value that we want to see to make the input_field mandatory ("Yes" in this case).
The form below sends images/files to Mongodb using the handlelebars (.hbs) engine and multer-gridfs-storage (Mongodb FIles), but by clicking delete it generates the following error:
TypeError: gfs.deleteOne is not a function
Also, it does not load the thumbnail of the attached photo
Ps: I think the error is in HBS form.
Full code :
https://github.com/rebek/upFileHBS
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" name="file" id="file" class="custom-file-input">
<label for="file" class="custom-file-label">Choose File</label>
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
{{#each files}}
<div class="card card-body mb-3">
{{#if file.isImage}}
<img src="image/{{this.filename}}" alt="">
{{else}}
{{this.filename}}
<form method="POST" action="/files/{{this._id}}?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
{{/if}}
{{/each}}
</div>
</div>
</div>
app.get('/', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
res.render('index', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'image/jpeg' ||
file.contentType === 'image/png'
) {
file.isImage = true;
} else {
file.isImage = false;
}
});
res.render('index', { files: files });
}
});
});
...
app.delete('/files/:id', (req, res) => {
gfs.deleteOne({ _id: req.params.id, root: 'uploads' }, (err, GridFSBucket) => {
if (err) {
return res.status(404).json({ err: err });
}
res.redirect('/');
});
});
gfs.files.deleteOne({ filename: req.params.filename}, (err) => {
if (err) return res.status(500).json({ success: false })
return res.json({ success: true });
})
using the above will delete the file
I am super new to React and quite new to Meteor.
I am doing a Meteor.call to a function ('getTheThing'). That function is fetching some information and returns the information as a response. In my browser I can see that the method is returning the correct information (a string), but how do I get that response into the DOM?
(As you can see, I have tried to place it in the DOM with the use of ReactDOM.findDOMNode(this.refs.result).html(response);, but then I get this error in my console: Exception in delivering result of invoking 'getTheThing': TypeError: Cannot read property 'result' of undefined)
App = React.createClass({
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
ReactDOM.findDOMNode(this.refs.result).html(response);
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">
</div>
</div>
</div>
);
}
});
this is under the different context, thus does not contain the refs there. Also, you cannot set html for the Dom Element. You need to change into Jquery element
var _this = this;
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
$(ReactDOM.findDOMNode(_this.refs.result)).html(response);
});
Though i recommend you to set the response into the state and let the component re-rendered
For a complete React way
App = React.createClass({
getInitialState() {
return { result: "" };
},
shouldComponentUpdate (nextProps: any, nextState: any): boolean {
return (nextState['result'] !== this.state['result']);
},
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
_this.setState({ result: response });
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">{this.state['result']}</div>
</div>
</div>
</div>
);
}
});
I have a RESTful API based application with Laravel 4 and Angular.js.
The application's CRUD processes are handled by angularjs $http service.
The Backend Side (Laravel 4):
Routing : app/routes.php
//.....
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
//....
Route::resource('pages', 'PagesController');
//....
});
//.....
Controller : app/controllers/api/PageController.php
<?php
//.....
class PagesController extends BaseController {
//......
public function update($id) {
$page = Page::find($id);
if ( Request::get('title') )
{
$page->title = Request::get('title');
}
if ( Request::get('slug') )
{
$page->slug = Request::get('slug');
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
//......
}
Calling : cURL
This update function can be accessed using cURL method also.
curl -i -X PUT --user admin:admin -d 'title=Updated Title' localhost/laravel/index.php/api/v1/pages/2
Front-end : HTML
<!-- Top Code -->
<!-- From to Add/Edit Pages -->
<form class="form-horizontal" role="form" ng-show="edit" ng-submit="updatePage(entry)">
<!-- Page Title -->
<div class="form-group">
<label class="col-lg-2 control-label">Page Title</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.title}}" ng-model="entry.title">
</div>
</div>
<!-- Slug -->
<div class="form-group">
<label class="col-lg-2 control-label">Slug</label>
<div class="col-lg-4">
<input type="text" class="form-control" value="{{entry.slug}}" ng-model="entry.slug">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
<!-- Bottom Code -->
Client-side : angularjs
// ......
function pageCtrl($scope, $http, Data) {
//.........
$scope.updatePage = function(entry) {
$http({method: 'PUT', url: Data.root_path + 'api/v1/pages/'+id}).
success(function(data, status, headers, config) {
//
}).
error(function(data, status, headers, config) {
//
});
}
//.........
}
Question:
How can I pass my form data(more than one values) to the $http.put request
here ?
How can I access the PUT request data in Laravel 4 Controller ? Can
I use Input::get() ?
Need some update in your html to get page id to update. Add the following html inside form.
<input type="hidden" ng-model="entry.id" value="entry.id"/>
Then change angular script to,
$scope.updatePage = function(entry) {
$http.put(Data.root_path + 'api/v1/pages/' + entry.id, entry)
.success(function(data, status, headers, config) {
//
})
.error(function(data, status, headers, config) {
//
});
}
And in your Laravel Controller,
public function update($id) {
$page = Page::find($id);
$input = $input = Input::all();
if ( $input['title'] )
{
$page->title = $input['title'];
}
if ( $input['slug'] )
{
$page->slug = $input['slug'];
}
$page->save();
return Response::json(array(
'error' => false,
'message' => 'Page Updated'),
200
);
}
so what i am trying to do, is after the user submit some information, i make a call to a action call saveronda, to save the information on the database, after saving i want to redirect to another page, according to the firebug the html is correct, but the view isnt refreshing.
so here is the code
so in my /rondas/chooseronda ive got this
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
when the user press the button submit i am making an ajax call to /rondas/saveronda and send some data, here is the code:
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
/*
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
*/
//buscar o nome
/*var nomeronda=$("#nomeronda").val();
//buscar a ordem
var ordem=$("#ordem").val();
//tag inicial e tag final
var taginicial=$("#tagini").val();
var tagfinal=$("#tagfim").val();
if(taginicial==tagfinal)
{
alert("a tag inicial não pode ser a mesma que a tag final");
}
else
{
var tags="";
//var allRowsOnCurrentPage = $('#toolbar2').getDataIDs();
var ids = $("#toolbar2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $('#toolbar2').jqGrid ('getRowData', rowId);
tags=tags+rowData.id_tag.toString()+' ';
}*/
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: "sasa"},
datatype: "json"
});
//}
});
});
</script>
in this case i am sending param1 with the value "sasa", and through firebug i am detecting the post to the /rondas/saveronda.
after saving the data i want to redirect the user to /rondas/list, so i have been trying different solution
public function saverondaAction()
{
// action body
/*
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
$param3 = $this->_request->getParam('param3');
$param4 = $this->_request->getParam('param4');
$param5 = $this->_request->getParam('param5');
$rondasModel= new Application_Model_Ronda();
$this->_forward('list', 'rondas');
}
*
*/
$this->_helper->redirector->gotoRoute(
array(
'controller' => 'rondas',
'action' => 'list'
)
);
}
or using redirect or forward..
none have worked, the view is still the /rondas/choosetags and not /rondas/list
what is my error...
thanks in advance..
Your initial view is /rondas/chooseronda when user press submit you make ajax call to /rondas/saveronda and send some data to it. Now if this is successful you want to redirect from the initial page (/rondas/chooseronda) to /rondas/list.
If the redirect code written in action /rondas/saveronda is not working, then you could return a success message back to initial view (/rondas/chooseronda), there you'll need to detect the success message in jQuery ajax code. If successful, put the redirect jQuery code, that will redirect it to /rondas/list.