Controller method is not detecting any parameter - javascript

I'am trying to send an id in my url but my controller doesn't get that value
$("#ChangeSlideForm").on("submit", function(){
$.ajax({
type: "POST",
url: base_url + "Visualiser/ChangeSlide/21",
success: function (response) {
alert(response);
// $("#deleteConfirm").modal('hide');
// jQuery(function RefreshPageAdd($){
// $('#deleteConfirm').on('hidden.bs.modal', function (e) {
// location.reload();
// });
// });
}
});
});
My View
<div id="bodyChange" class="modal-body">
<form id = "ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<label class="btnSlide btn btn-outline-success">
Zip <input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success">
Csv <input class="file" name ="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</form>
My controller header :
public function ChangeSlide($id){
print_r($id);
}
When I a put the id in the url directly then the parameter is accessible otherwise when I pass with ajax, It doesn't detect the parameter.

Try this:-
The HTML
<form id="ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide/21" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="bodyChange" class="modal-body">
<label class="btnSlide btn btn-outline-success"> Zip
<input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success"> Csv
<input class="file" name="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</div>
</form>
The Script:
<script type="text/javascript">
$(document).ready(function(){
$("#ChangeSlideForm").on("submit", function(e){
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serializeArray(),
success : function(data)
{
console.log(data)
},
error: function (xhr)
{
console.log(xhr)
}
});
});
})
</script>

Try this
public function ChangeSlide(){
print_r($this->uri->segment(3));
}

You missing parameter data in $.ajax(). So your ajax didn't send any data to your controller

When you pass value with ajax then controller method get that value as $this->input->post('id'); not as parameter.
So you have to add following to method
public function ChangeSlide($id = "")
{
}

Related

Javascript - one button call ajax and one button submit form using html5 form validation

I have a form that I want to use the required attribute, which I believe is from html5 to make sure the user puts in a name before running the ajax to send and email and stays on this page (index.php). The form below works. My problem is that I can't figure out how to a a button called pay that submits the form to pay.php like a regular form submit so the user ends up on pay.php when they click "pay" and I want the form validation to still occur when they click pay and on pay.php I can grab the contactName from the post.
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<div id="mail-status"> </div>
</form>
<script type="text/javascript">
$("inquire-button").on('click',function(e){
e.preventDefault();
});
$("#contactForm").on('submit',function(e){
sendContact();
e.preventDefault();
});
function sendContact() {
jQuery.ajax({
url: "mailer.php",
data:'contactName='+$("#contactName").val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
</script>
EITHER don't use the click, but only the submit event
$("#contactForm").on('submit', function(e) {
const $btn = $(document.activeElement);
if ($btn.is("#inquire")) {
console.log("Inquire clicked")
e.preventDefault();
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
}
else console.log("Pay clicked")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>
OR use a button
$("#contactForm").on('submit', function(e) {
console.log("Submitted (pay)")
})
$("#inquire-button").on("click", function() {
if (!this.form.checkValidity()) {
this.form.reportValidity()
return
}
console.log("Inquire clicked")
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="button" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>

Submit form without form id

I need to submit form using through Ajax call but I'm having trouble selecting the form. I don't want to use form ID because I'm having multiple forms and I need to setup one code for all
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
//$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card" >
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
No need to add form submit code because you are preventing submit, so when will you click just fetch data from the form and call your AJAX service.
I added one console log where you can see your form data.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
var formData = $(form).serialize();
console.log(formData);
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
This will help you to reduce duplicating the code..
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
Var action = $(this).action;
Var method = $(this).method;
Var data = $(this).serialize();
// perform ajax operation here with data, action and method
});
});
Happy coding :)
Your code is creating submit handler everytime the button is clicked, all you want is to send ajax call onclick, so just do that part.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
// below code is creating submit handler everytime the button is clicked
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
});
});
Also .find returns jQuery object, no need to make it Jquery object again, simple form will do instead of $(form).. rather declare like var $form = $(this).closest(".card-body").find("form")
Something like below, try
$(".pay").on("click",function(){
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
function submitForm(formData){
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
}
I've created below sample to refer
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
console.log(formData)
submitForm(formData);
});
function submitForm(formData) {
alert("submitting form with " + formData)
$.ajax({
type: 'POST',
url: "php/pay.php",
data: formData
})
.done(function(response) {})
}
});
.card {
width: 50%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h1>YYY</h1>
</div>
<div class="card-body">
<form>
<input name="user2" value="mat2" type="hidden">
<input name="id2" value="122" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay2</button>
<button class="btn btn-danger decline" value="decline">decline2</button>
</div>
</div>
Erm.. Why not just put the two buttons inside the form, to avoid any confusion or off-chance that the script might trigger another one of the "multiple forms" and refer to the nameless form through the parent element instead, like?
html:
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</form>
script:
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).parent();
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});

Dynamically Pass Form ID Into Function

I have several forms on a page and i want to utilize the same ajax function. It works great for one form since I am grabbing the id with getElementById and then passing it to my ajax function. What I am trying to do is pass down the id of the form onSubmit dynamically.
form
<form id="postData" name="business" method="post" action="{{ path('location_graph', {'location_id': location.getId }) }}"
class="m-form m-form--fit m-form--label-align-right">
<div class="form-group m-form__group row">
<label class="col-2 col-form-label required" for="description">Business
Description</label>
<div class="col-7">
<input type="text" class="form-control m-input" id="description"
name="extra[description]">
</div>
</div>
...
<div class="form-group m-form__group row">
<button type="submit" class="btn m-btn--square btn-outline-primary">
Submit
</button>
</div>
</form>
script
document.getElementById('postData').addEventListener('submit', postData);
function postData(event) {
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
You can attach a submit event handler to each of the forms and pass event and this.id (the id of the form element) as arguments.
Javascript:
function postData(event, id) {
event.preventDefault();
var elem = $('#'+id);
$.ajax({
type: elem.attr("method"),
url: elem.attr("action"),
data: elem.serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
HTML:
<form id="someid" onsubmit="postData(event, this.id)">

Error 500 on return all in Laravel Controller

Hi I am trying to send form data using ajax to my controller in Laravel. In my controller I am trying to return $request->all() to see if the form data is present. I am getting an error 500 internal server error and I am not sure why. I have setup my Exceptions/Handler.php to receive errors and also checked the error log.
Here is my HTML and Ajax:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click", function(e){
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my controller:
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200)
}
missing ;
public function create(Request $request) {
$request->all();
return response()->json(['responseText' => 'Success!'], 200); //<--here
}

Uploading image using ajax to submit form taking a lot of time

Basically I am using html form for uploading image on server. Below is my code for form:
<div class="modal modal-fixed-footer" id="modal-image">
<div class="modal-content">
<h3>Upload Image</h3>
<form id="uploadimg" enctype="multipart/form-data">
<input type="hidden" name="entity" value="order">
<input type="hidden" name="orderId" value="<?php echo $orderId; ?>">
<input type="hidden" name="status" value="<?php echo $json->response->body->order->status; ?>" />
<input type="hidden" name="url" value="order-details.php?order=<?php echo $orderId; ?>&e=0">
<div class="form-inputs p-l-r-0">
<div class="row">
<div class="col s12">
<div class="file-field input-field" style="display:none">
<div class="btn accent-color">
<span>File</span>
<input type="file" id="fileToUpload" name="fileToUpload[]" multiple="multiple">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more images">
</div>
</div>
</div>
</div>
<div id="dvPreview" class="row"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn-flat modal-action modal-close" id="uploadimg-submit">Submit</button>
<button class="btn-flat modal-action modal-close">Close</button>
</div>
Now when the #uploadimg-submit is clicked below jquery code is executed:
$('#uploadimg-submit').on('click', function(e) {
e.preventDefault();
$("form#uploadimg").submit();
});
and form submit function:
$("form#uploadimg").submit(function(e2) {
var smoothState = $('#main').smoothState().data('smoothState');
e2.preventDefault();
var formData = new FormData($(this)[0]);
// console.log(formData);
$.ajax({
url: 'processors/process-upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
ajaxindicatorstart();
},
success: function(rsp) {
if (rsp == '200') {
Materialize.toast('Image Uploaded Successfully', 2000, 'green');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
} else {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
},
error: function() {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
});
return false;
});
The file process-upload.php takes less than a second to process the image which i debugged using microtime(true). But total time take by sending request and recieving response is nearly 11 secs, majority of which (about 9 secs) is taken in sending request. Below are timeline analytics from chrome dev tools.
I want to reduce this time else it will be unfeasible to wait so long for uploading image. Is there any way I can optimize it further?

Categories