0

I am throwing all data from one page to another page via AJAX and also my table in MySQL is getting all data which I am sending. This means that just one line before header(), all my code is fine but my header does not redirect to the page. However I tried the Javascript window.location as well. I personally prefer header because if someone disables Javascript windows.location doesn't work. I think this is why I am using the header method.

The code I've written is below. I will appreciate if someone can help me.

if(isset($_POST['recaptcha'])){
    $secret = "something";
    $response = $_POST['recaptcha'];
    $remoteip = $_SERVER['REMOTE_ADDR'];
    $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
    $content = json_decode($url, TRUE);
    if($content['success'] ==1){
        function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
        }
        $fname = test_input($_POST["fname"]);
        $lname = test_input($_POST["lname"]);
        $email = test_input($_POST["email"]);
        $cname = test_input($_POST["cname"]);
        $discount = test_input($_POST["discount"]);
        $website = test_input($_POST["website"]);
        $address = test_input($_POST["address"]);
        $desc = test_input($_POST["desc"]);
        $expirydate = test_input($_POST["expirydate"]);
        $servername = "localhost";
        $username = "user";
        $password = "something";
        try {
        $conn = new PDO("mysql:host=$servername;dbname=something", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query = "INSERT INTO table(firstname, lastname, email, companyname, discountoffer, websitename, companyaddress, description, expirydate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $statement = $conn->prepare($query);
        $statement->execute(
            array(
            $fname,
            $lname,
            $email,
            $cname,
            $discount,
            $website,
            $address,
            $desc,
            $expirydate
            ) );
            $conn = null;
            header("Location: http://somethingpage.com/");
            exit;
        }
        catch(PDOException $e)
        {
            echo "Connection failed: " . $e->getMessage();
        }
        exit;
    }
    if($content['success'] !=1){
        echo "notok";
        exit;
        $conn = null;
    }
}

here is AJAX working from here i am sending all "form" data to above page through ajax it is also working fine because if i don't do recaptcha it returns the error and my html block gets render on screen which means my last block also executes fine. Here is code for ajax

"use strict";
        $(document).ready(function(){
            var fname;
            var fnameerr;
            var lname;
            var lnameerr;
            var email;
            var emailerr;
            var cname;
            var cnameerr;
            var discount;
            var discounterr;
            var website;
            var websiteerr;
            var address;
            var addresserr;
            var expirydate;
            var expirydateerr;
            var desc;
            var descerr;
            var recaptcha;
            var recaptchaerr;
            var errbox
            var errcontent
            function showerror(errbox, errcontent){
                if($(errbox).hasClass("hidden")){
                    $(errbox).removeClass("hidden");
                    $(errbox).html(errcontent);
                }
            }
            function hideerror(errbox, errcontent){
                if(!$(errbox).hasClass("hidden")){
                    $(errbox).html(errcontent);
                    $(errbox).addClass("hidden");
                }
            }
            var alphabets = /^[a-zA-Z.,]*$/;
            $("#fname").keyup(function(){
                fname = $('#fname').val();
                if(!alphabets.test(fname)){
                    errbox = $("#fnameerrbox");
                    errcontent = "Only alphabets are allowed in name field";
                    showerror(errbox, errcontent);
                }
                if(alphabets.test(fname)){
                            errbox = $("#fnameerrbox");
                            errcontent = "";
                            hideerror(errbox, errcontent);
                            fnameerr = "no";
                        }
            });
            $("#lname").keyup(function(){
                lname = $('#lname').val();
                if(!alphabets.test(lname)){
                    errbox = $("#lnameerrbox");
                    errcontent = "Only alphabets are allowed in name field";
                    showerror(errbox, errcontent);
                }
                if(alphabets.test(lname)){
                    errbox = $("#lnameerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    lnameerr = "no";
                }
            });
            var emailfilter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            $("#email").focusout(function(){
                email = $('#email').val();
                if(!emailfilter.test(email)){
                    errbox = $("#emailerrbox");
                    errcontent = "invalid email";
                    showerror(errbox, errcontent);
                    $("#email").focus();
                    keepcheckingemail();
                }
                if(emailfilter.test(email)){
                    errbox = $("#emailerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    emailerr = "no";
                }
            });
            function keepcheckingemail(){
                $("#email").keyup(function(){
                    email = $('#email').val();
                    if(!emailfilter.test(email)){
                        errbox = $("#emailerrbox");
                        errcontent = "invalid email";
                        showerror(errbox, errcontent);
                    }
                    if(emailfilter.test(email)){
                        errbox = $("#emailerrbox");
                        errcontent = "";
                        hideerror(errbox, errcontent);
                        emailerr = "no";
                    }
                });
            }
            var alphanumeric = /^[a-zA-Z 0-9.,]*$/;
            $("#cname").keyup(function(){
                cname = $('#cname').val();
                if(!alphanumeric.test(cname)){
                    errbox = $("#cnameerrbox");
                    errcontent = "Only alphabets & numbers are allowed in company name field";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(cname)){
                    errbox = $("#cnameerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    cnameerr = "no";
                }
            });
            var dis = /^[a-zA-Z 0-9.,%]*$/;
            $("#discount").keyup(function(){
                discount = $('#discount').val();
                if(!dis.test(discount)){
                    errbox = $("#dnameerrbox");
                    errcontent = "Only alphabets, numbers & % are allowed in company name field";
                    showerror(errbox, errcontent);
                }
                if(dis.test(discount)){
                    errbox = $("#dnameerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    discounterr = "no";
                }
            });
            $("#website").keyup(function(){
                website = $('#website').val();
                if(!alphanumeric.test(website)){
                    errbox = $("#weberrbox");
                    errcontent = "https not allowed. write, for ex. homesolver.ca OR www.homesolver.ca";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(website)){
                    errbox = $("#weberrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    websiteerr = "no";
                }
            });
            $("#address").keyup(function(){
                address = $('#address').val();
                if(!alphanumeric.test(address)){
                    errbox = $("#adderrbox");
                    errcontent = "Only alphabets & numbers are allowed in company address field";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(address)){
                    errbox = $("#adderrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    addresserr = "no";
                }
            });
            var todaydate = new Date();
                $("#expirydate").datepicker({
                    autoclose: true,  
                    format: "yyyy/mm/dd",
                    startDate: todaydate
                });
                $("#expirydate").change(function () {
                    expirydate = $("#expirydate").val();
                    expirydateerr = "no";
                });
            $("#desc").keyup(function(){
                desc = $('#desc').val();
                if(!alphanumeric.test(desc)){
                    errbox = $("#deserrbox");
                    errcontent = "Only alphabets & numbers are allowed in description field";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(desc)){
                    errbox = $("#deserrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    descerr = "no";
                }
            });
            $("#promotionsubmit").click(function(){
                if((descerr !="no") || (expirydateerr !="no") || (addresserr !="no") || (discounterr!="no") || (cnameerr!="no") || (emailerr !="no") || (lnameerr !="no") || (fnameerr !="no")){
                    errbox = $("#robotError");
                    errcontent = "All * fields are mendatory";
                    showerror(errbox, errcontent);
                }
                if((descerr == "no") && (expirydateerr =="no") && (addresserr =="no") && (discounterr =="no") && (cnameerr =="no") && (emailerr =="no") && (lnameerr =="no") && (fnameerr =="no")){
                    errbox = $("#robotError");
                    errcontent = " ";
                    hideerror(errbox, errcontent);
                $.ajax({
                    url:"somepage.php",
                    method:"POST",
                    data:{recaptcha: grecaptcha.getResponse(), fname:fname, lname:lname, email:email, cname:cname, discount:discount, address:address, desc:desc, website:website, expirydate: expirydate},
                    success: function(data){
                        $data = data;
                        if(data == "notok"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "please verify you are not robot";
                            showerror(errbox, errcontent);
                        }
                    }
                    });
                }
            });
    });
3
  • if this is your ajax script then try returning some thing from here and catch and handle that returned value from the main page ( from which you are calling this ajax script ). Commented Dec 15, 2017 at 6:35
  • i am posting all ajax working in question. just to let you know from "form" means that from ajax i am sending all data here which i have posted already and from here i want to redirect. kindly please see question again thanks Commented Dec 15, 2017 at 6:38
  • 2
    exactly so this is your ajax script , When you call a PHP Script in AJAX, the request is being executed by the AJAX call and not the current page the client is on, therefore it won't change the headers on the page that is actually being viewed Commented Dec 15, 2017 at 6:41

1 Answer 1

1

You can not use header() to redirect user directly from your ajax script.

When you call a PHP Script in AJAX, the request is being executed by the AJAX call and not the current page the client is on, therefore it won't change the headers on the page that is actually being viewed.

So you need to handle the response from your ajax in your success callback function. and then redirect user from there

                    $.ajax({
                    url:"somepage.php",
                    method:"POST",
                    data:{recaptcha: grecaptcha.getResponse(), fname:fname, lname:lname, email:email, cname:cname, discount:discount, address:address, desc:desc, website:website, expirydate: expirydate},
                    success: function(data){
                        $data = data;
                        if(data == "ok"){
                            window.location='someotherpage.php'; //redirect user from here
                        }
                    }
                    });

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

what if client side browser disables the javascript? does it work ?
Ajax requests and jQuery will not work when the client has JavaScript disabled.
thanks. so what is better solution for this? as i have noticed after ajax called i can not redirect from php page and if javascript is also disabled then how can i redirect ? I ll appreciate if you can help me
you need to code your web application in a way that can handle both scenario. read more about "graceful degradation"
Or progressive enhancements? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.