Django button ajax click - javascript

I have some HTML that Django is rendering well. I'd like to click a button on the HTML and have that cause an event to fire in the view.
It doesn't look like the button is causing the post to fire. I'm not sure what I'm doing wrong.
This is my views.py code:
def log(request):
if not request.POST:
template = loader.get_template('log.html')
html = template.render(Context())
return HttpResponse(html)
print "Post"
This is my log.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
$("#update_log_button").bind("button", function(){
$.post("hello");
return false;
});
</script>
</head>
<body>
<p>
<span>SPHIINX Log</span>
</p>
<p>
<textarea cols="2" name="log" rows="25"></textarea>
<input id="update_log_button" name="update_log" type="button" value="Update Log"/>
</p>
</body>
</html>

Is there a reason Why you are not using the click event directly?
Try this:
<script type="text/javascript">
$(function(){
$("#update_log_button").click(function(){
$.post(
url : "/hello/",
dataType:"html",
success: function(data, status, xhr){
//do something with your data
}
);
return false;
});
});
</script>
If the button is dynamically created then you may want to use the bind function to attach click event handler to the element:
<script type="text/javascript">
$(function(){
$("#update_log_button").bind('click', function(){
$.post(
url : "/hello/",
dataType:"html",
success: function(data, status, xhr){
//do something with your data
}
);
return false;
});
});
</script>
Try this URL to include the JQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Related

Stop Page redirection on Form Submit

I've looked up a lot of tutorials and poked around on here but haven't found anything that addresses my specific issue. I am guessing I have a syntax error or logic error somewhere in my code. My issue is that whenever I submit the form, I get directed to the test.php page. The php is working correctly as it is returning the correct result but I just want that to run and display the submitted form information underneath. Any help would be greatly appreciated.
index.html
<html>
<head>
<title>Computer swap form</title>
</head>
<body>
<form method = "post" action = "test.php" id="computerForm">
Serial Number: <br>
<input name="serialnumber" type="text">
<button id = "sub"> Submit </button>
</form>
<!--display the response returned after form submit -->
<span id ="result"></span>
<script type="text/javascript" src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
test.php
<?php
$sn = $_POST['serialnumber'];
if(!isset($sn))
{
echo "error serial number not set";
}
else {
echo "$sn successfully saved";
}
?>
my_script.js
$("#sub").click( function() {
$.post( $("#computerForm").attr("action"),
$("#computerForm").serialize(),
function(info){ $("#result").html(info);
});
});
$("#computerForm").submit( function() {
return false;
});
To achieve what you require put all your logic in the submit handler, and call preventDefault() on the event argument provided to the handler function:
$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
$("#result").html(info);
});
});

Onclick event with PHP, ajax and jQuery not working

I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

How to load and validate a form using jquery?

let's say I have 2 pages :
index.html with this code :
<!DOCTYPE html>
<html lang="fr">
<head>
<title>test formulaire</title>
</head>
<body>
<div id="formulaire">
</div>
<!-- /#formulaire -->
Montre le formulaire
<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/monscript.js"></script>
</body>
</html>
I have an other page that containts my form :
<form name="monformulaire" id="monformulaire" role="monformulaire">
<input type="text" name="montexte" id="montexte" value="" />
<button id="bouton" type="submit">Let's go man !</button>
</form>
I have a Jquery.js and a personnal script like this :
function montreformulaire() {
alert('ok charge formulaire');
$.get( "monformulaire.html", function( data ) {
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData );
});
$('monformulaire').submit(function(event) {
alert('formulaire envoyé !');
event.preventDefault();
/*
$.ajax({
type: 'POST',
url: 'ajoute.php',
data: $(this).serialize(),
success: function (data) {
alert($('form').serialize());
//showMsg(data);
showSupportPage(id);
},
cache: false
});
*/
});
$( "#montexte" ).val( 'toto' );
}
my problem is that when the form is submit I want to use a jquery submit function but it doesn't work.
I don't see why and how I could fix that.
Any idea is welcome :-)
Thanks,
Alex
Because you missed a # while passing the id on submit handler
$('#monformulaire').submit(function(event) {
// Your code here..
});
Other selector is
$('[name=monformulaire]').submit({
// Your code here..
});
Choose whichever suits you.
Very classic and common question. You make an ajax call to an element, but you do element.click(...) before it is fetched, thus before it actually exists.
Place the $('#monformulaire').submit(function (with a #, that you forgot) inside the ajax callback function, like this :
$.get( "monformulaire.html", function( data ) { // This is done FIRST
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData ); // this is done THIRD, #monformulaire now exists
$('#monformulaire').submit(function(event) {........}) // this is done FOURTH, accessing the element!
});
$('#monformulaire').submit(function(event) {........}) // This is done SECOND and won't do anything because #monformulaire doesn't exist yet
Welcome to the world of async languages :)
Your submit functions is not good. Do it like so:
$('[name=monformulaire]').submit();
or
$('[name=monformulaire]').submit(function(){
//Do your thing here
});
You have to use $('form[name="monformulaire"]').submit(...)

Jquery Ajax call not successful

I have the following code in Javascript and jquery
function abc() {
alert("called 1");
$.ajax({
url: "abc.htm",
context: document.body
}).done(function () {
alert("done");
});
}
and my html button code is as follow
<input type="button" value="click" onclick="return abc();" />
for some reason the ajax call is not successful. I have added the required jquery files to the page.
Please help thanks.
Modify it like this...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("called 1");
$.ajax({url:"abc.htm",success:function(result){
$("#div1").html(result);
}}).done(function(){alert("d")});
});
});
</script>
</head>
<body>
<div id="div1"></div>
<button>Get External Content</button>
You don't need to return anything to your html markup's onclick handler. Simply call abc() as in
<input type="button" value="click" onclick="abc();" />
Also, if you want more precise error handling then you can use the error and success ajax functions.
function abc() {alert("called 1");
$.ajax({
url: "abc.htm",
context: document.body,
success: function (data, status, xhr ) {
console.log(data.SomeValue);
},
error: function (xhr, status, error) {
console.log(error);
}
}).done(function () {
alert("done");
});
}

Categories

Resources