Form loads, but fails to submit, django-ajax - javascript

I am having trouble getting my form to submit. The problem seems to be unique to loading the form into a particular page. The form functions perfectly if not loaded and accessed manually by typing the url. Also, the form accessed manually doesn't function if method="POST" is removed from the form designation.
excerpt from views.py to manage form
if request.method == 'POST':
form = SelectMyBookForm(request.POST, choices=choices)
# do stuff
So my question is this:
Is the reason the form is not submitting properly in the loaded case because the "POST" request is not taking place at the correct url? How can I get the "POST" request to be recognized? Can I use Ajax (as in activate.js) to get around this condition in django?
I used the JQuery load() function to load a form on another page. The form renders correctly, but fails to submit when the button is pressed. I attempted to write a function in Javascript to help correct this issue. #submitform refers to the button that will submit the form #bookselect is the id of the form itself.
from activate.js
$("#bookselect").submit(function(e) {
e.preventDefault();
var elem = getElementsByTagName('course_link');
var pk = elem.attr('data');
var cond = $("li.tab.ui-tabs-selected").attr("id");
$.ajax({
type: "POST",
url: selectConditionURL(pk, cond),
success: function(response) {
console.log(response)
}
});
})

Related

My recaptcha render doesn't work and return 0

I currently have a problem with Google's Invisible Captcha.
It refuses to load properly despite all my attempts.
The situation:
I have a form which is added to the DOM via jQuery when clicking on a button. The form is then displayed in an overlayer which covers the entire screen.
At first, no worries but once the form is displayed, I try to render the captcha without success, which prevents doing the execute and thus using the captcha on the form.
Here is the insertion code of my form (which works):
$('.js-event-subscribe').click(function(e){
e.preventDefault();
var event = $(this).data('event');
clearTimeout(ajxTimeout);
if(typeof ajx != "undefined")
ajx.abort();
ajxTimeout = setTimeout(function(){
ajx = $.ajax({
type: 'POST',
url: langPath + '/ajax/event-subscribe/',
data: 'id='+event,
success: function(content){
if($('body').find('#js-event-subscribe').length)
$('body').find('#js-event-subscribe').remove();
$(content).insertAfter('footer');
$('html, body').addClass('opened');
//var test = grecaptcha.render('js-recaptcha-event');
//console.log(test);
//grecaptcha.execute('js-recaptcha-event');
}
});
}, 500);
});
So far it works, the form is correctly added and functional.
The grecaptcha.render (according to the documentation) should return the widgetID but reply 0.
The "js-recaptcha-event" parameter corresponds to the ID of the DIV captcha in the form (added to the DOM therefore).
<div id="js-recaptcha-event" class="g-recaptcha" data-sitekey="xxxxxxxxx" data-size="invisible"></div>
Therefore the grecaptcha.execute ('js-recaptcha-event') returns an error
Uncaught Error: Invalid site key or not loaded in api.js: js-recaptcha-event
I tried adding the sitekey in render parameters with the same result. :(
The recaptcha API is loaded via (also tested with async & defer in attributes)
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
Can you tell me what I need to make it work?
Thank you in advance
As far as I know 0 is a valid response to the render event, i.e. the widget ID is an integer starting at 0 for the first widget rendered.
As render is explicit, I would take the approach of specifying all the parameters in the render event:
widget = grecaptcha.render(captcha, {
'sitekey': 'xxx',
'callback': function(token) { ... },
'badge': 'inline',
'size': 'invisible'
});
Given your error response, I would triple-check that your site key is correct, and that it corresponds to the correct entry in your reCAPTCHA admin console, where the domain you are loading from needs to be specified.
Ensure the code for rendering the widget is loaded before the reCAPTCHA script loads.
I would suggest you render the reCAPTCHA immediately on the form appearing, and then execute it upon clicking submit. That may also resolve the issue.

Submitting form data as JSON using ajax POST

So I have a form with a 3 hidden pre-filled input fields and 2 text input fields. I am trying to submit this form data using AJAX post as a JSON.
Upon hitting the submit button, I get the url as :
http:myurl.com:7001/pagename/?obj1=val1&obj2=val2&obj3=val3&obj4=val4
after this I wrote some code which I have mentioned to convert these as JSON and then post it.
The problem which I am getting is:
How can I integrate the code I mentioned into the submit button, so that, as soon as the user click the submit button, the url as mentioned above is obtained and everything else (as mentioned in the code) happens in the background and the ajax post request is made.
Thanks.
I am sorry if anything is unclear.
//This is the code, and If I run it in console after clicking the submit button then I am able to do the ajax post successfully. I want to integrate this code to the submit button.
var urlvalue = location.search.substring(1).replace(/\+/g, '%20');
var postdata = JSON.parse('{"' + decodeURIComponent(urlvalue).replace(/&/g, '","').replace(/=/g,'":"') + '"}');
console.log(urlvalue);
const URL = myurl;
$.ajax({
url:URL,
type:'POST',
data: postdata,
success: function(result){
console.log(result);
},
error: function(error){
console.log(`Error $(error)`);
}
});
I'm not sure I understand your question exactly, but if you just want the form submission to POST the data somewhere, you will have to provide a function to the form's onsubmit attribute.
That function should contain pretty much the working code you have at the bottom of your question (as well as cancelling the default form action with event.preventDefault()).

AJAX error when passing a variable to a PHP file

How my page works:
The quiz php page loads and the user generates a score with a function inside quiz.js. The score is then saved in a variable score inside quiz.js
After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in sendData.php, without reloading the page.
My button looks like this:
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
And my PHP file being like this:
if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
$score = $_POST['score'];
$numQuiz = $_POST['numQuiz'];
// SQL query and stuff goes here
}
But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.
<form id="sendData" action="sendData.php" method="post">
<button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>
You're running the JS when you click a submit button in a form.
So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response.
You then see the result of the standard form submission.
If you just want a button to trigger some JavaScript, then use a non-submit button (<button type="button"), and don't put it in a form.
Better yet:
switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form
Use preventDefault() to stop the form submission when the JS is successful
Put form controls in the form so it submits useful data when the JS isn't successful
i.e. write Unobtrusive JavaScript then provides Progressive enhancement.
Two things:
You need to tell jQuery to use the application/json content-type:
function sendAjax() {
$.ajax({
url: "sendData.php",
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: {
score: score,
numQuiz: numQuiz
},
success: function() {
alert("Data succesfully sent");
},
error: function() {
alert("There has been an error");
}
})
}
PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. So we can parse the JSON payload (body) ussing:
$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);

Django submit a form->redirect to a new page->auto update new page

Ok as the title describes, Im trying to create a webpage(test.html) where in after the form is submitted it should redirect me to a new page(say status.html).And after this page loads It should shows some continuous updates on the submitted task. I was able to accomplish this on a single page , when Im trying to redirect this to a new page Im out of luck.
test.html
<form action="status/" method="POST" id="start-form">
.....
<input type="submit" value="Start" class="tbutton">
views.py
def status_page(request):
print("Inside redirect")
return HttpResponseRedirect(request,'my_app/status.html')
url.py
url(r'^test/status/$', 'status_page'),
jav.js
$('#start-form').on('submit',function(event){
event.preventDefault();
status();
});
function status() {
$.ajax({
url : "status_page/", // the endpoint
type : "POST", // http method
data:{' ': '',}, // data sent with the post req
headers: {Accept: "application/json"},
success : function(json) {
//on success display the rendered page,so what coding is needed here?
},
error : function(xhr,errmsg,err) {
//error handling code }
});
}
On execution the new page is not loaded, but if I bypass javascript then the form action gets executed and the new page rendering through the view happens. But with JavaScript, on success what happens ? how does the return statement from the view get captured in the success and how is the page displayed?
I need to use javascript and AJAX as once the new page is loaded I need to display continuous updates on the same page. So basically how do I implement redirection to a new page with the above code using javascript and Django? Any help will be truly appreciated!
In your views.py, HttpResponseRedirect is used incorrectly. If you want to redirect to a new page, then you should use,
return HttpResponseRedirect('/url-where-you-want-to-redirect/')
As HttpResponseRedirect expects url paramter instead of template name.
See here: https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponseRedirect
Better approach would be to return a JSON response from your status_page view and then in success method of ajax, you can go to next URL:
window.location.href = '/url-where-you-want-to-redirect/';
I hope this helps.

Only allow access to a php action through form submit, but when using an ajax call

i have a form that deletes the comment its in.
To only allow the page that carries out the php action to be viewed when the form is submitted i do a basic
if (isset($_POST['submit-delete'])) {
// carry out delete
}
this works fine, but i am using ajax to not reload the page.
The response is the same as i have used else where:
$(document).ready(function(){
$(".delrepcomment").submit(function(){
$.ajax({
type: "POST",
url: "process/deletecomment.php",
data: $(".delrepcomment").serialize(),
dataType: "json",
success: function(response){
if (response.commentDeleted === true) {
$('#successdisplay').fadeIn(1000),
$('#successdisplay').delay(2500).fadeOut(400);
}
else {
$('.delrepcomment').after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
This however doesnt work, unless i remove the check to see if the form has been submitted.
Whats the best way around this? I want to keep the check for the form being submitted incase of js being turned off or any direct access attempts.
Thanks.
You should post the data you require for the script to work. In your case, you have to post a key-value-pair with "submit-delete" as the key and an arbitrary value (unless you check that value later in the code).
On the other hand, PHP stores the used HTTP method in $_SERVER['REQUEST_METHOD'], this would be "POST" in your case.

Categories

Resources