I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.
Related
Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.
Here is part of the form:
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
Here is the script:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
data: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function () {
this.on("addedfile", function (file) {
console.log(file);
});
}
});
Here is the controller
public function upload_image(){
if ($this->input->post()) {
$this->invoice_items_model->add_image($this->input->post());
}
}
Here is the modal
public function add_image($data){
$dat = array(
'rel_name' => $data['name'],
'rel_type' => 'cms_items',
'dateadded' => date('Y-m-d H:i:s')
);
$this->db->insert('tblfiles', $dat);
}
For the one that need an answer:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sucess",function(file, xhr, formData){
});
},
dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
dictRemoveFile : "<?=_l('remove_file')?>"
});
I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.
I am running a Laravel 5 application that has its main view rendered using React.js. On the page, I have a simple input form, that I am handling with Ajax (sending the input back without page refresh). I validate the input data in my UserController. What I would like to do is display error messages (if the input does not pass validation) in my view.
I would also like the validation errors to appear based on state (submitted or not submitted) within the React.js code.
How would I do this using React.js and without page refresh?
Here is some code:
React.js code:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var SignupForm = React.createClass({
getInitialState: function() {
return {email: '', submitted: false, error: false};
},
_updateInputValue(e) {
this.setState({email: e.target.value});
},
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
},
saveAndContinue: function(e) {
e.preventDefault()
if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});
request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
success:function(data){},
});
setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000);
}
}
});
React.render(<SignupForm/>, document.getElementById('content'));
UserController:
public function store(Request $request) {
$this->validate($request, [
'email' => 'Required|Email|Min:2|Max:80'
]);
$email = $request->input('email');;
$user = new User;
$user->email = $email;
$user->save();
return $email;
}
Thank you for your help!
According to Laravel docs, they send a response with 422 code on failed validation:
If the incoming request was an AJAX request, no redirect will be
generated. Instead, an HTTP response with a 422 status code will be
returned to the browser containing a JSON representation of the
validation errors
So, you just need to handle response and, if validation failed, add a validation message to the state, something like in the following code snippet:
request = $.ajax({
url: "/user",
type: "post",
data: 'email=' + email + '&_token={{ csrf_token() }}',
data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
beforeSend: function(data){console.log(data);},
error: function(jqXhr, json, errorThrown) {
if(jqXhr.status === 422) {
//status means that this is a validation error, now we need to get messages from JSON
var errors = jqXhr.responseJSON;
var theMessageFromRequest = errors['email'].join('. ');
this.setState({
validationErrorMessage: theMessageFromRequest,
submitted: false
});
}
}.bind(this)
});
After that, in the 'render' method, just check if this.state.validationErrorMessage is set and render the message somewhere:
render: function() {
var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
return (
<div>
{this.state.submitted ? null :
<div className="overall-input">
<ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
<input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
<div className="validation-message">{this.state.validationErrorMessage}</div>
<div className="button-row">
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
</ReactCSSTransitionGroup>
</div>
}
</div>
)
}
I dont know what the problem is here, I try to append the content, but its not.
var InPro = false;
$(document).ready(function(){
var form = $('#form32');
var submit = $('#submit');
form.on('submit', function(e) {
if(InPro) return;
InPro = true;
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'post.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
InPro = false;
var item = $(data).hide().fadeIn(800);
$('#post-show').append(data);
$("#form32")[0].reset();
},
});
});
});
and here the post.php:
<?php
include_once("config.php");
include_once("verifica.php");
// No direct access to this file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
session_start();
$user = $_SESSION['user'];
$comment = $_POST['comment'];
if($comment==""){
die();
}
$ip = getenv("REMOTE_ADDR");
$data = date ("ymdHis");
$i=mysql_query("INSERT INTO posts (id, foto, user, titulo, youtube, button, data, ip) VALUES ('','0','$user','$comment','$youtube','$button','$data','$ip')");
$idpostfeed = mysql_insert_id();
echo"$comment";
?>
and my form:
<form id="form32" method="post"> <textarea name="comment" id="comment" class="comment" placeholder=""></textarea> <input type="submit" id="submit" class="button" value="Submit Comment"> </form> <div id=post-show></div>
so, I want to show result in #post-show div, but it is not working. what is wrong?
thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Hi I am really having a hard time on the new structures in laravel 5, I'm trying to submit a form via AJAX post but I keep getting error 422 (Bad Request). Am I missing something or do I need to do something with my Request class? Here is my code:
Controller:
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect("/");
}
return response()->json(['errors'=>$request->response]);
}
LoginRequest file (I added a custom response method which is):
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson())
{
return response()->json($errors, 422);
}
return response()->json($errors);
}
My ajax code:
$("#form-login").submit(function(){
var selector = $(this);
$.ajax({
url: selector.attr("action"),
type: "post",
data: selector.serialize(),
dataType: "json",
}).done(function(data){
console.log(data);
if(data.status == "failed"){
alert("error");
}else{
alert("success");
}
});
return false;
});
So My problem is that when I submit my form all I can see from my console is - Failed to load resource: the server responded with a status of 422 (Bad Request)
Please if anyone can help. Thanks in advance!
I had a similar problem, I'll leave here the code that I ended up with.
the form:
<div class="container">
<div class="text-center">
<div class="title">{!!HTML::image("img/HERLOPS_Transparent_Blue.png") !!}</div>
{!! Form::open(['data-remote','url' => '/auth/login', 'class' => 'col-lg-4 col-lg-offset-4', 'id' => 'login_form']) !!}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Your Password">
</div>
<button id="submit" type="submit" class="btn btn-primary">Login <i class="fa fa-sign-in"></i></button>
<div style="clear:both">
<a class="btn btn-link" href="{{ url('/password/email') }}">Forgot Your Password?</a>
</div>
{!! Form::close() !!}
<div style="text-align:center" class="col-lg-4 col-lg-offset-4" id="form-errors"></div>
<div style="clear:both"></div>
<div class="quote">{{ Inspiring::quote() }}</div>
</div>
</div>
The jquery:
(function() {
var submitAjaxRequest = function(e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST'; //Laravel Form::open() creates an input with name _method
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(NULL, NULL, jqXHR) {
if(jqXHR.status === 200 ) {//redirect if authenticated user.
$( location ).prop( 'pathname', 'projects' );
console.log(data);
}
},
error: function(data) {
if( data.status === 401 ) {//redirect if not authenticated user
$( location ).prop( 'pathname', 'auth/login' );
var errors = data.responseJSON.msg;
errorsHtml = '<div class="alert alert-danger">'+errors+'</div>';
$( '#form-errors' ).html( errorsHtml );
}
if( data.status === 422 ) {
//process validation errors here.
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></di>';
$( '#form-errors' ).html( errorsHtml );
} else {
}
}
});
e.preventDefault();
};
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
And finally the method of the controller that handles the ajax login request,
/**
* Handle an ajax login request to the application
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);// Returns response with validation errors if any, and 422 Status Code (Unprocessable Entity)
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials))
{
return response(['msg' => 'Login Successfull'], 200) // 200 Status Code: Standard response for successful HTTP request
->header('Content-Type', 'application/json');
}
return response(['msg' => $this->getFailedLoginMessage()], 401) // 401 Status Code: Forbidden, needs authentication
->header('Content-Type', 'application/json');
}
I was actually just struggling with this myself, and the answer is pretty simple actually.
Because Laravel's request responds with a status code of 422, jQuery's success/done functions don't fire, but rather the error function, seeing as it's not 200.
So, in order to get the JSON response from your AJAX request generated from the Request object due to validation failing, you need to define the error handler, in your case as follows:
$.ajax({ /* ... */ })
.done(function(response) { /* ... */ })
.error(function(data) { // the data parameter here is a jqXHR instance
var errors = data.responseJSON;
console.log('server errors',errors);
});