I am new to the Laravel and I am trying to submit post data via Ajax in Laravel and it throws
MethodNotAllowedException but when I submit the form via post it does work but refresh the page although I have used Ajax.
my Code is as below:
My JavaScript Ajax code:
function collect(){
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $("input#token").val()
}
});
const user = [{"fname": $("input#fname").val(), _token: $("input#token").val(), _method:"POST", "lname": $("input#lname").val(),
"email": $("input#email").val(), "pass": $("input#pass").val(),
"confirm-pass": $("input#confirm-pass").val()
}];
var form = $('form#add-user-form');
var send_button = $('button#send').text();
$.ajax({
url: '/users/store',
method: 'post',
data: user,
processData: false,
dataType: 'json',
contentType: false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
success:function(data){
alert('data sent');
if (data.code == 0 || data.status == 400 ){
$.each (data.error, function(prefix, value){
alert(prefix + ' ' + value[0]);
$(form).find('span.'+prefix+'_error').text(value[0]);
});
}else {
$(form)[0].reset();
alert(data.msg)
}
}
});
}
--- Controller Code ------------------------
$validator = \Validator::make($request -> all(), ['fname' => 'required|min:5|max:25',
'lname' => 'required|min:5|max:25',
'email' => 'required|email|unique:users',
'pass' => 'required|min:8|max:20|',
'confirm-pass' => 'required|min:8|max:20'
]);
if (!$validator -> passes() ){
return response()->json(['code'=> 0, 'error'=> $validator->errors()->toArray()]);
}else {
$user = new users();
$user -> name = $request -> fname ;
$user -> email = $request -> email ;
$user -> password = $request -> pass;
$query = $user -> save();
if ( !$query ){
return response() -> json(['code'=> 0, 'msg' => 'something went wrong']);
}else {
return response() -> json(['code' => 1, 'msg' => 'users has been successfully
added']);
--------------- HTML Code which -------------
<div id="registeration-form">
<div id="form-holder container">
<form action="{{ route('users.store') }}" method="post" class="registration needs-`
validation" id="add-user-form">
<input type="text" class="form-control" id="fname" name="fname" placeholder="
First Name" required> </input>
<span class="text-danger error-text fname_error"></span>
<input type="text" id="lname" class="form-control" name="lname" placeholder="
Last Name " required> </input>
<span class="text-danger error-text lname_error"></span>
<input type="text" class="form-control" id="email" name="email"
placeholder="Your Email " required> </input>
<span class="text-danger error-text email_error"></span>
<input type="password" class="form-control" id="pass" name="pass"
placeholder="Password " required> </input>
<span id="text-danger error-text pass-span pass_error"> </span>
<input type="password" class="form-control" id="confirm-pass" name="confirm-
pass" placeholder="Confirm Password " required> </input>
<span id="text-danger error-text con-pass confirm-pass_error"> </span>
<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}" />
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect();">Create Account </input>
</form>
</div>
</div>
My Route web.php file
Route::post('/store', 'usersController#store');
Route::post('store',[usersController::class, 'store'])->name('users.store');
What I want is that the Ajax should work without page refresh and
> it does through MethodNotAllowedException Line 251
Thank you all for your cooperation in this matter, I have resolved this issue with below changes.
I have added a route in route/api.php
Route::post('store', [usersController::class,'store']);
I have changed my Ajax sent url as below.
url: $('form#add-user-form').attr('action'),
That worked for me to resolve the issue.
#steven7mwesigwa Thank you for your answer, it was really helpful.
You must provide route for ajax request into route/api.php
use this instead of your current ajax configs:
url: '{{route('users.store')}}',
type: 'post',
data: user,
processData: false,
dataType: 'json',
contentType: false,
first of all it's better to use blade routes instead of writing the url, and secondly it's "type" not "method" when you're trying to use POST method in ajax
The route below doesn't exist.
$.ajax({
// ...
url: '/users/store',
// ...
});
Use this instead:
Note that you don't have to construct the data manually.
$.ajax({
// ...
type: form.attr("method"),
url : form.attr("action"),
data: form.serializeArray(),
// ...
});
NOTES:
Note that the 2 routes are the same:
Route::post('/store', 'usersController#store');
Route::post('store',[usersController::class, 'store'])->name('users.store');
You may want to remove one of them. If you're working with Laravel 8 and above, the format used in the second one is preferable.
Though not necessary, you may want to include the HTML markup below in your form as well. The value sent with the _method field will be used as the HTTP request method.
<input type="hidden" name="_method" value="POST">
I believe you have mismatching HTML tags on your submit button.
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect();">Create Account </input>
To avoid page reload. pass the event to the method call. In addition, prevent the default behaviour from your method definition.
<!-- HTML code. -->
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect(event);">Create Account </button>
// JavaScript Ajax code.
function collect(event){
event.preventDefault();
$.ajax({
// ...
});
// ...
}
Related
I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>
try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem
So I have a simple form where I ask the user some info to register and make an account, this is the part of the form I am using to achieve that:
<form class="login-form2" action="index.html">
<div class="center sliding"><img style='width:20%; margin: 42%; margin-top: 8%; margin-bottom: 0%;'src="./images/logoTemporal.png"></div>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<!-- Name -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input type="text" id="Name" name="Name" class="form-control" placeholder="Name or Name.Corp" autofocus>
</div>
<!-- Email -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="email" id="Email" name="Email" class="form-control" placeholder="Email">
</div>
<!-- Passwrod -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" id="Password" name="Password" class="form-control" placeholder="Password">
</div>
<!-- Confirm password -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" class="form-control" placeholder="Confirm Password">
</div>
<!-- Tipo -->
<div class="item-content input-group-addon">
<div class="item-media"><i class="icon f7-icons">Tipo Usuario</i></div>
<br>
<div class="item-input">
<select id="Tipo" name="Tipo">>
<option value="0" selected>Empresa</option>
<option value="1">Usuario</option>
</select>
</div>
</div>
<br>
<!-- Button-->
<!-- <a class="btn btn-primary btn-lg btn-block" href="register.html">Register</a> -->
<p> <input type="button" class="btn btn-primary btn-lg btn-block" id="signup" value="Send"/></p>
</div>
</form>
I am trying to get the values into some variables in a jc, but for some reason I am not getting them:
$(document).ready(function() {
$("#signup").click(function() {
alert("Im in the function");//this is the only alert showing when I test the page...
//From here on it is not working
var Name = $('#Name').val();
var Email = $('#Email').val();
var Password = $('#Password').val();
var Tipo = $('#Tipo').val();
if (Name == '' || Email == '' || Password == '' || Tipo == '')
{ alert("please complete the information"); }
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: 'dummy url',
crossDomain: true,
beforeSend: function(){ $mobile.loading('show')},
complete: function(){ $mobile.loading('hide')},
data: ({Name: Name, Email: Email, Password: Password, Tipo: Tipo}),
dataType: 'json',
success: function(html){
alert("Thank you for Registering with us! you
can login now");
},
error: function(html){
alert("Not Working");
}
});
}//else end
});
});
I am still trying to learn many things here but what I need to know is why the variables are not getting the values from the form, could be something dumb but I just cant see it... Would appreciate some help...
EDIT:
Adding my php code, now I get an error when trying to send the data to my host´s php using JSON, the javascript prints the "not working" alert, what I think is that my php is not really getting the json so its not working but im not 100% sure so here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
require 'data/DataCollector.php';
$varData = json_decode($data);
$Name = $varData->Name;
$Email = $varData->Email;
$Password = $varData->Password;
$Tipo = $varData->Tipo;
$database = new DataCollector([
'database_name' => 'dummy url',
'server' => 'dummy server',
'username' => 'dummy username',
'password' => 'dummy password',
'charset' => 'utf8',
]);
if($_POST){
$database->insert("Usuario", [
"nombre" => $_POST[$Name],
"email" => $_POST[$Email],
"password" => $_POST[$Password],
"tipoUsuario" => $_POST[$Tipo]
]);
}
?>
I have never used JSON and I am trying to learn about it, there is probably A LOT of issues with my code but any help will be very much appreciated! thanks!
your dictionary does not seem to be correct.
try this:
data: {"Name": Name, "Email": Email, "Password": Password, "Tipo": Tipo}
I am developing a login page for our mobile app using Phone gap. But whenever I clicked the Submit button, an error 'Cannot POST /' appears. Why is that so? Please see my code below.
index.html
<body>
<div class="main-info2">
<h3>Sign In</h3>
<div class="in-form">
<form id="login_form" method="post"">
<input type="text" placeholder="Username" required=" " id="email" />
<input type="password" placeholder="Password" required=" " id="password" />
<div class="check-sub">
<input type="submit" value="Login" id="login">
</div>
</form>
</div>
</div>
<div class="copy-right">
<p>Design by W3layouts</p>
</div>
</div>
<!-- //main -->
</body>
login.js
$(document).ready(function(){
do_login();
});
function do_login() {
$("#login").click(function () {
var email = $('#email').val();
var password = $('#password').val();
var dataString="email="+email+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0){
$.ajax({
type: 'POST',
url: "http://localhost:1234/cleverpro/login.php",
dataType: 'json',
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data == "success"){
console.log("hay nako!");
alert("hala");
}else if(data == "failed"){
$("#login").html('Login');
console.log("hastang sayupa");
alert("halajud");
}
}
});
}else{
return false;
console.log("walay sulod uy");
}
});
}
login.php
<?php
include "db.php";
if(isset($_POST['login'])){
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login=mysql_num_rows(mysql_query("select * from `user` where `email`='$email' and `password`='$password'"));
if($login!=0){
echo "success";
}else{
echo "failed";
}
}
?>
I didn't know where did I gone wrong with this. Please help me.
First of all it would be better to use on('submit', handler) instead on click. (see Whats the difference between onclick and onsubmit?)
When you clicks "Login", default form send action happens after your javascript code finishes. It means that form POST happens to 'action' of your form that is not set in your form and is '/' by default.
You need to preventDefault action, somethink like this
$('#login_form').on('submit', function(e) {
e.preventDefault();
//Your code
});
I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....