I have a login form which I currently use AJAX to display the error messages from my login.php script, e.g. "incorrect email", onto a div in my login form on my index.php rather than loading a new page with the errors on them.
However when the details are correct and the login is successful, it also displays the entire successful page location onto that div inside my login form too. I don't know how to fix this, I have tried an if statement to say if it is successful load a new location, but still doesn't work. Here is my AJAX for my login form:
$("#login_button").click(function() {
$.post($("#login_form").attr("action"),
$("#login_form :input").serializeArray(),
function(info) {
if (info.status != null) {
header('Location: home.php');
} else {
$("#login_errors").html(info)
};
});
// Prevent the default action from occurring.
return false;
});
Does anybody know how to fix this issue?
Going wrong with this line header('Location: home.php');, this is a PHP statement which you are trying to use under JS.
you could use, window.location = "home.php"; to redirect under JS.
Another thing what i believe is faulty
the callback function expects two parameters,
the content what you return on your action script.
the status of posted form
change function(info) { to function(info, status) {
and use under you if statement, something like this if (status!="success") {
know more about post in JS : http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Related
I have an HTML form. I am already doing a client side HTML.
<form id='myForm' onsubmit='return myFormValidation()'>
...
</form>
Now, in myFormValidation function, after making sure the client side is OK, before really submitting the form, I want to do also a server side form validation.
I am using JQuery. So,I changed my function to something like this:
function myFormValidation(){
//first, client side validation
...
//then, server side validation
$.post(url_of_server_side, $("#myform").serialize(), function(json) {
data = JSON.parse(json);
if(!data.ok)
{
$("#msg").text("some error");
}
else
{
$("#myForm").submit();//Oops!
}
});
return false;
}
But the "submit" function of form behaves like a recursive function and tries to validate the form again!
Should I disable the validation function before calling submit? Or, I guess, there is a better way for my problem (which is slightly or even totally different than this)?
If you need server side validation you should extend your "Save" enpoint to support correct response status codes and do not use separate "Validation" url. Use single url with different response types:
200 (Success) - data was saved successfully
400 (Bad request) - input data was incorrect. As response message you can include "validation result" message which you will display to user.
So your code can looks like
$.post(url_of_server_side, $("#myform").serialize())
.done(function() {
//show some success confirmation or redirect to main page
}).fail(function(xhr, status, error) {
$("#msg").text(error.message);
});
I would suggest, if all data is OK, the server-side script to perform the action that you want, e.g. saving to database. That way, you will not need a second post of the form in case everything is correct.
If something is wrong, then obviously, the checks must take place the second time as well.
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
I am creating a login page in PHP. On entering wrong username/password I am showing a javascript alert box. I now want to navigate user back to login page on clicking "OK" button of alert box . Am using "header(location:url)", but then javascript code is not working.
Is there any other way to do this.
You can try this
echo "<script language='javascript' type='text/javascript'>alert('error');
</script>";
echo "<meta http-equiv='refresh' content='1; URL=login.php'>";
For JS redirect, try;
window.location.href="http://url";
Hope this helps :)
Put this code in the login error page ..
<script>
alert('Wrong Username/Password');
window.location = "http://www.google.com";
</script>
But if you are familiar with jquery i advice you to do the login process with ajax request and show the notifications in the same page instead of navigating back and forth.
If you need i can create a simple one in plnkr
For the js redirect, u can use
window.location.href='http://whereEver';
Note: Username/ password validations are server side. Assuming its an ajax call, after you get the validation results, instead of triggering an alert, have a div in the page itself where you can inject the server response. Alerting looks unprofessional.
Better approach would be something like
HTML
<div class="response"></div>
CSS
.response {
display:none;
}
.error {
color: red; // find a better color
}
PHP
On validation failure, have a variable, lets call it status and make it false.
The validation response can be something like,
$response = ['status' => false, 'message' => 'Username / password mismatch'];
Then send back the results
die(json_encode($response));
Note: If you are using PHP < 5.4, use
$response = array('status' => false, 'message' => 'Username / password mismatch');
JS
$.ajax({
url: 'url-to-post',
type: 'POST',
data: $('form[name="your-form-name"]').serialize(),
dataType: 'json',
success: function(data) {
if (!data.status) {
// inject into response
$('.response').addClass('error').html(data.message).show();
}
else
{
// redirect them to home page, i assume
window.location.href = '/home';
}
}
});
I am pretty new to html5 web development
I have created a page with login and password on it and have a submit button.
On submit , I send a rest request to the server which has a url
THE RRQUEST IS SOMETHING LIKE THIS
<USERNAME>
abc
</USERNAME>
<PASSWORD>loooik
</PASSWORD>
which is in js file as var data...
This request is set as
var parameters=JSON.stringify(data);
I use the following code for establishing connection
xmlHttp.open("post",url,true);
XmlHttp.setRequestHeader("Content-type","application/json);
xmlHttp.send(parameters);
xmlHttp.onreadystatechange=function X()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
return true;
}
I need to add a loading element and want to display the next screen between request and the response. How can I achieve it?
In tag I have used submit input type where onClick attribute calls return sendPost() method which has the request to be called
How should I proceed for the same... having loading screen and getting the response ... suppose just the name to be displayed on next html screen
First of all see basic jQuery example. This will guide you through how jQuery works and help a lot in the solution I'm going to suggest.
http://learn.jquery.com/about-jquery/how-jquery-works/
jQuery has it's own AJAX method and further shorthand called $.post
Now you can write something like this -
function requestNetwork() {
// Code for loading screen
$.ajax({
url: "yourURL",
data: "yourData"
}).done(function(data) {
alert(xmlHttp.responseText);
// Code for dismissing loading screen
}).fail(function(data) {
// Code when call fails
}).always(function() {
// This code will always run
});
}
I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
var proceed = false;
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
proceed = true;
} else {
alert("Error: " + response);
proceed = false;
}
});
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return proceed; //breakpoint here makes the code run
});
});
The code is adapted from a WPSE question, which originally didn't work for me as the form didn't get submitted. I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. If there are errors, the alert is issued without a problem.
What is the best way to handle this?
EDIT
Based on #Linus answer below, the following code works with both valid and invalid data:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
if(jQuery(this).data("valid")) {
return true;
}
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
jQuery("#post").data("valid", true).submit();
} else {
alert("Error: " + response);
jQuery("#post").data("valid", false);
}
//hide loading icon, return Publish button to normal
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
});
return false;
});
});
Short answer: You can't - not in this manner.
Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.
So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.
This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.
EDIT:
Another way would be to set an attribute on your form, say valid, and in your submit handler check that:
jQuery("#post").submit(function() {
if($(this).data("valid")) {
return true;
}
// Rest of your code
});
And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:
$("#post").data("valid", true).submit();
EDIT:
You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.
Bind your button to a validation function instead of submit. If it passes validation, call submit().
Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. Set up your callbacks and go....
The real question is - why are you doing validation server-side? Why can't you load in the validation criteria before - as the post is being written? Then your validation can happen real-time and not on-submit.
jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out.
$.ajax({
type: 'POST',
url: ajaxurl,
async:false,
data: data,
timeout:3000,
success: function(){
}
});