Seeking clarification to weird POST behavior (Django, Django server, AJAX, Chrome) - ajax

I am seeing a weird behavior when I POST using AJAX. When I have the following code,
<a id="submit" class= "btn btn-large btn-primary">Sign Up</a> (form submit)
$('#submit').on('click', function(){
console.log($('#biz_details').serialize());
$('#status').css('display','block');
$.post('/business/signup',$('#biz_details').serialize(), function(data){
$('#updated').text('Success.').append(' here to view profile ');
}
,'json');
});
things seem to work fine. However, when I use
<submit id="submit" class= "btn btn-large btn-primary">Sign Up</submit> (form submit)
instead of the <a> tag, I get error: [Errno 32] Broken pipe. Also, I am redirected to
the same URL (\business\signup) but with my POST parameters being sent as GET.
To illustrate, if I were POSTing a=1&b=2, I am redirected to \business\signup?a=1&b=2.
My form declaration is
<form class="holder form-horizontal" id="biz_details" style= "background-color: white;overflow-y:hidden;">
Further, if I do have an action attribute to my form and have a js call in the action to the POST function, it works fine.
Can anyone throw some light on this behavior, especially the one about redirects?

In order for the function to work correctly with the submit button, you have to disable the default action for the form, and since you haven't defined a METHOD, the default (GET) is used.
To disable the default action, simply add a return false at the end of the function that is trigged on the form submit.
$('#myform').submit(function() {
// do something
return false;
});

Related

inivisible Google ReCaptcha Integration with Knockout and AJAX Post

I am trying to integrate the Google Invisible Captcha to my contact form. The integration is working to an extent and I can submit my form and the challenge appears.
However, I assumed that the data-callback added to the div would call my submit function again after the challenge is completed? So currently I have to click the form submit button a second time after the challenge is completed?
I have added the following to my contact form (reduced for brevity);
<div class="col-md-12">
<div class="g-recaptcha"
data-sitekey="mykey"
data-callback="submitForm"
data-size="invisible"
data-bind="formSubmitButton">
</div>
</div>
<div class="col-sm-12 text-center">
<input id="formSubmitButton" data-bind="click: submitForm" type="button" class="btn btn-primary btn-block btn-lg" value="Send Enquiry" />
</div>
and in my submitForm method I have the following code;
this.submitForm = function () {
...
//if no field error validate captcha
if (!error) {
//validate captcha
var response = grecaptcha.getResponse();
if (response.length == 0) {
grecaptcha.execute();
return;
}
}
...
}
I am correct in thinking that I shouldn't need to submit the form a second time? and if so what is it I am doing wrong here please.
You shouldn't need to submit the form twice.
I posted an answer to a similar question about setting up recaptcha with a knockout ajax request.
You may need to restructure how you are setting up your form and functions. I found that you can set up a jquery function to use as the required callback function, that calls your knockout ajax request. Set your button or hidden div to send that as the callback function. I found success by using a button.
You only need to click the button, which does its recaptcha thing (sends a request to google, and then saves its response, which can by accessed later), which then calls your callback function you gave it, which calls your original knockout ajax request. That request will work normally as it did before recaptcha was added, but you will send your recaptcha response like you were getting with: var response = grecaptcha.getResponse(); so your server can validate it.
The link I proved has a more detailed answer, I hope this helps.

Spring-Boot: Redirect and Refresh model and page

I have a spring-boot application, with theyemleaf. I repeatedly update the page, and redirect it to the same page, so i expect that the elements of the page get updated:
#GetMapping("/suggested-events/vote/{eventId}")
public String voteForEvents(Model model,
#PathVariable("eventId") Long eventId,
#RequestParam(value = "message", required = false) String message ) {
log.info("The message is: "+message);
SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
model.addAttribute("mainEvent",event);
model.addAttribute("events",events);
model.addAttribute("message",message);
return "/suggested-event/vote";
}
and when a button get pushed in the view it triggers the below post method:
#PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
log.info("You have made a vote");
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggested-events/vote/1";
}
This second controller method, performs an operation an makes a message, and redirects it to the first method. So, it successfully redirected to the first method and it logs
log.info("The message is: "+message);
but it does not refresh my page, and i do not get the message as model?
When i redirect to the first method, i expect it adds the message to my models:
model.addAttribute("message",message);
But it does not added to my page
and when a button get pushed in the view it triggers the below post
method:
It sounds like this trigger is using AJAX, rather than a form submit. Doing so would match the symptoms you describe.
If you POST to /suggested-events/vote using AJAX, the server will return a 302, and the browser will follow it. However, the response for that 302 is still the result of an AJAX call. You have access to it in your success callback, but the browser isn't going to render it for you.
but it does not refresh my page
If a 302 doesn't cause your page to re-render, this also suggests you're using AJAX.
If you actually use a form submit instead, the browser will re-render using the markup returned by the successful redirect.
This can be verified by using the following two buttons in your vote.html:
<form action="http://localhost:8080/suggested-events/vote" method="POST">
<input type="submit" text="Submit" />
</form>
<button onclick="postmessage();" >Button</button>
<script>
function postmessage() {
$.ajax({
method: 'POST',
data: {},
url: 'http://localhost:8080/suggested-events/vote'
});
}
</script>
The first button will work as expected, and the second button matches the symptoms you describe.
If you are already using a form, please update the question with it (or better yet, the entire Thymeleaf template).
I had the same problem as OP described and Mike's explanation brought me in the right direction.
I am reading a db-table and populating it with thymeleaf using th:each. I wanted to add a javascript-confirmation before deleting an item. Sending an ajax GET without an event-listener and reloading with location.reload(true) didn't reach the #GetMapping("/delete/{id}") in the controller.
This SO-thread gave me the answer to the ajax-call.
<a class="btn btn-danger" href="#" th:onclick="|confirmDeletion('${u.id}')|"></a>
<script th:inline="javascript">
function confirmDeletion(id) {
if (confirm("Delete this id? " + id)) {
var http = new XMLHttpRequest();
http.open("GET", "/delete/" + id, true);
http.addEventListener("readystatechange", function() {
if (http.readyState === 4 && http.status === 200) {
window.location.reload(true);
}
});
http.send();
}
}
</script>
there are many ways to redirect page in Spring, but be sure if the model attribute off message its passing correctly to FrontEnd or passing like parameter to another handler , you can see this document : http://javainsimpleway.com/spring-mvc-redirecting-model-attributes-from-one-controller-to-other-controller/ , hope this is useful !!

ajax method return view code instead redirect on view in laravel

I have many buttons in single form that's why i used ajax to call different method on different button click event. But while I call method using ajax and return view, it send code of view as response, And i need to redirect on that view my method code is as below.
public function store(Request $request)
{
return view('surat.proceed_sell');
}
can i redirect on other view using ajax? Or any other way to call different methods on different button click event then please let me know.
What you could do is return the url where to redirect as a response in your controller as
return url('the path');
and in your ajax success callback you could redirect to the view as
window.location = data;
The url should be defined in your route file where the view is rendered.
You cannot redirect to a view with Ajax because Ajax expects a response. What you should do is redirect to a page instead, using anchors.
First, define your routes
Route::get('surat/proceed', 'SuratController#proceed');
Then use anchor with a button to go that page. It doesn't matter how many buttons you have in the form, as longs as they are not of type submit, they should not submit the form.
<form method="post" action="">
Go to proceed
<button type="submit" class="btn btn-primary">Submit</button>
</form>
If this does not help you, please, update your question with your form code.

Ajax login form - browsers won't save password

I have Ajax login form, which is checking whether given credentials are correct and redirects to another page. The login form itself is built by a HXR call - it isn't built in the login page code.
The problem is that I can't get browsers to prompt for remembering passwords. Once I've got the Firefox to prompt but since the form is being built by XHR call, the Firefox didn't paste the values into the form.
PS. I am using mootools (Form.send) and usual window.location when login was successful.
PSS. The address of the login page is always the same.
The following code is loaded by a XHR within a element (I am using MochaUI):
JavaScript:
$('loginwindow_form').set('send', {
"url": "auth/ajax_login",
"method": "post",
"onRequest": function () {
$("loginWindow_spinner").show();
},
"onComplete": function (response) {
$("loginWindow_spinner").hide();
},
"onSuccess": function (responseText, responseXML) {
window.location = "appinit";
},
"onFailure": function (xhr) {
MUI.notification('onFailure');
}
});
$("loginwindow_form").addEvent("submit", function (e) {
!e || e.stop();
$('loginwindow_form').send();
});
xHTML (notice that the form does not have submit button - the button is elsewhere and has onclick action to send the form with given ID):
<iframe src="auth/blank" id="blankiframe" name="blankiframe" style="display:none"></iframe>
<form action="appinit" method="post" name="loginwindow_form" id="loginwindow_form" class="standardform" target="blankiframe">
<input type="text" name="email" class="input text" id="loginwindow_form_email" />
<input type="password" name="password" class="input text password" id="loginwindow_form_loginwindow_form_password" />
</form>
The sending button (in another, xhr loaded, element):
<button class="button" action="{sendForm: 'loginwindow_form'}">
<div class="accept">Login</div>
</button>
you really ought to post code. it's all very nice doing a .send in your callback, that's fine. still, you need to post how you handle the form and initiate submission in the first place.
the way it should work is if you intercept the form's submit method - but if you--say, have a button with a click handler, it won't be seen as a submission so it won't remember things. also, are you doing event.stop or .preventDefault?
I recomment that you use a traditional sumbit form, but submit into a hidden iframe. (Or the login form itself could be in an iframe). This way you can still send back JS responses to the iframe which will be executed, and the browsers will know that it was a login form.

How can I stop a form from processing/submitting that is using jquery AJAX submission?

I have a form with two buttons, a submit button and a cancel/close button. When the user clicks submit, the entered data is validated using http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/. If everything validates, the form is submitted with jQuery/AJAX. That all works fine and dandy. I run into problems with the cancel button though. I want the cancel button to require confirmation. If the user chooses to proceed, they are taken to a page of my choosing. If they decide they don't want to cancel, then they are simply left on the page. It's the last part that isn't working.
My form code looks like this:
<form name="createPage" id="createPage" method="post" action="pager.php" class="ajax updateForm">
<input name="whatever" type="text" />
<button type="submit" id="submitQuickSave" class="submitSave"><span>save</span></button>
<button type="submit" id="submitCancel" class="submitClose" onclick='confirm_close()'><span>close</span></button>
</form>
My current cancel script looks like the following. If the user does indeed want to cancel, I unbind the form submit so that validation isn't executed. The form then proceeds to submit and includes cancel as a parameter in the action attribute. I handle the cancellation server side and direct the user to a new page.
function confirm_close()
{
var r=confirm("All changes since your last save operation will be discarded.");
if (r==true)
{
$(".ajax").unbind("submit");
}
else
{
}
}
I cannot figure out what to put in the 'else' argument. What happens is that if the users cancels the cancellation (i.e., return false), then the form still tries to submit. I cannot make it stop. I've tried several things from this site and others without success:
event.stopImmediatePropogation
.abort()
Any ideas? Basically, how can I get the cancel/close button work properly?
Consider separating your JavaScript from your HTML. With this in mind, you could write the handler for your the click event you're trying to intercept like this:
$("button#cancel").click(function($event) {
var r = confirm("All changes since your last save operation will be discarded.");
if (r) {
$(".ajax").unbind("submit");
}
else {
$event.preventDefault();
}
});
You would have to tweak your HTML and add an id attribute to the cancel button:
<button id="cancel" type="submit" value="cancel">Cancel</button>
Example here: http://jsfiddle.net/wvFDy/
Hope that helps!
I believe you just
return false;
Let me know if this works.

Resources