Obtaining data from server for POST not working - javascript

I am still quite new to Jquery and Ajax request. On the website I am developing I have a simply form element that sends the input data which is an email to the server. For some reason I cant find a way to obtain the form information to send it to the server.
Here is my Jquery code
$( document ).ready(function() {
var temp = "http://localhost:5000/"
$( "#target" ).submit(function( event ) {
var aa = $('#target').serialize();
alert( "Handler for .submit() called." + aa);
$.ajax({
type: "POST",
url: temp+"sign",
data: aa,
success: function(){},
dataType: "string"
});
});
});
it is quite messy... I am trying to diagnose the problem.
this is the form element
<form class="form-inline text-center-min" id="target" style="padding-bottom: 100px">
<div class="form-group ">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
<input type="email" class="form-control filter" id="exampleInputEmail2" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-filter">Join</button>
</form>
Please it would be awesome for any help for this.

Use event.preventDefault(); head of your callback function.
$(document).ready(function () {
var temp = "http://localhost:5000/"
$("#target").submit(function (event) {
event.preventDefault();
var aa = $('#target').serialize();
alert("Handler for .submit() called." + aa);
$.ajax({
type: "POST",
url: temp + "sign",
data: aa,
success: function () {},
dataType: "string"
});
}); });

Related

Save input data and add icon inside textbox after ajax success

I want to save each input text by its own id and append the icon inside that input after ajax succeed.
HTML:
<div class="form-group has-feedback autosave">
<input type="text" class="form-control" id="fname" name="fname" placeholder="Your name"/>
<i class="form-control-feedback"></i>
</div>
<div class="form-group has-feedback autosave">
<input type="text" class="form-control" id="lname" name="lname" placeholder="Your lastname"/>
<i class="form-control-feedback"></i>
</div>
Javascript:
$(document).on('blur', '.autosave input', function(e) {
//when input inside .autosave was blurred
var _id=$(this).attr('id');//id
var _val=$(this).val();//value
$.ajax({
type: 'POST',
url: 'save.php',
data: {id:_id,val:_val},//send id and val
dataType: 'json',
success:function(data){
$(_id).addClass('fa fa-check');//addclass when succeed
console.log(data);//debug
},//success
});//$.ajax
});
I plan to display the check icon inside each input when the submit succeed. So the idea is getting the id and val from each input. And send it to db via ajax. After the response, that input will be update with icon with specific id.
You don't need to use the element's id - you can store the reference to this which the function runs under and use that within the $.ajax success handler. Try this:
$(document).on('blur', '.autosave input', function(e) {
var $el = $(this);
$.ajax({
type: 'POST',
url: 'save.php',
data: {
id: $el.prop('id'),
val: $el.val()
},
dataType: 'json',
success: function(data) {
$el.addClass('fa fa-check');
console.log(data); //debug
},
});
});
Finally, after a big trying. I found the solution. Thanks to #RoryMcCrossan who gave me the starting idea.
Javascript
...
success: function(resp) {
$this.closest('.form-line').find('i').removeClass('fa fa-check').addClass('fa fa-check');
$this.closest('.form-group div.form-line').addClass('success has-success');
console.log(resp); //debug
},
The only different is the process after success. It looks messy, but working. If you have any shorter pattern would be appreciated.

not able to submit form without page reloading

I have the following code that i wish to use to submit form without reloading the page, but it reloads the entire page and when checked in console the script.php page is also not getting executed.
Code on index.php page
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
code on script.php page
<?php
$name=$_POST['name'];
echo $name;
?>
Can anyone please tell how i can submit the form without reloading the page and also display the result from script.php page on index.php page
update your function. pass event object in function. and use event.preventDefault() to prevent default submit action.
$(".submit").click(function(e) {
e.preventDefault();
try this
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
OR
<input type="button" class="submit" />Submit
You need to send the data from the script.php page back to your index.php page. Swich out the little bit of ajax for this:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
In your script.php:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>
Do not mix form submit and button click.
If you are a click event of button then use type="button" and if you are doing $("form").submit() then use type="submit".
Also check for
$(".submit").click(function(e) {
e.preventDefault();
and check your ajax post data , do
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});
Instead of listening to the input's click event, you should listen to the form's submit.
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>

Prevent Default is not working

I have checked around here and none of these solution on here fix my issue.
I cannot seem to get the preventDefault() to work. Code below:
Jquery:
$("#changepassword").submit(function(event) {
event.preventDefault(); // stop normal form submission
$.ajax({
url: "changePassword.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "html",
success: function(html) {
$("#s-window").append(html);
}
});
});
HTML:
<div id="s-window">
<form id="changepassword" action="changePassword.php" method="POST">
<input type="password" name="currentPassword" placeholder="Current Password"/>
<input type="password" name="newPassword" placeholder="New Password"/>
<input type="password" name="confirmPassword" placeholder="Confirm Password"/>
<input class="button" type="submit" value="Change Password" />
</form>
</div>
There are no errors on my conosle. The changePassword.php works as it is supposed to. But rather than updating my #s-window it redirects me to the changePassword.php page
How can I recode this to make everything happen on the page?
You need to wait until document is ready:
$(document).ready(function(){
$("#changepassword").submit(function(event) {
event.preventDefault(); // stop normal form submission
$.ajax({
url: "changePassword2.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "html",
success: function(html) {
$("#s-window").append(html);
}
});
});
});
You can try this way using return false;, if you have any confusion see here more event.preventDefault() vs. return false
$("#changepassword").submit(function(event) {
//event.preventDefault(); // stop normal form submission
return false;
});
At least in IE, event is a global variable (as per Is 'event' a reserved word in JavaScript?). This may not be the cause of your problem, but it might be a good idea to change your naming nonetheless.
In you ajax call change dataType: "html" to dataType: "script"

Disabling button on ajax submit

I have this button that I want to disable when my ajax is running, and then being enabled again once it's done.
My HTML:
<form name="send" class="stacked form-send-disable" id="form">
<label for="senderID">Your phone number here (senderID)</label>
<input type="tel" name="senderID" id="senderID" autofocus="on" class="input-1-2" placeholder="Your number" maxlength="9">
<label class="error" id="senderID_error" for="senderID">Please enter your own number here.</label>
<label for="recipient" id="recipient_label">Your recipient(s)</label>
<input type="text" name="recipient" id="recipient" class="input-1" maxlength="50" placeholder="e.g 748930493 - add multiple numbers by using a comma ' , '.">
<label class="error" id="recipient_error" for="recipient">You need to enter at least one number here.</label>
<label for="message">Write your message</label>
<textarea type="text" name="message" class="input-1" placeholder="(Write something clever..)" id="message"></textarea>
<label class="error" for="message" id="message_error">You can't send empty messages.</label>
<input type="submit" name="submit" class="button btn btn-green block disabled-btn" id="submit_btn" value="Send the message(s)">
</form>
ajax:
<---- Some form validation going on up here ------>
var dataString = 'recipient=' + recipient + '&message=' + message + '&senderID=' + senderID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
return false;
});
I tried to do the following in my document:
Jquery:
$('#form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
But nothing happens. I guess I have to somehow call this within the ajax, so that it applies to the button that way?
Thanks in advance.
UPDATE
$(':submit', this).prop('disabled', true);
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
}).always(function(){$(':submit', this).prop('disabled', false);});;
}
I updated with the above code (big thanks to A.Wolff), and my ajax request still works, however there is no change on the button, which i assume is because of lack of css for this particular state of the button, how do I go about this?
Thanks to the other replies, i will try them out.
I made a working demo that disables the form whilst the ajax request is happening. I hope its of some use. See: http://jsfiddle.net/EWkpR/
$("#form").on("submit", function(event) {
//stop the default submission:
event.preventDefault();
//create an alias to this form
$form = $(this);
//create the feedback element
$feedback = $("<div id='feedback'>Please wait...</div>");
$form.before($feedback);
//validate the form:
var valid = true;
/*[some form validation here]*/
//use jQuery's serialize to build the form submission params:
var dataString = $(this).serialize();
console.log(dataString);
//check if invalid
if(!valid){
//not valid. tell the user
$feedback.html("<p>Some message about invalid fields!</p>");
} else {
//valid.
$form.disable();//disable the form;
//do the ajax
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$feedback
.html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.fadeIn()
.delay(4000)
.fadeOut("normal",
function(){$form.enable();}//callback to fade the form back in
);
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
}
return false;
});
//plugin function to disable form fields
$.fn.disable = function(){
this.fadeTo(1,.5);
this.find("input").attr("disabled", true);
};
//plugin function to enable form fields
$.fn.enable = function(){
this.fadeTo(1,1);
this.find("input").removeAttr("disabled");
};
You can set the button as disabled before the AJAX runs and re-enable it once the ajax has completed.
$.ajax({
beforeSend: function() {
$("input[type=submit]", $("#form")).attr("disabled", "disabled");
},
...
complete: function () {
$("input[type=submit]", $("#form")).removeAttr("disabled");
}
});
Edit: I notice there is a class on the button disabled-btn if this needs to be added and removed as the button is disabled/re-enabled then you can do this by chaining the following to the above:
.addClass("disabled-btn");
...
.removeClass("disabled-btn");
I would assume if this is the case then the class should be removed from the actual element to start with.
You could use:
//using allias for nested ajax:
var _self = this;
$(':submit', _self ).prop('disabled', true);
//your nested ajax request
$.ajax(...).always(function(){$(':submit', _self ).prop('disabled', false);});

HTML/JQuery: Button submits once when it shouldn't at all

I'm using jQuery to allow the form to submit, so I don't want the form to submit on it's own.
Here's my form:
<form class="navbar-form navbar-right" id="signform">
<div class="form-group">
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button id="signbtn" class="btn btn-success">Sign in</button>
</form>
Here's my JQuery code:
var signingIn = false;
$(document).ready(function() {
$('#signbtn').click(function() {
if (signingIn) return;
signingIn = true;
var img = $('<img id="loader" style="padding-left: 10px;" src="loader.gif"/>');
$(this).after(img);
var data = $('signform').serialize();
$.ajax({
url: '/logs',
type: 'post',
data: data,
done: function() {
$('#loader').remove();
alert('success');
}
});
});
});
Now when I go to the url: website.com/index.html and click Sign in, it refreshes the page (what I don't want at all) and goes to website.com/index.html? - Now when I click it again, nothing happens (exactly what I want all the time so my added elements through jQuery isn't lost).
You want to use jQuery ajax call like so:
$(document).on('click','button#signbtn', function(){
var $form = $('form#signform');
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data){// whatever you want your code to do on success}
})
return false; // avoid to execute the actual submit of the form.
});
$(function() {
$( '#signform' ).submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function(result) {
// Do something on success
}
});
});
});

Categories

Resources