I want to add something to database using Ajax. I have a link which submits the form and then Ajax call should work, but it's not. I use this same Ajax call on different page, but in that form I'm using simple button with type submit. But on this page, I want to submit with ...
This is the form
{!! Form::open(['id' => 'ajax-form', 'style' => 'float:right']) !!}
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idCampaign" id="idCampaign" value="{{$campaign->id}}">
<a class="fa fa-bookmark fa-2x" onclick="document.getElementById('ajax-form').submit();" aria-hidden="true" href="javascript:{}" style="color:#fd8809"></a>
{!! Form::close() !!}
This is the Ajax:
$("#ajax-form").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
if(data.status == 'failedd'){
swal("Error!", "You have already added this campaign to favorites! If you want to remove it, go to your Favorites list page", "error")
}
else{
swal("Success!", "You added the campaign "+ data.idCampaign + " to favorites!", "success")
}
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
When I click on this link, it redirects me to another page which throws: MethodNotAllowedHttpException.
Change your ajax url to this:
url: '/addFavorites',
and your route to this:
Route::post('/addFavorites', 'SearchController#addFavorites');
Just to make sure you point at the same url
EDIT:
make sure that you have one route with get and the same route with post. see bellow:
Route::get('/addFavorites', 'SearchController#loadFavorites'); <-to load the page
Route::post('/addFavorites', 'SearchController#submitFavorites'); <-to submit the data
Change this: $("#ajax-form").submit(function(event) {
To this: $('#yourid').click(function(){
Remove the onclick in the 'a' element and add the id='yourid' with the name you want.
MethodNotAllowedHttpException usually comes when you haven't defined route or you have defined route for get method and you are using the route for post method. please check your routes.php
Related
I'm submitting my Stripe Checkout form via AJAX (catching the form submit event) because I have a complex multi-pane HTML form and want to display payment errors from Stripe without having to reload the page and regenerate the form or making the user re-enter a load of info.
This all works fine, except once the Stripe Checkout button is used once it's disabled. After I display the error message on the booking form page, I need the user to be able to click the Stripe button again and try different payment info.
How do I reactivate the Stripe button? Do I need to remove the whole Stripe button script from the DOM (I'm using jQuery) and re-insert it (or similar code) fresh?
My standard Checkout button code:
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="my_stripe_key"
data-image="mylogo.png"
data-name="My Booking Form"
data-zip-code="true"
data-locale="auto"
data-email=""
data-description="Payment for this booking"
data-currency="gbp"
data-amount=""
data-label="Pay and book!">
</script>
and if relevant, my AJAX form submit code:
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
You have an attribute disabled="true" which is set to the submit button element after the form is submitted. You just need to remove this attribute : $('button[type="submit"]').get(0).removeAttr("disabled");.
Example that works :
http://jsfiddle.net/5xq8Lhda
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="booking" action="your-server-side-code" method="POST">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_TYooMQauvdEDq54NiTphI7jx" data-amount="999" data-name="Stripe.com" data-description="Widget" data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-locale="auto" data-zip-code="true">
</script>
</form>
<script>
$('#booking').get(0).submit = function() {
$('button[type="submit"]').get(0).removeAttr("disabled");
return false;
}
</script>
To use your example, you should do something like that :
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serialize();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val()
},
type: 'POST',
url: 'book',
dataType: 'json',
data: formdata,
success: function(data) {
if (data.response == 'ok') // Payment went through OK
{
// Redirect to booking confirmation page:
window.location.replace(data.url);
} else // Payment failed, alert user to try again
{
$('#erroralert').text('Sorry, payment failed, please try again').removeClass('nodisplay');
$('button[type="submit"]').get(0).removeAttr("disabled");
}
},
error: function(data) // Server error
{
console.log('Error:', data.responseText);
}
});
// Prevent form submit.
return false;
}
If you intend to submit your form by AJAX, or just generally want more control over the checkout experience, I'd recommend using the Custom Checkout integration here.
Simple Checkout was designed around a very straight-forward use case: fill out the form, complete a simple form submit. You can do things like attempt to grab the submit button and remove the disabled attribute, though Stripe could always change things up, it may not act as you intend.
The Custom integration provides a perfect place for your ajax submit or additional js code, in the token callback,
token: function(token) {
// your form submission or next steps here
}
I have a bootstrap 3 modal that is launched via a button on the parent and then populate the modal-body with form data coming from my MySQL database. Among the populated data is small gallery showing attachment pictures and one unique delete-button underneath each picture to launch a query to delete the attachment from a specific attachment folder.
Gallery and delete button ON THE MODAL:
<div class=\"row\">
<div class=\"box box-widget widget-user-2\">
<div class=\"widget-user-header bg-gray\">
<div class=\"lightBoxGallery\">";
$files = scandir($log_folder);
foreach ($files as $attachment) {
if (in_array($attachment, array(".",".."))) continue;
echo "
<span class=\"input\"><button type=\"button\" id=\"DeleteAttachmentButton\" name=\"DeleteAttachmentButton\" class=\"form-btn btn-danger btn-xs\" data-filename=\"".$attachment."\"><i class=\"fa fa-trash\"></i></button><img src=\"".$log_folder.$attachment."\" style=\"height:100px; width:150px;\"></span> ";
}
echo "
</div>
<!-- ./lightbox gallery -->
The problem now is that nothing happens when I press the delete button for the specific attachment. I believe this to be caused by the JavaScript code below which is located ON THE PARENT right after the modal.
// DELETE ATTACHMENT - DELETE BUTTON ON EDIT MODAL
$("#DeleteAttachmentButton").click(function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I checked with Chrome Debugger to see whether any AJAX call is made, but I do not even get to the JavaScript Confirm Alert nor do I receive any error message in the console.
Any hints please?
Thanks
You have an invalid JSON data in your AJAX call (may be you can see errors in your browser's console),
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
//------------------^ don't use this
Just use Filename:attachment_name}
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name)}
change this
$("#DeleteAttachmentButton").click(function(e){
to this
$(document).on("click","#DeleteAttachmentButton",function(e){
Read about event-delegation
$(document).on('click', '#DeleteAttachmentButton', function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I use eModal to call for a modal remotely via ajax. Although within the modal I have a form and the javascript code does not listen to it and thus it doesn't post. My codes are as follows;
eModal and Ajax for the form;
$(document).ready(function() {
// process the PROJECT UPDATE form
$('#proj-edit').submit(function(event) {
// get the form data
var formData = {
'projID' : $('input[name=projID]').val(),
'projname' : $('input[name=projname]').val(),
'projstart' : $('input[name=projstart]').val(),
'projend' : $('input[name=projend]').val(),
'projhotel' : $('input[name=projhotel]').val(),
'projcity' : $('input[name=projcity]').val(),
'projstatus' : $('#projstatus').val()
};
if (formData.projname == '' ||
formData.projstart == '' ||
formData.projend == '' ||
formData.projhotel == '' ||
formData.projcity == '') {
return false;
}
// process the form
$.ajax({
type : 'POST',
url : 'inc/prjedit.ajax.php',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
} else {
$('#proj-edit').trigger('reset');
swal("Success!", "Edit success!", "success");
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
console.log(data);
});
event.preventDefault();
});
$('button[id=demo]').click(function() {
var value = $(this).val();
ajaxDemo(value)
});
function ajaxDemo(value) {
var title = 'Ajax modal';
var params = {
size: eModal.size.lg,
title: title,
type: 'GET',
url: 'inc/demo.ajax.php?pID='+ value
};
eModal.setEModalOptions({
loadingHtml: '<div class="text-center"><span class="fa fa-circle-o-notch fa-spin fa-5x text-primary"></span></div>',
});
return eModal
.ajax(params);
}
});
The modal content is rather simple;
<form class="form" method="POST" action="" id="proj-edit" name="proj-edit">
// the input fields are here. Although since it is too long, I did not include them in here.
<button type="submit" class="btn btn-info" name="update-prj">Register</button>
</form>
I should note that the JavaScript code is in a different document named magic.js, the modal works although it does not submit the form. What am I missing here or what am I doing wrong?
The console log has this to say about all this;
(When eModal opens ->) XHR finished loading: GET "http://localhost/parantez/inc/demo.ajax.php?pID=301".k.cors.a.crossDomain.send # jQuery-2.1.4.min.js:4n.extend.ajax # jQuery-2.1.4.min.js:4n.fn.load # jQuery-2.1.4.min.js:4ajax # eModal.js:336ajaxDemo # magic.js:270(anonymous function) # magic.js:253n.event.dispatch # jQuery-2.1.4.min.js:3r.handle # jQuery-2.1.4.min.js:3
(When form is submitted ->) Navigated to http://localhost/
This issue has now been solved thanks to this post. Thank you very much for taking your time to answer, I highly appreciate your input. Kudos to all of you.
you are passing javascript object to php which is not valid in ajax request
use JSON.stringify() to convert json object into string and inside php use json_decode function to make object of json ...
like this
$.ajax({
type : 'POST',
url : 'inc/prjedit.ajax.php',
data : JSON.stringify(formData),
dataType : 'json',
encode : true
})
if you don't want to send json data then use
formData to send data with ajax same as from submission like that
data = new FormData();
data.append('projID', $('input[name=projID]').val());
do this for all and then simply pass data to ajax function like this
$.ajax({
url: 'http://example.com/script.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
ok hope this will help ...
I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.