I have a form that uses Ajax for client-side verification. The end of the form is the following:
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
EDIT: this is my mail3.php file dealing with errors:
$errors=null;
if ( ($name == "Name") ) {
$errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
$errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
$errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
$errors .= $spamError; // spam error
}
if ( !($errors) ) {
mail ($to, $subject, $message, $headers);
//header ("Location: thankyou.html");
echo "Your message was successfully sent!";
//instead of echoing this message, I want a page redirect to thankyou.html
} else {
echo "<p id='errors'>";
echo $errors;
echo "</p>";
}
I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?
Thanks!
Amit
Sure. Just put something at the the end of your success function like:
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
where your server returns the response no_errors when there are no errors present.
Just do some error checking, and if everything passes then set window.location to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
You can just redirect in your success handler, like this:
window.location.href = "thankyou.php";
Or since you're displaying results, wait a few seconds, for example this would wait 2 seconds:
setTimeout(function() {
window.location.href = "thankyou.php";
}, 2000);
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
}
});
In your mail3.php file you should trap errors in a try {} catch {}
try {
/*code here for email*/
} catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
}
Then in your success call you wont have to worry about your errors, because it will never return as a success.
and you can use: window.location.href = "thankyou.php"; inside your success function like Nick stated.
I posted the exact situation on a different thread. Re-post.
Excuse me, This is not an answer to the question posted above.
But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.
Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?
In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...
Just my 2 cents. :)
I think you can do that with:
window.location = "your_url";
I suppose you could attack this in two ways;
1) insert window.location = 'http://www.yourdomain.com into the success function.
2) Use a further ajax call an inject this into an element on your page, further info on which you can find in the jQuery docs at http://api.jquery.com/jQuery.get/
Another option is:
window.location.replace("your_url")
Related
The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure
This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});
I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id,
userId: userId},
success:function(data){
if(data.success){
$(".newCommentForm" +id).replaceWith("<span id='" + id + "' class='limitedText'>" + newComment + "</span>");
$(thisId).data("PinComment", newComment);
}
else { alert('error');},
error:function(){
alert('error');
}
});
}
external file (i have added the return arrays here):
public function editComment(){
$userId = Input::get('userId');
if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){
$id = Input::get('id');
$newComment = Input::get('newComment');
DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
return array('success' => true);
} else {
return array('success' => false);
}
}
You have a typo here else { alert('error');},, you need another closing brace to close the success function.
You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery
Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');
I use ajax, php to insert data into mysql database. However after finished executing all queries, it doesn't do anything. I mean, when I click submit button in the form, as a user I don't see anything happening even though I set my Ajax function to alert the data. But in the backend all data are inserted properly into the database.
So, I'm not sure how to notify user of a successful form submission. Could anyone help please? Thank you in advance.
I referred here, but it doesn't help:Page redirect with successful Ajax request
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
}
catch(E)
{
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
//Ajax function for some other element before submitting form
function sendtobox(param,param2)
{
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('boxA');
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
}
}
}
xmlhttp.open("GET","getsubjects.php?q="+param+"&r="+param2,true);
xmlhttp.send();
}
//Ajax after submit button clicked
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data["json"] );
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
window.location='tutor-profile.php'
//header('Location:tutor-profile.php');
}
});
return false;
});
});
</script>
response.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include('inc/config.php');
$return = $_POST;
//$return ='{"slider1":"150","level":{"Upper Secondary":"2"},"sub":{"8":""},"rate2":{"7":"89","8":"150","9":"150","10":"150","11":"150","12":"150","13":"150","14":"150"},"a_end":"on","e_week":"on","e_end":"on","name":"ting1","phone":"098-098-0980","email":"ting1#Gmail.com","postcode":"56547","gender":"on","password":"nk","action":"test"}';
$return["json"] = json_encode($return);
// json_encode($return);
//
//below code to store in database
$data = json_decode($return["json"], true);
//var_dump($data); // Dump all data of the Array
>>>>>>INSERT QUERIES GO HERE>>>>>>>>>>>>>>>>
echo"form submitted ";
}
The code for redirect to another page in Javascript is
window.location.href ='tutor-profile.php'
Anyway they do not understand your previous roles and XMLHttpRequest your statements, that is ajax, but you simplify everything using only the last function $.ajax of jQuery.
The other correction is that you're saying that the server response will be of type "Json" but you just give back a string through a miss. What you can do is change it to this:
exit( json_encode( array('response'=>'put your text here') ) );
And then in JS instead of
$(".the-return").html("<br />JSON: " + data["json"] );
place this:
$(".the-return").html("<br />JSON: " + data.response );
I have a section of code I am using to check if the desired username is available using a jQuery AJAX call:
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail ); );
}
}, error: function() {
// Not sure what to put here...
}
});
}
The script works as expected -- I check the MySQL database on _check_username.php, and I successfully return a "pass" if the name's available, or "fail" if the name is already taken, and store it in the JS variable does_it_pass_or_fail.
However, regardless of whether does_it_pass_or_fail contains "pass" or "fail", I ONLY get the response "That username is available!"
So, the AJAX / PHP / MySQL portion seems to be working fine, but this simple JavaScript if statement has me stumped!
try using this:you had some syntax error in your code close to alert.try logging error also.
function check_username()
{
// Set user_name to the current value of input #new_user_name
var user_name = document.getElementById('new_user_name').value;
// Ajax to check availability of username
$.ajax({
url: '_check_username.php',
type: 'post',
data: { 'user_name': user_name },
success: function(data) {
var does_it_pass_or_fail = data;
console.log(data);
if ( does_it_pass_or_fail === "fail" )
{
alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail );
}
else
{
alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail );
}
}, error: function(erro) {
console.log(error);
}
});
}
Use firebug to debug the ajax request.
place
console.log(data);
in the success function.
success: function(data) {
console.log(data)
}
This may help you in debugging your ajax issues.
Thank you all for leading me in the direction of further inspecting the AJAX call.
As it turns out, my '_check_username.php' script was returning a newline before returning "pass" or "fail" -- so, naturally, "\npass" is a different string than "pass". Once I realized this I was able to repair the script.
Here's a link i saw but still confused over the answers provided for them : jQuery Ajax returns the whole page
My situation is something similar.
I have a index.php that calls for a popup login form, that tries to submit this login information to a ajax call to another php called login_check.php.
This is my index.php :
var dataString = 'email='+ email.val() + '&password=' + password.val();
$.ajax({
type: "POST",
url: "login_check.php",
data: dataString,
cache: false,
error: function (request, status, error) {
alert("An error occured while trying to complete your request: " + error);
},
success: function(data)
{
alert(data);
}
});
This is what is in my login_check.php :
session_start();
//input from login form
$myemail = htmlspecialchars(trim($_POST['email']));
$mypassword = htmlspecialchars(trim($_POST['password']));
//selecting from database to check user account
$sql="SELECT * FROM user WHERE email='$myemail' and password='$mypassword'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$count=mysql_num_rows($result);
//If result matched $myemail and $mypassword, table row must be 1 row
if($count==1)
{
echo 'true';
session_register("myemail");
$_SESSION['login_user']=$myemail;
}
else if($count==0)
{
echo 'false';
}
And the output of the alert box is the full html of the page i am currently in, i.e. index.php.
And i have no idea whyy. ):
Same happen here, I figured it out it has a conflict with other plugin, deactivate your plugin and it should works.
Hope it helps on other looking for this solution.
You might also want to try this syntax of making an Ajax POST request.
$.post('login_check.php',{'email':email.val(),'password':password.val()},function(response){
alert(response);
},"json");
No clue whether this solves your problem, but it's always a good idea to encode the data:
var dataString = encodeURIComponent('email='+ email.val() + '&password=' + password.val());
Maybe this solves your problem, too...