AJAX POST incorrectly works like GET - javascript

I am trying to post contact page data to my view, but it stopped working when I included if else statements.
Here is my script:
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
}else
{
return true;
}
}
</script>
And here is my form:
<form class="contact-form">
{% csrf_token %}
<p class="input-block">
<label for="contact-name"><strong>Name</strong> (required)</label>
<input type="text" name="name" value="" id="contact-name" required>
</p>
<p class="input-block">
<label for="contact-email"><strong>Email</strong> (required)</label>
<input type="email" name="email" value="" id="contact-email" required>
</p>
<p class="input-block">
<label for="contact-subject"><strong>Subject</strong></label>
<input type="text" name="subject" value="" id="contact-subject">
</p>
<p class="textarea-block">
<label for="contact-message"><strong>Your Message</strong> (required)</label>
<textarea name="message" id="contact-message" cols="88" rows="6" required></textarea>
</p>
<div class="hidden">
<label for="contact-spam-check">Do not fill out this field:</label>
<input name="spam-check" type="text" value="" id="contact-spam-check" />
</div>
<input type="submit" value="Submit" onclick="javascript:Submit();">
<div class="clear"></div>
</form>
Without the if else it was working fine but now all pages are reloading with all form data as query parameters. How can I correct this?

First you need to prevent the default action if you are trying to do AJAX.
Since, I see you are already using jQuery. I recommend adding the following to the top of your <script>:
$("#contact-form").submit(function(e){
e.preventDefault();
Submit();
});
Obviously, you won't need this anymore..
onclick="javascript:Submit();"
Now run this code in any sort of javascript debugger (Chrome and Safari both have good ones) and you should be good!

Try this please..i hope it works...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".contact-form").submit(function(e){
e.preventDefault();
Submit();
});
});
</script>
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
}
}

You need to return a false from your Submit() function. Also, call the function from the form tag using onsubmit handle.
<form class="contact-form" onsubmit="Submit();">
and in Submit() function:
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
} else {
return true;
}

Do not use javascript: in an onxxx event handler. javascript: is a protocol specifier that goes on a URL, but the onclick handler expects raw javascript, not a URL.
You need to return false from the onclick to prevent the default action of submitting the form. I assume you do want to prevent the default and use AJAX instead?

Related

How to submit single form via AJAX when you have multiple forms from PHP loop

I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -
php loop form -
<form method="post" id="'.$vid.'" class="note-form">
<textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
<input type="hidden" name="tac" value="'.$vid.'"/>
</form>
$vid is the unique id for each form that im passing from the DB.
JS file -
// Capture keyup from textarea to submit form
$('.quicknote').bind('keyup', function() {
var id = this.id;
var formID = "#"+id;
$(formID).delay(200).submit();
});
$(formID).submit(function(e) {
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?
Your form id and textarea id are same that's why its causing problem . Instead you can use
$(this).closest('form') this will get closest form from textarea then you can submit only that form.
Demo Code :
$('.quicknote').bind('keyup', function() {
var selector = $(this).closest('form') //get closest form
$(selector).delay(200).submit(); //submit that.
});
$("form").submit(function(e) {
console.log("data to send --> " + $(this).serialize())
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
<textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
<input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
<textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
<input type="hidden" name="tac" value="2" />
</form>

textarea not send form do not send form the first click to send. The at 2 click yes

In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;

Hide the RSForm form when submitted

I have this AJAX code which successfully shows the "loading.." message when submitted in RSForm.
I want to hide the form when the user clicks the submit button. How should I go about editing in this javascript?
<script>
jQuery(function($){
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponseAll
};
// bind to the form's submit event
$('#userForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.my-message').html("Loading....");
return true;
}
// post-submit callback
function showResponseAll(responseText, statusText, xhr, $form) {
var $response = $(responseText);
var comon = $response;
var dane = comon.find('.message-load')
$('.my-message').html(dane);
}
});
</script>
<form method="post" id="userForm" action="URL"><div class="my-message"></div>
<div class="message-load"><div id="rsform_error_3" style="display: none;"><p class="formRed">Please complete all required fields!</p></div></div>
<fieldset class="form-horizontal formContainer" id="rsform_3_page_0">
<div class="form-group rsform-block rsform-block-email">
<div class="col-xs-12 formControls">
<input type="text" value="" size="20" placeholder="you#email.com" name="form[Email]" id="Email" class="rsform-input-box form-control rsform-input-box">
<span class="formValidation"><span id="component27" class="formNoError">Please let us know your email address.</span></span>
</div>
<div class="col-xs-12">
<button type="submit" name="form[Join Newsletter]" id="Join Newsletter" class="rsform-submit-button btn btn-primary">Join Newsletter</button>
</div>
</div>
</fieldset>
<input type="hidden" name="form[formId]" value="3">
</form>
I believe we must add something to pre-submit callback but I don't know how. I want to hide the form and show them a "thank you" message when somebody clicks the submit button
Not able to make out when you say RSForm. Presuming you are referring to same userForm
$('#userForm').submit(function(event) {
//since making ajax call you have to prevent the default behavior that is submit
event.preventDefault();
$('#userForm').hide();
$(this).ajaxSubmit(options);
return false;
});
});
Note:This id="Join Newsletter" may not be a valid value for id attribute.
You can check this LINK to know more about valid values.
You can use .ajaxStart() method:
$(document).ajaxStart(function(){
$('#userForm').hide();
$('#userForm').find('.my-message').html("Thank You!!!");
});
Or add the two lines in these functions:
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.my-message').html("Loading....");
$('#userForm').hide(); // <------------hide it here
return true;
}
// post-submit callback
function showResponseAll(responseText, statusText, xhr, $form) {
var $response = $(responseText);
var comon = $response;
var dane = comon.find('.message-load')
$('.my-message').html(dane); // <----i suppose this is Thank you message.
}

Keep getting null on create user

Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

Categories

Resources