I'm trying to create a form that submits pictures to database using Ajax.
The form is defined in function "new_pic" that is neither accepted nor returning errors when a picture is submitted.
After clicking submit button the flash message "please fill the form" is returned.
Please tell what did I do wrong?
db.py:
db.define_table('input_images', \
Field('action_id', type='string', unique=False, compute=lambda r: action_id ),\
Field('picture', 'upload', uploadfield='picture_file')),\
Field('picture_file', 'blob'),\
primarykey=['action_id']\
)
default.py:
import uuid
action_id = str(uuid.uuid4())
def index:
return dict()
def new_pic():
form = SQLFORM(db.input_images, buttons=[])
if form.process(session=None, formname='test').accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill the form'
return dict(form=form)
index.html:
<div class="inner">
<form id="myform" action="#" enctype="multipart/form-data" method="post">
{{=LABEL('Upload picture', _for='picture', _class='button-25')}}
{{=INPUT(_id='picture', _name='picture', _type='file')}}
<div id="sbmt_picture">
{{=INPUT(_id='submit_btn', _name='submit_btn', _type='submit', _class='button-25')}}
</div>
<input type="hidden" name="_formname" value="test" />
</form>
</div>
<script>
jQuery('#myform').submit(function() {
ajax('{{=URL('new_pic')}}', ['picture'], 'trgt');
return false;
});
</script>
<div id="trgt"></div>
The problem was in the JS. I just found another kind of this element here: https://stackoverflow.com/a/28386477/13128766
That works for me:
<script>
jQuery(document).on("submit", "form", function(event)
{
event.preventDefault();
jQuery.ajax({
url: "{{=URL('new_pic')}}",
type: jQuery(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
</script>
Related
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();
}
I have uploaded an image to the server without page load. My question is that what is the best way to display it after successful upload in the browser without page load ??
html part---->
<form method="post" data-remote="true" accept-charset="UTF-8" action="/update_profile_image" enctype="multipart/form-data" id="edit_user_72" class="edit_user">
<div>
<input type="file" id="user_avatar" name="user[avatar]" as="file">
</div>
<input type = "button" value ="Update" id= "update-img"
onclick ="AjaxUpdateImage($('form').attr('action'),$('form').attr('id'))" />
</form>
ajax part--->
function AjaxUpdateImage(url,id) {
var formData = new FormData($('#'+id)[0]);
$.ajax({
type: "POST",
url: url,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data: formData, // serializes the form's elements.
success: function(data)
{
console.log(data);
},
error: function (data)
{
console.log(data)
}
})
server part (ruby on rails)---->
def update_profile_image
id = params[:user][:attr].to_i
#user = User.find(id)
#response = #user.update_attribute(:avatar, params[:user][:avatar])
respond_to do |format|
format.json { render json: #response }
end
end
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've this form
<form id="frm_main" action="#" method=POST>
<input type=hidden name="MAX_FILE_SIZE" value="100000" />
<input id='file' name="file" type="file">
<input type=submit id='btn_import' name='btn_import' value='Importar' />
<input type=hidden id="uploadResponseType" name="mimetype" value="html" />
<input type=hidden id="func" name="func" value="upload" />
<div id="uploadOutput"></div>
</form>
So, the problem became when I try to post the upleaded file. If I use ajaxSubmit function the form is submited but it doesn't return to the page; and if I use $.ajax function, it doesn't sent the uploeade file. The thing is that I need to return to the same page because I've to do some stuff with the file content. I've already tried lot of combinations but I'm still having the same results. The code to handle submit look like this
$( '#frm_main' ).bind( 'submit', function( e ) {
// e.preventDefault(); // <-- important
$( this ).ajaxSubmit({
target: '#uploadOutput', // <-- div container
type: "POST", // <-- override, just in case.
url: "/process.php", // <-- server-side handler
data: "func=upload", // <-- parameter for post purpouse
beforeSubmit: function(a,f,o) {
o.dataType = $('#uploadResponseType').val(); // should be 'html'.
$('#uploadOutput').html('Submitting...');
},
success: function(data) {
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
$out.append('<div><pre>'+ data +'</pre></div>');
}
});
return false;
});
And I've already tried with next code
$('#frm_main').bind('submit', function() {
var formdata = $(this).serialize();
$.ajax({
url: '/process.php',
data: formdata,
dataType: 'html',
success: function(data){
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
}
});
return false;
});
And process.php code looks like this
switch($_POST['func']) {
case 'upload' :
$output = upload_file ();
echo $output;
break;
default :
echo "<BR/>INVALID";
break;
}
?>
Can somebody help me with this situation, please? Any help will be gratefully appreciated
Don't you need form enctype="multipart/form-data" to upload files?
I have a form with two input fields, one text and one send button. I want to submit via jQuery .ajax() without reloading the document.
It works as long as the button is clicked, but not when you press return/enter, then it submits without ajax methodology. I tried onEnter() or onSubmit(), but that didn't work either.
These are the code bits:
//HTML
<div id="search_form">
<form method="POST" action="search.php">
<input id="search_text" type="text" name="query"/>
<input id="search_button" type="button" value="send"/>
</form>
</div>
<div id="results"></div>
//Javascript
jQuery(function(){
$("#search_button").click(function(){
var query = "query="+$("input[name=query]").val();
$.ajax({
type: "GET",
url: "request.php",
data:query,
cache:false,
success: function(result){
$('#results').fadeIn();
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
});
Instead of a click on the button, rig up to the submit event on the <form>, like this:
$(function() {
$("#myFormId").submit(function() {
$.ajax({
type: "GET",
url: "request.php",
data: $(this).serialize(),
cache: false,
success: function(result){
$('#results').fadeIn();
},
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
return false;
});
});