AJAX not submiting - javascript

I have a laravel project where admin can change user data via form. I want this form to be submitted by ajax. But it doesn't get submited.
I have a form:
<form id="userData{{$loop->iteration}}" method="POST">
#csrf
<!--some inputs-->
</form>
<button id="changeUserData{{$loop->iteration}}" data-id="#userData{{$loop->iteration}}">Save</button>
JS:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$(formId).submit(function (e){
console.log("test2");
e.preventDefault();
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})
});
When I press the button the first console.log gets fired but nothing else. I checked if formId matches the form id and it does so I don't know what's wrong.

The problem is .submit() with handler argument does not submit the form itself. It just binds an event handler to the form's submit event.
You may just remove that bind and it should work:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})

Related

POST method not supported when submitting multiple forms through the same JS code. (405)

I have multiple forms on the same page that are submitted through the same JavaScript code.
<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController#cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="462f2e80-8012-11e9-8b02-65a0a3459d7a">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>
<form class="form" id="cancelchallenge" method="POST" action="{{action('ChallengeController#cancelChallenge')}}">
<input type="hidden" name="cancel_challengeid" value="9b9ef9d0-8012-11e9-aa0f-95ff09733e52">
<button type="button" class="btn-submit-cancelchallenge">cancel challenge</button>
</form>
There could be any number of forms all of which will have a unique value for each hidden input.
Here is my JavaScript code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit-cancelchallenge").click(function(e){e.preventDefault();
var $form = $('#cancelchallenge');
var cancel_challengeid = $("input[name=cancel_challengeid]").val();
$.ajax({
type:'POST',
url: $form.attr('action'),
data:{cancel_challengeid:cancel_challengeid},
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});
If I submit any given form using the above code it works but it will always only submit the input value - from the first form - regardless of which form I submit.
Okay So I realise I shouldn't be using the same ID's in multiple forms so I change the form ID from:
id="cancelchallenge" to class="cancelchallenge"
and then update the JS code from:
var $form = $('#cancelchallenge'); to var $form = $(this);
thinking that will allow to submit any given form with the correct input value. However this now results in a 405 error.
"The POST method is not supported for this route. Supported methods: GET, HEAD."
My route looks like this:
Route::post('cancelChallenge', 'ChallengeController#cancelChallenge');
Briefly my controller looks like this:
public function cancelChallenge(Request $request)
{
//Some validation
$challenge = Challenge::where(['id' => $request->cancel_challengeid,
'player1' => Auth::user()->id])->first();
//DB::beginTransaction();
//Update a row in the challenges table
//Insert a row into the transactions table
//Update a row in the users table
//Commit transaction
}
Anyone able to point me in the right direction? Thanks.
$(this) - current element.
el.parent() - parent of element.
el.find() - find selector inside element.
$('.btn-submit-cancelchallenge').click(function(e){
e.preventDefault();
let $form = $(this).parent();
let cancel_challengeid = $form.find('input[name=cancel_challengeid]').val();
$.ajax({
type:'POST',
url: $form.attr('action'),
data: {cancel_challengeid: cancel_challengeid},
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});
Or better:
$('.btn-submit-cancelchallenge').click(function(e){
e.preventDefault();
let form = $(this).parent();
$.ajax({
type:'POST',
url: form.attr('action'),
data: form.serialize(),
success:function(data){
if(data.successful) {
toastr.success(data.successful);
}
}
});
});

Django : Ajax form still reloads the whole page

I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.

Forms with Ajax send with multi-parameter and A href

within the form element I send data with a href. Using the JavaScript (as defined below), it works perfectly.
I want to send the forms now with Ajax, unfortunately it does not work. Do you have a solution for me. jQuery is included on the page.
Thank You!
function sendData(sFm, sID, sFn, sCl) {
var form = document.getElementById(sFm);
form.sid.value = sID;
form.fnc.value = sFn;
form.cl.value = sCl;
form.submit();
}
Send Data
My new Code:
function sendData(sFm, sID, sFn, sCl) {
var form = $("#"+sFm);
form.submit( function() {
var sid = $('input[name="sid"]').val(sID);
var fnc = $('input[name="fnc"]').val(sFn);
var cl = $('input[name="cl"]').val(sCl);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {sid: sid, fnc: fnc, cl: cl}
}).done(function( e ) {
});
});
form.submit();
}
$("form").submit(function() { // for all forms, if you want specially one then use id or class selector
var url = $(this).attr('action'); // the script where you handle the form input.
var method = $(this).attr('method');
$.ajax({
type: method,
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // handle response here
}
});
return false; // avoid to execute the actual submit of the form.
});
:) , Thanks
Just because we don't want to submit all form by ajax so we can set a data-attribute to form tag to indicate, will it should be submit by ajax or normally ,, so ,,
$("form").submit(function() { ...
if($(this).attr('data-ajax') != "true") return true; // default hanlder
...
so If form is written like this :-
<form action="/dosomething" method="post" data-ajax="true"> </form> // will be sumit by ajax
<form action="/dosomething" method="post" data-ajax="false"> </form>
// will be sumit by default method

after submit clear textbox

I'm inserting data into a table using Ajax. I'm using ajax so my page wouldn't get refresh. Here is my Ajax code for calling the inserting page:
<script type="text/javascript">
var i = jQuery.noConflict();
i(document).ready(function(){
i('#myForm').on('submit',function(e) {
i.ajax({
url:'insert.php',
data:$(this).serialize(),
type:'POST'
});
e.preventDefault();
});
});
</script>
Now every time i write in the textbox and hit the submit button the data gets entered but it remains in textbox and i have to press the delete button to erase it.
Question: how can I make so my data gets cleared when I press the submit button?
You can reset the form in the ajax success handler
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
context: this
}).done(function () {
this.reset();
});
e.preventDefault();
});
});
document.getElementById('myForm').reset(); // In Javascript
$("#myform")[0].reset(); // In jQuery Fashion
You can reset form fields on the completion as suggested by arun or on success as below
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
success:function(data) {
$('#myForm')[0].reset();
}
});
e.preventDefault();
Hope it helps

Ajax Form Cannot Prevent Page Reload with event.preventDefault();

I have the following code which is supposed submit a form via Ajax without having to reload the page:
$( document ).on('submit', '.login_form', function( event ){
event.preventDefault();
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
});
However for some reason, despite the event.preventDefault(); function which is supposed to prevent the form from actually firing, it actually does fire.
My question is, how do I prevent the above form from reloading the page?
Thanks
don't attach a listener on document instead use a on click handler on the submit button and change the type to button.
<button id="form1SubmitBtn">Submit</button>
$('#form1SubmitBtn').click(function(){
//do ajax here
});
Happy Coding !!!
for instance you can write like this
$(".login_form").on('submit', function( event ){
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
event.preventDefault();
});
You can use jquery and ajax to do that. Here is a nice piece code below that doesn't refresh the page but instead on submit the form gets hidden and gets replaced by a thank you message. The form data is sent to an email address using sendmail.php script.
Assuming your form has 3 input fields - name, email and message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function() {
jQuery("#button").click(function() {
var name=jQuery('#name').val();
var email=jQuery('#email').val();
var message=jQuery('#message').val();
var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
jQuery.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
jQuery('#contact_form').html("<div id='message'></div>");
jQuery('#contactForm').hide();
jQuery('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Thank you for your submission. We will be in touch shortly.</p>").hide()
.fadeIn(1500, function() {
});
}
});
return false;
});
});
</script>
On top of your form tag just add this to display the thank you message.
<div id='message'></div>
Enjoy coding!!!!!!!

Categories