This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using AJAX to call a PHP file that does email validation and outputs simple text that gets returned to the AJAX Success. I am using the text returned to create variables to represent which error to display. I am having trouble using these variables, the form still submits. What could I be doing wrong?
My Code:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
success: function(data) {
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
}
});
}
if (invalid == 1) {
alert('invalid email');
error= true;
}
if (taken == 1) {
alert('email taken');
error= true;
}
if (error == true) {
return false;
}
Is this AJAX call inside a click event? If so, you may want to use event.preventDefault() function to avoid triggering the form submission:
event.preventDefault();
Have a look to the example in the documentation
You should have two things in consideration:
1) if you're ajax call is triggered by a link or submit button , you MUST use preventDefault function
2) in your "checkmail.php" don't forget to call exit function in the end of call
Related
I am using two ways for user login in codeigniter:
One is by typing url like this localhost/mySite/login
Other is popup dialog appear when I click a link from localhost/mySite
When I'm following step 2 then calling a function using ajax request.
both time I am calling same function. but when call to the function using Ajax load an additional header.
I used following code for the calling function.
if ($this->input->is_ajax_request()){
echo json_encode(array('status'=>'success','url'=>'auth/enable_account'));
exit();
}
else {
redirect ( "auth/enable_account",'refresh');
}
My jquery code
jQuery('#signin_form').submit(function(event) {
var email = jQuery('#email').val();
var password = jQuery('#password').val();
var remember = jQuery('.dev_signin_remember').is(':checked');
jQuery.ajax({
url:baseurl+'auth/login',
type:'POST',
data:{'email':email,'password':password,'remember':remember},
dataType:'json',
success:function(data){
if(data.status == 'success') {
if(data.url != '') {
window.location.replace(baseurl+data.url);
}
else {
window.location.replace(baseurl+"auth/login");
}
}
else {
jQuery('.dev_signin_error').html('Invalid Username or password');
}
}
});
setTimeout(jQuery.unblockUI);
});
This question already has an answer here:
How to handle multiple actions using a single html form
(1 answer)
Closed 9 years ago.
I've a form "dataEmp" where user has to enter username and password and "submit".I have successfully sent the form data to "checkLogin.php" file but what if i want to send that same form to another file, "logout.php". After doing some searching i found I've to use jquery ajax to do so. I'm not very familiar with ajax so if you give the full code, it'll be appreciated.
<form id="dataEmp" name="dataEmp" action="checkLogin.php" method="post">
.
. //user details
.
</form>
Here i am just giving your idea to make call with ajax on success page to where you wish to store data just call like below
$(document).ready(function() {
$('#loginform').submit(function(e) { // fetch data from form to submit to action.
e.preventDefault();
$.ajax({
type: "POST",
url: '/class/check_login.php',
data: $(this).serialize(),
success: function(data)
{
if (data === 'Login') {
window.location = '/user-success.php';
}
else {
alert('Invalid Credentials');
}
}
});
});
});
but you should have to write you php code in your way to handle this request in server side.
This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
this is my first question at stackoverflow, speaking specifically ... i am using the result of my PHP file ("myphp.php") ...
<?php
echo "Hello"
?>
now the javascript code that was called :
function functionX()
{
var result;
$.post("myphp.php",function(data)
{
result=data; /// result should be Hello
});
alert(result); /// the msgbox shows "Undefined"
// i am enable to access the result i got from PHP file
}
So my problem is how to access the result , so that i can use it at other parts of my code ...
OR can you suggest some other ways .. THANXX
as i am a newbie to ajax .. i want to use this concept for checking username availability as shown
var result;
function functionX(username)
{
$.post("check_username.php",{usn:username},function(data)
{
if(data=="OK"){result="yes";}
if(data=="FAIL"){result="no";}
});
alert(result); // Now i want the result here .. its important
}
<?php
$usn=$_POST['usn'];
$flag=0;
$q=mysql_query("SELECT * FROM accounts");
while($row=mysql_fetch_assoc($q))
{
if($row['usn']==$usn)
{
$flag=1;break;
}
}
if($flag==1)
{
echo "OK";}
else
echo "FAIL";
?>
i know these methods for detecting username existence can be silly .. so that's what i did
try this
var result;
$.ajax({
type: "POST",
url: 'myphp.php',
success: function (data) {
result=data;
}
});
alert(result);
It's because if you just put the code below it doesn't mean after as raina77ow mentioned.
If you don't need the data later just use this:
function functionX(){
$.post("myphp.php",function(data) {
alert(data);
});
}
I've been on a problem for hours without finding any issue...
I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.
In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.
Here is part of the code :
function validateRegistration(){
// Some tests....
// Check if username is already used
// Call external php file to get information about the username
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
}
});
// Other tests
}
My question is how can I make validateForm() return false from inside the $.ajax ?
Could I for instance declare a js variable before the Ajax part and set it with Ajax ?
I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...
Thanks a lot for your help!
To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.
Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.
You could make a synchronous ajax call, instead of an asynchronous, as you're doing now. This means that the Ajax call will complete before the next lines of code are executed.
To do so in jQuery, just add async: false to your request object:
var someVariable;
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
someVariable = "something";
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
},
async: false
});
alert(someVariable); // should alert 'something', as long as the ajax request was successful
In the php, if you print out JSON like:
echo json_encode(array("ko"=>"good"));
shows up as:
{
"ko":"good"
}
then in the function it would be
if(data.ko == "good"){
//do stuff
}
This is how I normally do it. You can get the variable by using the name you used in the JSON so you can have other things if you need.
If the goal is to check a username availability, how about checking it as or just after the username is typed in. For example you could either bind it to the keyUp event for keystrokes or the blur event for when you leave the text box.
This would mean that by the time the user gets to the submit button, that part of the form would already be validated.
The traditional solution here is to pass a callback function to validateRegistration which expects a boolean value. Have the Ajax function call the callback function when it completes.
The onsubmit handler expects a return value immeidately, so performing an asynchronous test within your submit event handler is a fairly unituitive way to do things. You should instead perform the test as soon as possible (e.g. as soon as the user enters a username) and then store the result of username validation in a global variable, which is later checked at submit time.
// global variable indicating that all is clear for submission
shouldSubmit = false;
// run this when the user enters an name, e.g. onkeyup or onchange on the username field
function validateRegistration(callback) {
shouldSubmit = false;
// number of ajax calls should be minimized
// so do all other checks first
if(username.length < 3) {
callback(false);
} else if(username.indexOf("spam") != -1) {
callback(false)
} else {
$.ajax({
....
success: function() {
if(data == "ko") {
callback(false);
} else {
callback(true);
}
}
});
}
}
Now call validateRegistration with a function argument:
validateRegistration(function(result) {
alert("username valid? " + result);
if(result) {
$("#username").addClass("valid-checkmark");
} else {
$("#username").addClass("invalid-xmark");
}
shouldSubmit = result;
});
Now use the global variable shouldSubmit in your form's submit event handler to optionally block form submission.
i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance
Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.
In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)