jQuery is not redirecting after AJAX call - php

I'm validating a form using jQuery and against a database using PHP-MySQL. The AJAX call is successful but the current page(A) is not redirected to page(B) after successful validation. But if i refresh the page, the page(B) is loaded. That is, the call is successful but jQuery is not redirecting.
<script language="javascript">
$(document).ready(function()
{
$("#login_form").submit(function()
{
//remove all the class add the messagebox classes and start fading
$("#msg").text('Checking....').fadeIn(1000);
//check the username exists or not from ajax
$.post("signin_check.php",{ loginid:$('#username').val(),pswd:$('#password').val() }, function(data)
{
if(data=='yes') //if correct login detail
{
$("#msg").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).text('Logging in.....').fadeTo(900,1,
function(){
//redirect to secure page
document.location = "/pawn/selectdomain.php";
});
});
}
else
{
$("#msg").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).text('Incorrect login details !!').fadeTo(900,1);
});
}
});
return false; //not to post the form physically
});
//now call the ajax also focus move from
$("#password").blur(function()
{
$("#login_form").trigger('submit');
});
});
</script>
I also tried replacing document.location with window.location and window.location.href and window.location.replace(....) but even they dont work. Someone please help.

the problem must be one of these 2 or both:
1) The data that ajax returns is not equal to 'yes'
2)ajax is not successful and it has error
please check that if the ajax is successful and then return value is equal to 'yes'

Related

Refresh and show div which existing in other file in jquery

I want that whenever my twilio call disconnects, the page should refresh itself automatically and a div that exists in different file should open. Here is my code
Twilio.Device.disconnect(function (conn) {
window.location.reload();
$('.dhxwin_active').show();
});
I think it is possible using querystring URL Like:
Twilio.Device.disconnect(function (conn) {
window.location = window.location.href + "?r=refresh"; // Get the URL Paramerter "r" according your requirement.
window.location.reload();
});
When page refresh you have got "r" value for URL
var refresh = '<?php echo $_REQUEST['r'] ;?>';
if(refresh == 'refresh') {
$('.dhxwin_active').show();
}
Please correct me if i am wrong

jquery validation and changing of div content

I am having name, email in content of a html page. i have to validate it on clicking continue button. and also the content in the content div has to change. how can i do both on clicking the continue button. help me with some suggestions. thanks.
am using the following code for changing div content.
<script>
$(document).ready(function () {
$("#button").click(function () {
$("#content").load("<?php echo base_url().'survey/categories' ?>");
});
});
$(document).ready(function () {
$("#button1").click(function () {
$("#content").load("<?php echo base_url().'survey/budget_overview' ?>");
});
});
</script>
As i understand your question, i think what you want is to do the two tasks at the same time on click of the button. So here's some sample code assuming this is what you want. If you have any doubts just ask. And i have added just sample Email Validation Using RegExp in JavaSript at the end of the code as a function.. Get the idea, Hope this helped you,,
//
$(document).ready(function() {
//Button1 Click
$("button").click(function(){
//initialize inputs here
var email =$("#email").val;
var input1=$("#input1").val;
//Validate Inputs Here
if(IsEmail(email)==true && input1!=""){
return true
}
else{
return false;
}
//Loading the first content after validating inputs
$("#content").load("<?php echo base_url().'survey/categories' ?>");
//To Trigger the other button
$('#button1').trigger('click');
});
//Button1 Trigger Will fire Click event
$("#button1").click(function () {
$("#content").load("<?php echo base_url().'survey/budget_overview' ?>");
});
});
//Email Validation In JavaScript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
I think the problem is with your syntax. You have to specify a file URL in the load method like this:
$(document).ready(function(){
$("form").submit(function(){
$("#content").load("myfile.php");
return false;
});
});
You can have a look on the load documentation.

Javascript HTML button click not working

I've created a login system using HTML, JavaScript, Ajax and PHP.
I'm trying to implement the log out function now, here's what I have:
First there is a div in my html, which says welcome to anyone on the site not logged in:
<div id="welcome" style="postion:absolute; top:0; float:right;">Welcome to SIK!!!!</div>
I then have a JavaScript function which is called when a user is logged in or registered to amend the div to say hi to the specific user, and show a log out button.
function show_logged_in(success)
{
var is_logged_in = success;
var dataString = {"reg":invalid, "login":invalid,"is_logged_in":is_logged_in};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data:dataString,
dataType:'JSON',
success: function(username) {
alert("User is shown");
user = username;
$('#welcome').html('<p>Hi ' + user + '</p><p><button id="logout_but"
type="button">Log Out</button></p>');
},
error: function() {
alert("ERROR in show_logged_in");
}
});
}
And then when the user clicks logout, in my main js file there is a function:
$("#logout_but").click(ui.logout);
here is my main js file altogether:
$(document).ready(function(){
//----------Login/Register Gui --------------
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//create new instance of gui class
var ui = new Gui();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
$("#logout_but").click(ui.logout);
});
So now you can see the order of the calls, and also the click function that is called for the logout button is:
this.logout = function() {
alert("clicked");
var dataString = {"is_logged_out":invalid};
$.ajax({
type:"POST",
url:"PHP/class.logout.php",
data:dataString,
dataType:'JSON',
success: function(success){
alert("User is logged out");
$('#welcome').html('<p>Welcome to SIK</p>');
},
error: function() {
alert('ERROR in log out');
}
})
}
As you can see I have and alert at the top of the last function I posted to show me if the function is actually being called.
My problem is when I click the logout button nothing happens. I also don't see the alert, thus the problem is occurring on the click.
Any help with this situation would be great.
That's because you create the logout button dynamically and AFTER the click handler is trying to attach itself to the element in your main js file. As a result, the handler doesn't find the #logout_but element and therefore doesn't attach to anything.
To fix that, you could use a delegate instead of a click handler:
Replace this:
$("#logout_but").click(ui.logout);
with
$("#welcome").on("click", "#logout_but", ui.logout);

How to stop jQuery post page refresh

I am getting data from an MySQL database through PHP. I am sending the and getting the data from PHP using jQuery. Here is the code.
$.POST("SubmitCode.php", $("#questionCodeForm").serialize(),'json').done(function(data) {});
Now the problem is that once I send this data the page refreshes. How can I stop the page refresh. If I delete 'json' then the page stops refreshing but the problem is that I want to get the json data without page refresh. How can I do this?
-------------------------------------------after edit-----------------------------------------------------------------------------
Here is the updated code
$(document).ready(function() {
initialization();
codeSubmission();
});
function initialization() {
$("#answerForm").hide();
}
function codeSubmission() {
$("#submitButton").click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize()).done(function(data) {
var questionName = data.questionName,
options = data.options,
pollingStatus = data.pollingStatus,
codeExist = data.codeExist;
alert(data);
alert(data[1]);
alert(questionName);
alert(options);
if(codeExist == true) {
$("#questionTitle").text("questionName");
for(rowNum=1;rowNum<=5;rowNum++) {
$("#checkbox-"+rowNum).val("Answer1");
$("#checkbox"+rowNum+"label").text("Answer"+rowNum);
}
$("#answerForm").slideDown(500);
} else if(codeExist == false) {
alert("This quiz code is invalid");
}
},'json');
//return false;
});
//return false;
}
Now the problem is that the output of alert(questionName) is undefined. The data is passed as a string. How do I get the correct information in the correct variables?
Try this instead: (note the placement of the callback function, and lowercase .post method)
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
Also make sure that whatever is triggering the post isn't an actual link and if it is, you need to stop the default action from occuring. For example:
Click here to submit
javascript:
$(a).click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
});
You also have to parse the json on the client side. You can do this using
obj = jQuery.parseJSON(data);

Using ajax, jQuery and php together for real-time form validation

Okay, so I have a form that a user will fill out, these are the username field, and a color verification field. The username field automatically checks my database when the focus is changed to alert the user whether they're username is taken or not. The color verification field compares the color of the image displayed on screen to the color the user enters. If both of these fields are completed successfully, the button to register is displayed. This is the jQuery I am using
$(document).ready(function()
{
$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox2").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("checkusername.php",{ username:$(this).val() } ,function(data)
{
if(data=='no') //if username not avaiable
{
$("#msgbox2").fadeTo(200,0.1,function() //start fading the messagebox
{//alert(data);
//add message and change the class of the box and start fading
$(this).html('Your username was taken<? $_SESSION['test2'] = 0; ?>').addClass('messageboxerror') .fadeTo(900,1);
});
}
else
{
$("#msgbox2").fadeTo(200,0.1,function() //start fading the messagebox
{ //alert(data);
//add message and change the class of the box and start fading
$(this).html('User name is available!<? $_SESSION['test2'] = 1; ?>').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
The php file for the above code is:
session_start();
require("../db.php");
$username = $_POST['username'];
$sql ="SELECT * FROM user WHERE username = '$username'";
$go = mysql_query($sql,$db);
$numrows = mysql_num_rows($go);
if ($numrows) {
// no
echo("no");
} else {
// yes
echo "yes";
}
The second field for color is set up the same:
$(document).ready(function()
{
$("#color").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the color is right or not
$.post("checkcolor.php",{ color:$(this).val() } ,function(data)
{
if(data=='no') //if color is incorrect
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{//alert(data);
//add message and change the class of the box and start fading
$(this).html('Your color was incorrect<? $_SESSION['test1'] = 0; ?>').addClass('messageboxerror') .fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{ //alert(data);
//add message and change the class of the box and start fading
$(this).html('Verification Successful<? $_SESSION['test1'] = 1; ?>').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
The php file for the above code is:
session_start();
$sescolor= $_SESSION['color'];
$usercolor = $_POST['color'];
$_SESSION['usercolor']= $_POST['color'];
$usercolor = strtoupper($usercolor);
if ($sescolor==$usercolor) {
echo("yes");
} else {
echo "no";
}
What I wanted to happen was for the two fields "username" and "color" to change the session variables of 'test1' and 'test2' based on they're state. So if username was invalid, test2 would be assigned a 0 instead of 1. Same for the color verification. Then the idea was that I would have a seperate function check to see if both 'test1' and 'test2' were 1. If so, the user would see the submit button, if not, they would see an error message.
This is what the "checkboth.php" would look like
$test1= $_SESSION['test1'];
$test2= $_SESSION['test2'];
echo $test1;
echo $test2;
if(($test1 ==1) && ($test2 ==1))
{
echo("yes");
}
else{
echo("no");
}
I am using the same jQuery structure for the third function. This works, however, I always get back 'yes'. Upon a var_dump of the session, I find test1 and test2 to always equal 0. How do I go about accomplishing this?
Thanks in advance!
I prefer ajax to post....after all, you're trying to do an asynchronous check of data without interrupting the UI experience. That's the "A" in ajax.
$.ajax({
url: "checkusername.php", //
timeout: 30000,
type: "POST",
data: data,
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
//do highlights
}
});
If you plan on using JSON as return data as I have shown, then you have to return json in your php doc. Right now, you've got it returning yes/no printed on the page, which would work if you specified your callback type as text. Otherwise, using your method it's just going to get confused.
As to your color verification, I'd "stack" it in the success of the first as you can't have it happen until after the username is checked.
Why not use beautiful jquery validation plugin? It has remote validation method.

Categories