I have this span in the html body:
<span id="username_status"></span>
snippet of sql query:
if($exist > 0)
{
echo 'Sorry, That username is Taken!'; //value in username_status
}
else{
echo 'Username available!'; //value in username_status
}
and i'm trying to use the query result to generate a form validation alert:
var s1 = document.getElementById('username_status').innerHTML;
if (s1 === "Sorry, That username is Taken!")
{
alert("Please Change Your Username. It is already used.");
return false;
}
}
I've searched far and wide, but it looks i'm not getting anything. any help?
Instead of returning a message you can return a status code like status:success.
And i think you should send an ajax request to handle this,if you want to use javascript:
Javascript(I assume you use jQuery):
$.post("your-php-file.php",{username:"some-username"},function(data){
if(data.status == "success"){
alert("This username is available");
}
else{
alert("This username is already in use.");
}
});
PHP:
if($exist > 0){
$res['status'] = "success";
}
else{
$res['status'] = "failed";
}
echo json_encode($res);
Related
I send a post request to a php file with some data:
function addNewPost(){
$.post('create_post.php', {},
function(data){
if(data != 'OK'){
$('.errorMsg').html(data);
}else{
alert('Well Done! Post Is Added Successfully');
}
},
);
}
$(document).on("click",'#create', addNewPost);
The php file connects the DB and insert data to the Database, And if the data is inserted successfully the file returns OK:
$st = $conn->prepare('INSERT INTO posts() VALUES(?, ?, ?, ?, ?)');
$st->execute();
if ($st) {
echo 'OK';
}
It returns OK, But it's added to the errorMsg element, So the if condition is executed although the returned data = OK.
Also I tried:
if(data == 'OK'){
alert('Success');
}else{
$('.errorMsg').html(data);
}
But didn't work neither.
What's wrong? Should I set specific dataType? Should I replace echo with return?
You can do as:
if ($st) {
echo 'OK';exit;
}else{
echo false;exit;
}
or try this:
if ($st) {
echo json_encode(array("message"=>"OK"));exit;
}else{
echo json_encode(array("message"=>false));exit;
}
in js file:
var jsonResp = $.parseJSON(data);
if(jsonResp.message == 'OK'){
alert('Success');
}else{
// else case
}
I'm trying to redirect a user to an existing URL (stored in a MySQL database) if the value they input already exists in the database. I've got most of it working, but I've run into some issues.
I'm using AJAX to check the database. It sends the input value to another PHP file & checks the database to see if it already exists.
if($row) {
echo ".$row["itemNum"].";
} else {
}
It's within the AJAX code that I'm having issues, in particular this:
success: function (response) {
if (response == <?php ".$row["itemNum"]." ?>) {
window.location.href = "http://www.example.com/" <?php echo "+"; if (".$row["itemNum"].") { echo ".$row["itemNum"]." } else {""}
} else {
// do other stuff
}
}
$row["itemNum"] doesn't always exist, so it's in a conditional statement to prevent a syntax error.
The above doesn't work regardless of how I do it.
I have a feeling the main issue is with the if (response == <?php ".$row["itemNum"]." ?>) line?
Based on this code:-
if($row) {
echo $row["itemNum"]; // check the change here
} else {
}
You have to do like this:-
success: function (response) {
if (response !== '') { // if response have some value
window.location.href = "http://www.example.com/"+response;
} else {
// do other stuff
}
}
As you suspected you have problem with following line.
if (response == <?php ".$row["itemNum"]." ?>) {
The Problem is your use of (") and (.) characters
Following syntax will give you what you want.
if (response == <?=$row["itemNum"]?>) {
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".
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
I've just been helped with some functions and callbacks to get this animation on my form once submitted:
$("#message").show().delay(5000).fadeOut('fast', function(){
$("#slide_panel").slideToggle("slow");
});
Though, the problem I have now is, if someone had to submit the form without entering the correct details, the error message will also pop up (pops up in the same div "message" as the thank you message), delays for 5 seconds and then closes the form.
Of course, I don't want it to close the form, instead show the error message for 5 seconds and then fadeout the error message.
Anything I need to add here:
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$('#name').val( "" );
$('#email').val( "" );
$('#phone').val( "" );
$('#dayin').val( "" );
$('#dayout').val( "" );
$('#comments').val( "" );
$('#verify').val( "" );
$("#message").show().delay(5000).fadeOut('fast',
function(){
$("#slide_panel").slideToggle("slow");
});
}
);
});
return false;
});
});
I'm assuming I need to do something similar to this code:
if(data.match('success') != null);
In my contact.php form.... I have this:
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
Anything I need to do here? Or do I only need to edit the javascript file?
if you use JSON to call a function somewhere in the code behind you will be able to return a status property.
I used it aswell in my current project and here is an example of how I used it:
var link = '/brainbattleJSON/MarkAssignmentAsInProgress';
$(this).hide();
$.getJSON(link, { questionId: qId }, function (json) {
if(json.status == "ok"){
//do this
}else{
//do this
}
});
Code behind:
// your function with validation
// if the form is valid make status "ok" otherwise put anything else
Return Json(New With {.status = "ok"});
I hope this can help you a bit :)
Edit:
You will need to change the value of var link to the path of your function where you check the form.
Then where you now say if your error!='' you will send back the json.
in this you will say:
return json(new with{.status = 'error', .errors = 'yourErrors'})
So for errors it might be useful to send an array just in case if you get more than 1 error on the form.
All the messages will no longer be shown in php with echo but you will have to put the errors there with javascript.
I have a uploaded register and login pages(zip file) at following link:
http://www.4shared.com/folder/uanQHCAg/_online.html
It uses same div to display success and error messages. You can try and implement what you are looking for, with an addition of fadeout effect.