I am creating a signup form in HTML/CSS/JS which uses an AJAX request to get response from server. In my jQuery, I use a method to validate form contents which also calls a function (containing ajax) to see if the username exists or not. I have checked the similar questions but couldn't relate to my problem.
The AJAX goes inside a function like this
function checkIfUserNameAlreadyExists(username)
{
// false means ok, i.e. no similar uname exists
$.ajax
({
url : 'validateUsername.php',
type : 'POST',
data : {username:username},
success : function(data,status)
{
return data;
}
});
}
The PHP code looks like this
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$enteredLoop=false;
$linkobj = new mysqli('localhost','root','','alumni');
$query = "select username from user where username='".$uname."'";
$stmt = $linkobj->prepare($query);
$stmt->execute();
$stmt->bind_result($uname);
while($stmt->fetch())
$enteredLoop=true;
if($enteredLoop)
{
echo "
<script type='text/javascript'>
$('.unamestar').html('Sorry username already exists');
$('.userName').css('background-color','rgb(246, 71, 71)');
$('html,body').animate({
scrollTop: $('.userName').offset().top},
'slow');
</script>";
return;
}
}
?>
The function checkIfUserNameAlreadyExists returns false by default (don't know how) or this ajax request is not submitted, and it submits the form details to php.
Any help ?
Your checkIfUserNameAlreadyExists() function is synchronous and your ajax call is asynchronous. That means that your function will return a value (actually no value is returned at all in your case...) before the ajax call is finished.
The easiest way to solve this, is to generate the html in the success function, based on the return value of the data variable.
Something like:
success : function(data,status) {
if (data === 'some_error') {
// display your error message, set classes, etc.
} else {
// do something else?
}
}
Apart from that, are you actually setting the value of $uname to $_POST['username']?
You need to append response script to the document for executing.
function checkIfUserNameAlreadyExists(username)
{
// false means ok, i.e. no similar uname exists
$.ajax
({
url : 'validateUsername.php',
type : 'POST',
data : {username:username},
success : function(response)
{
$('body').append(response);
}
});
}
Related
I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;
I am trying to check username's availability from the database by using jQuery's $.post.
I don't know if the path is wrong or the php script is wrong but it keeps returning a data of blank or null perhaps. Why is that?
JS File:
$(document).ready(function(){
$("#signup_username").bind("keyup blur",function(){
$("#loading_img_username").show();
var prompt_username = $("#signup_username").val();
if(prompt_username != ''){
$.post('php/check.php', {username: prompt_username} , function(data){
$("#signup_username_status").html(data);
$("#loading_img_username").hide();
}).error(function(){
$("#loading_img_username").hide();
$("#signup_username_status").html("<span style='color:#cc2000;'><i class='glyphicon glyphicon-remove'></i> Cannot verify username availability.</span>");
});
} else{
$("#signup_username_status").html("<span style='color:gold;'><i class='glyphicon glyphicon-info-sign'></i> Provide your username.</span>");
$("#loading_img_username").hide();
}
});
});
PHP FILE:
<?php
$user = $_POST['username'];
echo $user;
I am aware that whatever you prompt at the input field : #signup_username will be an output as data to be pass on a callback function at $.post
Suggestion 1:
jQuery his post function is using datatypes to receive information, you are using the datatype "text" on this moment. I should use XML or JSON since that's clearer to read out.
$.post('url', {username: prompt_username}, function( data ) {
$("#signup_username_status").html(data.username);
$("#loading_img_username").hide();
}, 'JSON');
You'll need to encode the data in PHP if you do this to:
$user = $_POST['username'];
die(json_encode(array('username'=>$user)));
Suggestion 2:
Does your jQuery post request not work? Debug it with the .error function it's kinda handy if you know how to use it! Here is an example of how to put out errors:
$.post('url', {username: prompt_username}, function( data ) {
$("#signup_username_status").html(data.username);
$("#loading_img_username").hide();
}, 'JSON').error(function( a,b,c ) {
console.log(a,b,c);
});