Post a form using Jquery ajax and get the response - javascript

I'm using this code to post a form using jquery ajax .
my problem is that i want to make php code to be like this:
if (isset($_POST[''])) {
// some code here
}
this is the javascript code:
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" )
$("div#status").html("Please enter your Email");
else
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
$("#myForm").submit( function() {
return false;
});
});

If you tested the code, and the php section works fine, but you can not get a response in jquery, then, you should check your php code(It should be like this):
if (isset($_POST[''])) {
$data = "";
// some code here to fill $data
echo $data; // this is the actual response to the jquery interface.
}

There are 6 b's in php file name but 7 b's in ajax url.
url: "bbbbbbb.php", <--- 7 b's
bbbbbb.php <--- 6 b's
Plus, along with success you should have error also so you'd see what the error is.
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}

Despite a lack of actual question, here's a crack at an answer.
The first issue is that the javascript, while working, won't get to do the complete job it's supposed to do. The javascript code appears to want to prevent the form from being manually submitted via the submit event. You may want to reorganise the javascript to look like:
$("#myForm").submit( function() {
return false;
});
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" ) {
$("div#status").html("Please enter your Email");
} else {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
}
});
Additionally, you may want to look up usage of modern event watching in jquery, and the usage of .on(). i.e. $("#myForm").on("submit", function() {});. But that's not quite the point of this post.
As for the PHP code, let's infer you have the following HTML form:
<form action="login.php" id="myForm">
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
<button type="submit" id="submit" name="submit" value="submit">Submit</button>
</form>
<div id="status">Please provide username and password to login</div>
In login.php, you would have
if (!empty($_POST)) {
if (isset($_POST['submit']) && $_POST['submit'] == 'submit') {
// validate $_POST contains username and password
...
// sanitize username and password
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);
// do my processing
// doLogin returns true for successful login, or message contain error string
$result = doLogin($_POST['username'], $_POST['password']);
if ($result === true) {
echo 'You have successfully logged in';
} else {
echo $result;
}
} else {
echo 'Unknown form action';
}
} else {
// do GET processing
}
With this, just echo the response you want to appear in the div#status.

Related

How to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

save data in database without redirection in php

I have a simple form, and I want to save the data in my database without redirection. I am using php, ajax and jquery for my page. I don't know if I did something wrong but after I hit the submit button the form data appears on the address bar. the data is stored in the database successfully but the page reloads as well. My code is given below.
HTML
<form>
<input type="text" placeholder="Full Name*" required pattern= "[a-zA-Z]+" title="Alphabets only" name="name" id="name">
<input type="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" name="email" id="email">
<input type="text" placeholder="Contact*" required pattern="[0-9]\d{9}" title="only 10 digit allowed" name="contact" id="contact">
<textarea placeholder="Enquiry(if any)" name="msg" id="msg"></textarea>
<button type="submit" name="register" id="register_btn">Register</button>
<span id="success"></span>
<span id="error"></span>
</form>
PHP
include("conn/connect.php");
if(isset($_POST['email'])){
$email= mysqli_real_escape_string($connect, $_POST['email']);
$name= mysqli_real_escape_string($connect, $_POST['name']);
$contact= mysqli_real_escape_string($connect, $_POST['contact']);
$msg= mysqli_real_escape_string($connect, $_POST['msg']);
$sql= "INSERT INTO registration(email, name, contact, msg, added_on) values('$email','$name','$contact','$msg', now())";
if(mysqli_query($connect, $sql))
{
echo '<h4>Registration Complete</h4>';
}
}
JAVASCRIPT
<script>
$(document).ready(function(){
$('#register_btn').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var contact = $('#contact').val();
var msg = $('#msg').val();
if(name == '' || email == '' || contact == '')
{
$('#error').html("<h4>Mandatory field(s) are empty</h4>");
setTimeout(function(){
$('#error').fadeOut("Slow");
}, 3000);
}
else
{
$('#error').html('');
$.ajax({
url:"registration.php",
type:"POST",
data:{name:name, email:email, contact:contact, msg:msg},
success:function(data){
$("form").trigger("reset");
$('#success').fadeIn().html(data);
setTimeout(function(){
$('#success').fadeOut("Slow");
}, 3000);
}
});
}
});
});
</script>
You're calling an event on submit button that will refresh your page.
Use event.preventDefault() in your click function.
$(document).ready(function(){
$('#register_btn').click(function(event){
event.preventDefault();
});
});
FYI, if your validations stop working then try to do this.
$('#register_btn').click(function(event) {
//Check form is valid
if ($(this).closest('form')[0].checkValidity()) {
// stop form from redirecting to java servlet page
event.preventDefault();
$.ajax({
type: form.attr("method"), // use method specified in form attributes
url: form.attr("action"), // use action specified in form attributes
data: form.serialize(), // encodes set of form elements as string for submission
success: function(data) {
// get response from servlet and display on page via jQuery
}
});
}
});
Reference
As Loading.. points out you need event prevent default but in the form submit event, like this:
$('form').on('submit', function(e){
return false;
});
return false on submit = e.preventDefault + e.sotpPropagation

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

How to display an alert box?

The following code actually submits and with the same i need to display an alert box showing message has been sent.
Code :
<input type="button" class="Jdvs_Btn" onclick="send_reply('SEND_REPLY', <? echo $clsSurvey->feedback_id?>);" value="SEND" style="font-weight:bold;width:95px;height:30px;float:left; margin-right:5px;" />
And the Javascript
Code:
if(action == "SEND_REPLY")
{
if( frm.email.value == "" )
{
alert("Please fill your email.");
frm.email.focus();
return false;
}
else if( validateEmailAddress(frm.email.value) == false )
{
alert("Please fill a valid email.");
frm.email.focus();
return;
}
else if ((tinymce.EditorManager.get('content_to_send').getContent()) == '')
{
alert("Please enter content to send.");
return;
}
else
{
frm.form_action.value = action;
frm.submit();
alert('Message Sent Successfully');
}
}
The code for mailing is:
This is where the validation and other are done, i need to display an alert box here
Code:
function sendReply()
{
echo $this->feedback_id;
$this->checkAndUpdateReply($this->feedback_id,$this->content_to_send);
$Message = nl2br($this->content_to_send);
$mailMessage = "
<html>
<head>
<title>constant('_SHORT_PRODUCT_NAME') - Feedback Mail</title>
</head>
<body>";
$Message = nl2br($this->content_to_send);
$mailMessage.= $Message."
<table border='0' cellpadding='0' cellspacing='0'width='100%'>
<tr>
<td style='$css_class' align='left'><br/>Email: "._EMAIL_INFO."</td>
</tr>
<tr>
<td style='$css_height' align='left'><br /><b>Note</b>:- This is an automatically generated email , Please dont reply back to this mail.</td>
</tr>
</table>
</body>
</html>";
$mailSubject= constant('_SHORT_PRODUCT_NAME').' - FeedBack Reply';
$clsEmailTempalte = new clsEmailTemplate($connect, "");
$clsEmailTempalte->sendMail($mailSubject,$mailMessage,$this->email);
}
At the end of your send_reply javascript function just do an alert("Mail Sent");
If you're using ajax (e.g. with jQuery) you'll need to add your alert to the callback.
For jQuery:
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
In your javascript function send_reply just add the line
alert("Message sent");
should work.
Just put alert("message has been sent"); at the end of your js function.
If I were doing this (using jQuery). I would call the php file that sends the email using ajax like so:
Your HTML:
<input type='button' id='submit_form' data-id='<? echo $clsSurvey->feedback_id?>' />
Your Javascript:
$('#submit_form').click(function(e){
// To stop the form submitting on button click if you want it to...
e.preventDefault();
// Send the id via post to the mailscript
$.ajax({
url: 'mailscript.php',
type: 'POST'
data: {
id: $(this).attr('data-id')
}
}).done(function(data){
// Use data if you want to return something from the script and add to the message maybe?
alert('Add your message in here');
});
});
Then just add your mailing php inside the mailscript.php (or whatever you want to call it). whenever your script has completed it's job, the done function will fire showing your alert.

Ajax POST keep firing error function event though php script success

I am using jquery, jquery mobile and html to build a mobile app using phonegap.
Using ajax to call php scripts in server, works fine; updating, inserting data and sending email. However ajax error function is what always called,
Using firebug, 200 ok status is what returned, no idea what triggers error.
I have searched for this issues and found many suggestions here such as using complete () or done() functions instead of success() and error(), echoing json response... but no luck with all these solutions.
one solution is to add this header to php script,
header("Access-Control-Allow-Origin: *");
header solution has solved my problem with all ajax post scripts, however I am concerning about possible security risks because it is should run in mobile application.
In addition, adding such header can be logic when we need to access database but if we have a contact form that call php mail function and no database changes will occur , why we need to add that header too?
contact form
<div data-role="header" data-position="fixed" >
<input type="button" value="Send" name="sendbutton" id="sendbtn" />
<h1>contact us</h1>
<a data-rel="back" data-icon="arrow-r" data-iconpos="notext"></a>
</div>
<div data-role="content" >
<form id="contact-us" >
<input type="text" id="contactName" placeholder="Name" />
<input type="email" id="email" placeholder="Your Email" />
<input type="text" id="subject" placeholder="Message Subject" />
<textarea rows="20" cols="30" id="message" placeholder="Message.." ></textarea>
</form>
</div>
Jquery script
$("#sendbtn").click(function(event){
$("#sendbtn").disabled =true;
var postData ="";
if($("#contactName").val().length == 0 ||$("#email").val().length == 0 ||$("#subject").val().length == 0||$("#message").val().length == 0)
alert("Sorry but some required fields are empty !");
else {
if (!regex.test($("#email").val()))
alert("Please check that you write email correctly!");
else {
postData='contactName=' + $("#contactName").val() + '&email=' + $("#email").val() + '&subject=' + $("#subject").val() + '&message=' + $("#message").val();
$.ajax({
type: 'POST',
data: postData,
url: 'mydomainname.net/services/contact.php',
success: function(){
$('input').not('[type="button"]').val('');
$('textarea').val('');
alert('Message was Sent, Thank you!');
},
error: function () {
alert('Sorry, Error occurred ');
$('.error').fadeIn(1000);
}
});
}
}
});
php code
<?php
if ( isset($_POST['email']) && isset($_POST['contactName']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "myemail#mydomainname.net", "Contact Form: ".$_POST['contactName']." Title ".$_POST['subject'], $_POST['message'], "From:" . $_POST['email']);
}
?>
The code send email but always called ajax error function
Any other solution rather than header solution? thank you.
there some unclose breaks, try this :
$("#sendbtn").click(function(event){
$("#sendbtn").disabled =true;
var postData ="";
if($("#contactName").val().length == 0 ||$("#email").val().length == 0 ||$("#subject").val().length == 0||$("#message").val().length == 0) {
alert("Sorry but some required fields are empty !");
} else {
if (!regex.test($("#email").val())) {
alert("Please check that you write email correctly!");
} else {
postData='contactName=' + $("#contactName").val() + '&email=' + $("#email").val() + '&subject=' + $("#subject").val() + '&message=' + $("#message").val();
}
}
$.ajax({
type: 'POST',
data: postData,
url: 'contact.php',
success: function(){
$('input').not('[type="button"]').val('');
$('textarea').val('');
alert('Message was Sent, Thank you!');
},
error: function ()
{
alert('Sorry, Error occurred ');
$('.error').fadeIn(1000);
}
});
});
First, i think, collecting postData you should do like $('#my-form').serialize();
url: 'mydomainname.net/services/contact.php'
url should be set with scheme prefix, if you want post to another server.
however I am concerning about possible security risks.
At server side you can check domain and than decide - send allowed header or not.

Categories

Resources