I'm new to jquery, php and ajax and was writing this code with the help of a colleague.
My code:
if( name == '' ){
alert("Please enter your name");
$("#name", first).focus();
status = 'N';
}
else {
status = 'Y';
};
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
$("#email", second).focus();
status = 'N';
}
else {
status = 'Y';
};
if( message == '' ){
alert("Please enter your message");
$("#message", third).focus();
status = 'N';
}
else{
status = 'Y';
};
if( status == 'Y'){
$.ajax({
type: "POST",
url: url,
data: {name:name, email:email, phone:phone, message:message},
success: function(data)
{
alert(data);
$("message_span").html(data);
// show response from the php script.
}
};
So my problem is that I want the .focus() to focus on the text area which is not filled in ascending order, which is not happening, which is why I'm using the first, second .. parameters.
Now the second problem is that the ajax is not giving me a pop up of "message sent successfully" which is there in my php code
My php code:
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$message=$_POST['message'];
$to='myemail';
$subject='Form Submition';
$message='Name: '.$name.'\n Phone: '.$phone.'\n Wrote the following messsage \n\n'.$message;
$headers='From: '.$email;
echo 'Message successfully sent';
Any help is much appreciated and I'm sorry if this question was asked before but I wasn't able to find it.
Thanks!
Here is a sample code to help you out. Try it:
$("#submit").click(function() {
var status = 'Y';
if ($("#name").val() == '') {
alert("Please enter your name");
$("#name").focus();
status = 'N';
return false;
}
/* if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
$("#email").focus();
status = 'N';
}
*/
if ($("#message").val() == '') {
alert("Please enter your message");
$("#message").focus();
status = 'N';
return false;
}
if (status == 'Y') {
$.ajax({
type: "POST",
url: url,
data: {
name: name,
email: email,
phone: phone,
message: message
},
success: function(data) {
alert(data);
$("message_span").html(data);
// show response from the php script.
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='name' />
<input type='text' id='message' />
<button id="submit">Submit</button>
Related
I have a login form using ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't.
php :
<?php
include 'db.php';
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$cek = mysqli_query($conn, "SELECT * FROM user_csr WHERE email='$email' AND csr_pwd='$password'");
if(mysqli_num_rows($cek)>0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax :
function ceklogin(){
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
$.ajax({
url: 'tes.php',
method: 'POST',
data: {email: email, password: password},
success: function(html) {
if(html == 'true')
{
alert("login success");
}
else
{
alert("login failed");
}
}
});
}
<form>
<input type="email" name="email" id="mail" required>
<input type="password" name="password" id="pass" required>
<button type="submit" class="w3ls-cart" onclick="ceklogin()">Sign In</button>
</form>
the result of an alert is 'login failed'. but email and passwords are in accordance with the database.Hope anyone can help me out on this one, thanks in advance.
This should work. Just make sure you have a DIV as identified below to show your result.
function ceklogin() {
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resultDiv").innerHTML = this.responseText;
}
};
var sentInfo = "email=" + email + "&password=" + password;
xhttp.open("POST", "YourPHPFileHERE.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(sentInfo);
}
you should try adding "===" in your if condition.
` if(html === 'true')
{
alert("login success");
}
else
{
alert("login failed");
}`
I don't really understand why this does not work - I have read a whole lot about this specific problem, but I must be missing something.
I want to alert the "echo" from the PHP - which it doesn't.
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "json",
success: function(data){
alert(data);
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "This is your current email";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "Your email is changed";
}
} else {
echo "Please provide a correct email";
}
The database is updating, do the script itself runs perfectly, but after the "success" - it doesn't alert anything.
UPDATE
I have now tried this:
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "text",
success: function(data){
if(data == 1) {
alert("This is your current email");
}
else if(data == 2) {
alert("Your email is changed");
}
else if(data == 3) {
alert("Please provide a correct email");
}
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "1";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "2";
}
} else {
echo "3";
}
The console is returning the raw data (1,2,3) but the alert is still not showing!
I am tring to send data from ajax but getting post error. I also took help form ReCaptcha 2.0 With AJAX but still I am getting the same POST error in php fle.
$("#submit").click(function(){
var name = $("#name").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message= $("#message").val();
if(name=='' || mobile=='' || email=='' || subject=='' || message==''{
$("#errmsg").html("All fields are required");
} else {
//$("#reqmsg").html(username);
$.ajax({
type: "POST",
url: "insertquery.php",
data: "name="+name+"&mobile="+mobile+"&email="+email+"&subject="+subject+"&message="+message+"&g-recaptcha-response="+grecaptcha.getResponse(),
success: function(data){
if(data=="ok"){
alert("query submitted");
window.location="http://www.intuitioninteriors.in";
} else {
$("#errmsg").html("some went wrong.please try again");
}
}
});
return false;
}
});
Above is the ajax file.
include("database.php");
$name=$_POST["name"];
$mobile=$_POST["mobile"];
$email=$_POST["email"];
$subject=$_POST["subject"];
$message=$_POST["message"];
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
$url="http://www.google.com/recaptcha/api/siteverify";
$privatekey="xxxxxxxxxxxxxxxxxxxxxxxxx";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$privatekey."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
if ($response["success"] != false) {
$query="insert into query values(NULL,'$name','$mobile','$email','$subject','$message')";
$result=mysqli_query($conn,$query)or die(mysqli_error($conn));
if($result){
echo 'ok';
} else {
echo 'not ok';
}
} esle{
echo 'not verified';
}
This is php file.
Error: POST http://intuitioninteriors.in/insertquery.php 500 (Internal Server Error)
How can I fix it?
I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));
Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.