I've been scanning my code over and over again but I can't seem to find the problem.
When I click the link #add-user-btn the file actions.php is called twice (and hence the PHP script is executed twice).
Here's the script: I suppose it has something to do with the javascript in front of the ajax request?
$(function () {
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
});
The HTML:
<div id="adduser" class="reveal-modal">
<h1>Add new user</h1>
<p><label for="email">E-mail:</label> <input id="email" name="email" type="text" placeholder="name#example.com" /></p>
<p><label for="name">Name:</label> <input id="name" name="name" type="text" placeholder="Adam Smith"/></p>
<p><label for="password">Password:</label> <input id="password" name="password" type="password" placeholder="123456" /></p>
<p>
<label for="authorization">Authorization:</label>
<select id="authorization" name="authorization">
<option value="0">Administrator</option>
<option value="1">Superuser</option>
<option value="2">User</option>
</select>
</p>
<button id="add-user-btn">Submit</button>
<a class="close-reveal-modal">×</a>
</div>
Try
$("#add-user-btn").unbind('click').bind('click', function () { });
This will ensure the click event only gets called once.
This problem also occurs when you include multiple times the same JavaScript file in your HTML file.
<html>
<head>
<script src="utility.js"></script>
<script src="utility.js"></script>
</head>
When I worked with an specific website that I only had access to my javascript, I got this kind of error too. The problem was that there was lots of $(function() and $(document).ready in other codes.
what you can do to prevent this, if you can't correct the core problem is:
var preventRunDefault;
$(function () {
if(!preventRunDefault) {
preventRunDefault = true;
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
}
});
But the right way is to search the cause and don't do workarounds.
Related
Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});
I am trying to submit a form and send the data to my php function with Ajax. The problem is that, When I send data without ajax call and just using form action, My form validation works, but when I want to use Ajax, Form will be submitted without being validated. Here is my code:
html:
<form novalidate="" class="form-horizontal">
<div class="control-group">
<label for="email" class="control-label">Email address</label>
<div class="controls">
<input type="email" required="" id="email" name="email">
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label for="emailAgain" class="control-label">Email again</label>
<div class="controls">
<input type="email" name="emailAgain" id="emailAgain" data-validation-matches-message="Must match email address entered above" data-validation-matches-match="email">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<button id="button" class="button" type="submit" name="submit">Check your
</form>
Ajax:
$(document).ready(function () {
$(function () {
$("#button").click(function () {
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ")
});
}
});
return false;
});
});
});
I also tried submitHandler: function(form){} with Ajax call, but in that case, my success function in Ajax call won't work and it seems that the data will be sent through GET method instead of POST! weird!!! Thanks in advanced!
Ok you have a submit button and on clicking this you are doing some ajax, so you need to use event.preventDefault()
Here how the code should be and it should work, also check for any syntax error in your code. Below is the code I just tested and worked on my linux box.
<script>
$(document).ready(function () {
$(function () {
$("#button").click(function (x) {
x.preventDefault(); // lets stop the default behaviour which is submit
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ");
}
});
});
return false;
});
});
</script>
issues are still there...pls help
I am unable to load external file while using AJAX jquery. I want to use Jquery ajax to pop up form then validate, enter data in mysql. but starting from a simple ajax function. kindly let me know where i am going wrong
<link rel="stylesheet" type="text/css" media="all" href="test_style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="contact_form">
<form id="ajax-contact-form" name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<INPUT class="button" type="submit" name="submit" value="Send Message">
</fieldset>
</form>
</div>
</body>
</html>
and contact.php file is
<?php
echo "Hello";
?>
You need to return false; to prevent the form from submitting and refreshing the page and check if your $("#div1") is missing.
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
return false;
});
});
Simple. Since you are posting your form through ajax, you must prevent the default form submit by returning a false inside the submit method. Below is the correct version:
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url:"contact.php",
data: str,
success:function(result) {
$("#div1").html(result);
}
});
return false;
});
});
</script>
You can use a more simple form of post request as follows:
$.post("url",{var1: value1, var2: value2},function(data,status){
if(status=='success')
alert(data);
});
the second argument you can pass as many using this post request. The first argument url, if ofcourse relative to the document in which this js is loaded or you can give the exact url on the server.
According to your php file, data=='Hello'.
Similar is the procedure for any GET request also.
Make sure you are missing the div1
please use
<div id="div1"><div>
Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});
i have a newsletter form i use on my site using ajax with jquery. i want to show to a user a wait message.
what is the best option?
heres what i have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
$.ajax({
type: "POST",
url: '/save.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// my code when success
}
});
});
});
</script>
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
</form>
</div>
thanks
Here's what you can do:
Create a div (message dialog) and show when the user press on submit and hides it when the ajax is completed.
I would also recommend to use the jQuery Validation plugin to validate the email.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
// validation
$.ajax({
type: "POST",
url: '/file.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// do what ever you need
},
error: function (response, desc, exception) {
// alert some message
},
beforeSend: function() {
$('#loader').fadeIn(1000);
},
complete: function() {
$('#loader').fadeOut(1000);
},
});
});
});
</script>
<style type="text/css">
#loader { display: none; /* and other css youy need like border, position, etc... */ }
</style>
<div id="loader">loading ...</div>
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
</form>
</div>
You can do it something like this.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
//Put the loding script here
$("#preloader").show();
$.ajax({
type: "POST",
url: '/save.php',
data: $('#form').serialize(),
cache: false,
success: function(result) {
// my code when success
//Stop the preloader if the process is done
$("#preloader").hide();
}
});
});
});
<div id="newsletter">
<form id="form">
<label for="email">Your Email*:</label>
<input name="email" value="" type="text" id="email" size="30" maxlength="255" />
<span id="submit">Submit</span>
<img src="preloader.gif" id="preloader" />
</form>
</div>
When the user hit the submit show your preloader image. After the process is done, hide it.