jquery ajax not catch the data back - javascript

I have this jquery ajax script
$.ajax({
type: "POST",
url: "register.php",
data: "name=" + name + "&email=" + email + "&password=" + password + "&confirm_password=" + confirm_password + "&captcha=" + captcha,
success: function(data){
if(data == "Success"){
$("#tombol_submit").remove();
$("#register_sukses").fadeIn(500);
}else{
$("#register_gagal").html(data).fadeIn(500);
$("#submit").removeAttr("disabled").attr("value", "Submit");
}
}
in the register.php, once the data successfully added to database, it will echo the "Success" word, the word Success is appear in the form page, but the button (tombol_submit) not removed, otherwise it back into Submit button (just like in 'else' statement). How to remove the button, so the client cannot click the submit button again?
here's the register.php script
<?php
session_start();
include "config/koneksi.php";
if(!empty($_POST['captcha'])){
if($_POST['captcha'] == $_SESSION['hasil']){
$fullname = $_POST['name'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$queryform = "INSERT INTO register (fullname,email,pass)
VALUES('$fullname','$email','$password')";
if ($hasilform = mysqli_query($konek2, $queryform)) {
echo "Success";
} else {
echo "Failed";
}
} else {
echo "The captcha code is wrong";
}
} else {
echo "The captcha cannot be empty";
}
?>

Normally $().remove() will work.
If you are asking why this if...else... doesn't work and always goes to else, please check the response from your backend to make sure the response is only a "Success" string.

You can try like this
$("#tombol_submit").css("display","none");

use this:
$("#tombol_submit").hide();

i think
id "tombol_submit" is not exit
Check console for error,
then based on error you can fix the problem.

Related

HTML form to trigger both php and javascript when submitted

I have a simple html form with just a box for the user to enter their email address.
When the "submit" button is pressed I want the email address submitted to be:
(a) emailed to me
(b) automatically added to a Google form
I can do both of these individually. I can perform (a) using:
<form id="input-form" action="email.php" method="POST">
where "email.php" is:
<?php
mail('me#gmail.com', $_POST['email'], "Add to Mailing List");
header('Location: https://my_website.com/thanks.html');
?>
and I do (b) using:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#input-form').on('submit',function(){
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
});
</script>
When I comment out the javascript, the submitted information is emailed to me as desired and the user is directed to my "thank you" page. But when I include the javascript, now the email doesn't arrive, but the email address that they entered is instead added to the Google form. So the Google form works part works, but it seems to override the sending of the email to myself.
Additionally, when the javascript is included the user no longer is redirected to my "thank you" page. Instead they are just directed to the Google form thank you page:
How can I get both (a) and (b) to happen after submission please?
You can use ajax to to activate your email.php script:
<script>
$('#input-form').on('submit',function(e){
e.preventDefault(); // this stops the form submit
var inputq1 = encodeURIComponent($('#email').val());
var q1ID = "entry.1047793221";
var baseURL = 'https://docs.google.com/forms/d/e/1FAIpFLSe7dz1sfyEigQF3QGkTfKCieaqb8OgXoGzLOZPmhn6TvjqFg/formResponse?';
var submitURL = (baseURL + q1ID + "=" + inputq1);
console.log(submitURL);
$(this)[0].action=submitURL;
var data = {
// fill with form input values
email: $('#email').val(),
};
// send ajax request to send your email
$.ajax({
url: '/email.php',
type: 'POST',
data: data,
success: function( response ) {
response = JSON.parse( response );
// check if email is sent successfuly and respond appropriately
if (response.status == 'success') {
$('#input-feedback').text('Thank You!');
location.replace("https://my_website.com/thanks.html")
} else {
$('#input-feedback').text('Ooops! Something went wrong.');
}
},
error: function (xhr, status, error) {
console.log( xhr.responseText );
}
});
});
</script>
PHP
<?php
$response = [
'status' => 'error',
];
// validate input values
if (empty($_POST['email'])) { // this is the most basic validation
echo json_encode($response); exit();
}
// check if mail was sent successfuly
if( mail('me#gmail.com', $_POST['email'], "Add to Mailing List") ) {
$response['status'] = 'success';
echo json_encode($response); exit();
}
// if email failed to send
echo json_encode($response); exit();

PHP return to jquery / ajax not working

PHP return to jquery / ajax not working,
In my edit function error message is displayed yet success function executed and in my delete function nothing is displayed yet success is executed..
Have tried everything :( (well obviously not everything...)
Any ideas?
currentPage.EditItem = function(id) {
if (confirm('Are you sure you wish to edit?')) {
console.log("DetailPage :: edit");
var itemm = $("#itemm").val();
var amount = $("#amount").val();
var statuss = $("#statuss").val();
var Uid = localStorage.getItem("Uid");
console.log(statuss);
if (itemm == "") {
alert("Please enter item");
} else if (amount == "") {
alert("Please enter amount");
} else if (statuss == "") {
alert("Please enter status");
} else {
$.ajax({
type:'POST',
url:'http://www.mywebsite.com/edit.php',
data:{'Uid':Uid,'itemm':itemm,'amount':amount,'statuss':statuss},
success: function(data) {
alert("Edit item success");
window.location.href = "new_up.html";
},
error: function() {
alert("Edit user failure");
},
});
window.location.href = "new_up.html";
};
};
};
PHP
<?php
// Check connection stuff
$itemm_id = $_POST['Uid'];
$itemm_itemm = $_POST['itemm'];
$itemm_amount = $_POST['amount'];
$itemm_statuss = $_POST['statuss'];
print($itemm_statuss );
$qry = "xxxxxxxxxxx";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "success";
mysqli_close($con);
?>
DELETE
currentPage.deleteItem = function(id) {
if (confirm('Are you sure you wish to delete?')) {
var Uid = localStorage.getItem("Uid");
$.ajax({
type:'POST',
url:'http://www.mywersite.com/delete.php',
data:{'Uid':Uid},
success: function(data){
if(data == "YES"){
alert("Item deleted!");
window.location.href = "new_up.html";
}
else{
alert("can't delete the row")
}
},
});
};
};
PHP
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$itemm_id = $_POST['Uid'];
$qry = "DELETE FROM balance1 WHERE id ='$itemm_id'";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "YES";
mysqli_close($con);
?>
You might want to improve the indentation of your code before posting. It's hard to read this way. Posting a clear question with clear example code will get you more responses.
I didn't check the whole code because of this, but I think this will help you to find the error:
The success function of your ajax call gets fired whenever it manages to send its data to the server and gets a textual reply. This means it is also fired when the server returns an SQL error: this error message is also a reply.
You might want to view the results in the console to see what is going on:
success: function(data) {
console.log(data);
},
Or have the script check the response to see if the expected string 'success' was returned or something else (like an SQL error):
success: function(data) {
if(data == 'success'){
// OK!
}else{
// The server didn't say 'success' so something fishy is going on.
}
},
Also: 'success' will always be echoed the way you've written your code now. You should place it somewhere it will only be triggered when it was actually ok:
if (mysqli_query($con,$qry)){
echo "success";
}else{
die('Error: ' . mysqli_error($con));
}
You could do:
if (!mysqli_query($con,$qry)) {
header("HTTP/1.0 404 Not Found");
exit;
}
which should trigger the error: option in your jQuery call.
The reason why your code won't work is because die('Error: ' . mysqli_error($con)); to jQuery actually means "success": the server returned some text as response with a header 200 - jQuery is not going to parse that text to see if it contains the word "Error".

AJAX and HTML element not working

I am trying to set a div tag to display a message if user isn't found in the database.
This is the line I can't get to work:
$("message").html(msg);
If you could help me understand what I'm doing wrong it would help. Thanks
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var code = $("#code").val();
var msg = "Who are you?!";
var dataString = 'username='+ username + '&code='+ code;
localStorage.setItem("number",code);
if(username==''||code=='')
{
alert("Um..you are missing something...");
}
else
{
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function(result){
if(result != 0)
alert(result);
},
error: function(){
$("message").html(msg);
}
});
}
return false;
});
});
My PHP code
<?php
$username = trim($_POST["username"]);
$code = trim($_POST["code"]);
include_once './inc/config.php';
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sql="SELECT * FROM info WHERE First_Name='".$username."' AND Line_Number='".$code."'" ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
return false;
}
mysqli_free_result($result);
mysqli_close($con);
If your message element has the ID message, select it like this:
$("#message").html(msg);
If it has the class message, select it like this:
$(".message").html(msg);
The JQuery documentation contains an overview and in-depth description of all selector types.
In addition, to trigger the error method in your Javascript, your server-side code needs to send a HTTP error code, for example like this:
header("HTTP/1.1 404 Not Found");
Or like this:
http_response_code(404);
Is message a class or an ID? Make sure that you use the proper selector on which your output is to be displayed.
Use, # for id and . For class
error: function(){
$("#message").html(msg);
To target a div with id message use
$("#message")
You have missed the #
Try this:
$.ajax({...
success: function(data){
if(data)
$("#message").html (msg);
else
alert(data);
}
});
Apart from the obvious error in the message selector, another problem I can see is in your code is in your PHP.
Your php code does not return an error condition, it returns a true or false, so always your success callback will be called.
So
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
echo false;
}
then
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function (result) {
if (result) {
alert(result);
} else {
alert(msg);
//make sure you use a proper selector here
$("message").html(msg);
}
},
error: function () {
$("message").html(msg);
}
});
error: function(){
$("message").html(msg);
}
Do you respond with 404 or anything else, except of 2xx, when user is not found? And, yes, selector is incorrect. Your function will be called only in case of HTTP error during request to the server.
This
else{
//echo "Who are you?!";
return false;
}
will not run your function.
This
else{
//echo "Who are you?!";
header("HTTP/1.0 404 Not Found");
exit;
}
can do it, but not a very nice solution. The best one is to return something like this
$response = array('status' => 'failed', 'text' => 'Whatever');
header('Content-type: application/json');
echo json_encode($response);
exit;
and in your success function work with data, check the 'status' and so on.

Trying to show sucess message with jQuery concatenated with php echo

Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources