Redirect page or do other tasks - Ajax, PHP and jQuery

Hi E's, I need to do some changes in one solution that I get some mouths ago.
In that solution I have a page (index.php) that send via $Post variables to the file (ajax_processar.php), and depend what the value of the variable the system redirect the index.php to other page.
This is the question where I have the solution for what I say above (http://rdsrc.us/3qnt7G).
This is the code:
//index.php:::::

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="../../ficheiros_apoio/jquery.min.js"></script>
</head>
<body> 

<script>
$.post("ajax_processar.php",{
        "redirect":"1"
    },function(data, textStatus, jqXHR){
        // redirect
        window.location=data;    
    });
</script>
</body>
</html>

Open in new window

//ajax_processar.php::::

 <?php
$x = $_POST['redirect'];
if($x == 1){
     echo "http://www.google.com";
}
if($x == 2){
     echo "../orgohereinstead.php";
}
if($x == 3){
     echo "redirecthere.php";
}
?> 

Open in new window


The solution above work perfect if the only goal was redirect always index.php to other page.
The problem now is, I need to do more things then redirect page. I try to erase the the urls in ajax_processar.php, but the script in this way do a infinite cycle.

In practice what I need is:
<?php
$x = $_POST['redirect'];

if($x == 1){
     echo "otherpage.php";
}

if($x == 2){
     //send something to the data base
}

if($x == 3){
     //send a email to a costumer
}
?>

Open in new window


Like you can see, just if x==1 the page are redirect, if are 2 or 3 the script will write in db or send the email, but not do nothing in index.php.

What kind of changes I have to do in index.php and ajax_processar.php for the script do the tasks depending the variable that has been send?

The best regards, JC
LVL 3
Pedro ChagasWebmasterAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Lukasz ChmielewskiConnect With a Mentor Commented:
Try with this:

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
        $.ajax({
        type: "POST",
        url: "ajax_processar.php",
        data: {'redirect': '2'},
        success: function(dat){
                console.log('ajax is done');
                if(dat == "done"){
                        $('#n').text(dat);
                } else {
                // redirect
                window.location=dat;
                }  
        }
        });
}); 
</script>
</head>
<body> 
<div id="n"></div>

</body>
</html>

Open in new window


Changing the value 1/2/3
0
 
Lukasz ChmielewskiCommented:
Unless you do not echo anything from ajax_processar, you can do it like this:

<?php
$x = $_POST['redirect'];

if($x == 1){
     echo "otherpage.php";
}

if($x == 2){
     //send something to the data base
    // BUT DO NOT ECHO OR SEND HEADERS, DO YOUR STUFF IN THE DB, THEN:
     echo "otherpage.php";
}

if($x == 3){
     //send a email to a costumer
     // SEND, THEN:
     echo "otherpage.php";
}
?>
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, I don't tested yet your solution, but I suppose independently of the value of the variables, index.php will always reload/refresh or redirect?! But what I need is just reload/redirect if it is necessary or request.
Maybe what I want was impossible, maybe.

~JC
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
Lukasz ChmielewskiConnect With a Mentor Commented:
OK, now I think I get it,

 // redirect
        window.location=data; 

Open in new window


data is the thing returned from processar, so if you want the index to stay the way it is, you should add a condition in you javascript

if(data == "done"){
 // do nothing
}
else{
        // redirect
        window.location=data; 
}

Open in new window


Mind that the processar should return "done" (for example) if you do not want a redirection...

<?php
$x = $_POST['redirect'];

if($x == 1){
     echo "otherpage.php";
}

if($x == 2){
     //send something to the data base
    // BUT DO NOT ECHO OR SEND HEADERS, DO YOUR STUFF IN THE DB, THEN:
     echo "done";
}

if($x == 3){
     //send a email to a costumer
     // SEND, THEN:
     echo "done";
}
?>

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, I like your idea, but unefortenely still not work:
Let's review the code, maybe I dont something wrong:
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="../../ficheiros_apoio/jquery.min.js"></script>
</head>
<body> 

<script>
$.post("ajax_processar.php",{
        "redirect":"1"
    },function(data, textStatus, jqXHR){
        if(data == "done"){
        } else {
        // redirect
        window.location=data;
        }    
    });
</script>
</body>
</html>

Open in new window

ajax_processar.php
 <?php
$x = $_POST['redirect'];

if($x == 1){
     echo "http://www.google.com";
}

if($x == 2){
     echo "done";
}

if($x == 3){
     echo "done";
}
?> 

Open in new window


Maybe can be something wrong in the conditional "if", because the page are redirect to the page "done".
Can you check please.

~JC
0
 
mcnuteCommented:
Well if you send the ajax request alway with the { redirect: 1 } then always a redirect will be performed.

So the question is, when do you want the other tasks to be triggered?
You want the user to do something in order to make a email send or something is written in the database, because obviously, if your ajax request always sends along { redirect: 1 } the always the redirect will be performed regardless of the changes you've done so far to your
request code and the changes in ajax_processar.php.

So I could think of something like that. If the user fills out a newsletter subscription form, then the database will be filled with his email, then you ajax request should send along { redirect: 2 }, right?

It really depends on the interaction with index.php and the user how you trigger your tasks in ajax_processar.php.

Hope that cleared your mind a little bit. It is definitely possible to do.
0
 
Lukasz ChmielewskiCommented:
You send

$.post("ajax_processar.php",{
        "redirect":"1"

to processar... If you want other tasks to be performed, you should send 2 or 3.
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, first thanks you for the feedback.
I tested the solution with the 3 values possible in the variable (1,2,3), and the behavior is that I explain in my last post.
About what the script will do, send email, database etc, is just a example of what I will try to do, can be more things. Maybe not have solution for this problem.
Your idea with the variable data appear perfect and logic, but why not work?!
Can you test the solution, please copy the solution from my last post, change the path to the jquery file, and view the behavior. Also I try change == to === in the conditional if, but still not work.
Please help me to find a solution.

~JC
0
 
mcnuteCommented:
Try this solution with ajax_processar.php unchanged:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
        $.ajax({
        type: "POST",
        url: "ajax_processar.php",
        data: {'redirect': '2'},
        success: function(dat){
                console.log('ajax is done');
                if(dat == "done"){
                        $('#n').text(dat);
                } else {
                // redirect
                window.location=data;
                }  
        }
        });
}); 
</script>
</head>
<body> 
<div id="n"></div>

</body>
</html>

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, the new solution have now a new behavior, if the value was 2 or 3, they don't redirect the page, that was the goal. But now if he value was 1, the page not redirect!
I believe you are close to the best solution.
You have tested he solution? I made this question because I'm not in my office and I made the changes in my IPad!
Can you check please.

~JC
0
 
mcnuteConnect With a Mentor Commented:
Ohhps. The window.location=data must change to: window.location=dat.

Since data is a reserved keyword in javascript it is no good idea using it. So I changed that to dat and forgot changing it in the else block.

So take just this script and it will work:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
        $.ajax({
        type: "POST",
        url: "ajax_processar.php",
        data: {'redirect': '2'},
        success: function(dat){
                console.log('ajax is done');
                if(dat == "done"){
                        $('#n').text(dat);
                } else {
                // redirect
                window.location=dat;
                }  
        }
        });
}); 
</script>
</head>
<body> 
<div id="n"></div>

</body>
</html>

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, with the last solution we back to the initial problem, now the behavior is the same of the beginning.
Now independently of the value of the variable, in all cases the script reload index.php.
I do some change in ajax_processar.php, now I include a email for test:
 <?php

$x = $_POST['redirect'];

if($x == 1){
     echo "http://www.google.com";
}

if($x == 2){
mail("apple@xxxxxxx.xxx", "hello", "variable 2");
     echo "done";
}

if($x == 3){
     echo "done";
}

?> 

Open in new window

They send well the information because if I choose value 2 I receive the email, but the page is reloaded.
Maybe need a small change to the code.

~JC
0
 
mcnuteCommented:
You're doing an ajax request. This means that by its nature the actual page where the ajax request has been fired will not be reloaded/refreshed or redirected. In your case it is being redirected because the ajax_processar.php sends back googles url to your ajax success function which uses to perform a javascript redirect with window.location = dat;

If you want on all 3 parameters a redirection you must provide the url in your ajax_processar.php for all three not just for the first.
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @mcnute, the goal is just redirect if the value of the variable was 1, for the values 2 and 3 the script must perform other tasks and nor redirect the page index.php.
In your opinion you thing that is possible. @Roads_roads are close of a good solution, can you help us?

~JC
0
 
mcnuteCommented:
Your error of thouhgt lies in how you think ajax works. There is no redirection to index.php. It simply never is left. The ajax call is being executed in the back of the browser so to speak without leaving it.

What you want to acheive cannot be done with ajax. The simply use a form like this:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body> 
<div id="n"></div>
<form action="ajax_processar.php" method="post" >
        <input type="radio" value="1" name="redirect" >
        <input type="radio" value="2" name="redirect" >
        <input type="radio" value="3" name="redirect" >
        <input type="submit" value="sendtophp" >
</form>
</body>
</html>

Open in new window

With your ajax_processar.php like this:
<?php
ob_start();
$x = $_POST['redirect'];

if($x == 1){
     header('Location: http://www.google.com');
}

if($x == 2){
     // send email here
     echo 'Email send successful.';
}

if($x == 3){
     // do other stuff here
     echo "other stuff was successful";
}

Open in new window

0
 
mcnuteCommented:
There was an error in the html until now. I corrected this in the answer. Try it like this.
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @mcnute, I get this warning when chose the value 1:
Warning: Cannot modify header information - headers already sent by (output started at /home/pedro/public_html/biblioteca/tutoriais/1196/ajax_processar.php:1) in /home/pedro/public_html/biblioteca/tutoriais/1196/ajax_processar.php on line 6 //line 6 is the line of the function header.

Open in new window

Is better I mentalizing that not have solution for my problem. First because we try here lots of examples using ajax and neither work, I hope @Roads_Roads refine him solution.
Second, you can give me a solution, and that solution also not work and this solution is not quite what I'm looking for. Not work because if I chose 1 give the above warning and not redirect the page index.php to google. If I chose 2 or 3, the result will appear in the ajax_processar.php (also not should appear in index.php), when it should not. The only value in this case that can change the page index.php is "1", the other values (2,3) just do a hidden process (like write in db, send email, etc).

But I don't lost the hope, and I believe that a good solution will appear.
Thanks for both.

~JC
0
 
mcnuteCommented:
My solution above worked perfectly for me on my local server. No need to put you head in the sand. Header already sent error should have been fixed with the ob_start() on the second line of ajax_processar.php. Did you exactly use my solution? Or did you modified your existing one. I recommend you, to copy out the code off here and try again. If you made additional changings to your files then post them back here so we can check them out.
0
 
Lukasz ChmielewskiCommented:
Let's get back to the closest working solution, try to change this:

 <?php

$x = $_POST['redirect'];

if($x == 1){
     echo "http://www.google.com";
}
elseif($x == 2){
mail("apple@xxxxxxx.xxx", "hello", "variable 2");
     echo "done";
}
elseif($x == 3){
     echo "done";
}

?>
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @Roads_Roads, I want test the solution in your last post. But what version of index.php I shall use, the original (my first version)?

~JC
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @Roads_Roads, not work, the behaviors is:
1 - redirect to google site. OK
2 - Send the email but redirect index to 'gone'. KO
3 - redirect index to 'gone'. KO

In resume the last code I try is:
index.php
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
        $.ajax({
        type: "POST",
        url: "ajax_processar.php",
        data: {'redirect': '1'},
        success: function(dat){
                console.log('ajax is done');
                if(dat == "done"){
                        $('#n').text(dat);
                } else {
                // redirect
                window.location=dat;
                }  
        }
        });
}); 
</script>
</head>
<body> 
<div id="n"></div>

</body>
</html>

Open in new window

ajax_processar.php:
 <?php

$x = $_POST['redirect'];

if($x == 1){
     echo "http://www.google.com";
}
else if($x == 2){
mail("geral@xxxxxxxx.xxx", "hello", "variable 2");
     echo "done";
}
else if($x == 3){
     echo "done";
}

?>

Open in new window

The logic seems fine, but something does not work.

~JC
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi @mcnute. Your code work in my server too, the problem is what your code do.
Let me tell you what each value do in your example:
1 - Redirect to Google. OK
2 - Show the message "Email send successful.", when index.php should stay intact. KO
3 - The same of 2. KO

Other thing it is indispensable that the communication between both files done with the Ajax.

~JC
0
 
Lukasz ChmielewskiCommented:
The last code you posted works fine.
The ajax response does not redirect index.php to "done".
Look at those two pieces of code:

if(dat == "done"){
$('#n').text(dat);

Open in new window


<div id="n"></div>

Open in new window


When the response from processar equals "done", then the div with id="n" shows the message "done". It is not redirected, you can try it by switching this piece of code

if(dat == "done"){
   //$('#n').text(dat);
  alert("I am not redirected");
} else {
   // redirect
   window.location=dat;
}  

Open in new window

0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, have something here that I don't understand, there is you say the solution work. But for me still not work.
For there is no doubt I post some pictures, where you can see the code of index.php and ajax_processar.php. Also I attach a image with the result for each variable value. The only value that work fine was with the variable 1 (page redirect to Google, the others values all go to a page "done" (view the attach image).
Perhaps with the pictures you can see a mistake I am committing.

~JC
0
 
Pedro ChagasWebmasterAuthor Commented:
I forgot to attach the images. Here you go:
index.phpajax_processar.phpvalue:1value:2 and 3
~JC
0
 
Lukasz ChmielewskiConnect With a Mentor Commented:
1. Is there a whitespace in your processar file just before the <?php   ?
2. try to use "done" instead of 'done'
3. do you have any htaccess file ?
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, now work. Great.
Unbelievable, the influence that the space before <?php have, and the error was that one.
Put ' or " in done don't have influence.
About the htaccess file, I have a normal one in the root of the project, but I thing don't have any influence.
What matter is the script work well.
Thanks for both, I will assign the points, and I will put here the finish code for future reference:
INDEX:PHP
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
        $.ajax({
        type: "POST",
        url: "ajax_processar.php",
        data: {'redirect': '2'},
        success: function(dat){
                console.log('ajax is done');
                if(dat == "done"){
                $('#n').text(dat);
                alert("I am not redirected");
                } else {
                // redirect
                window.location=dat;
                } 
        }
        });
}); 
</script>
</head>
<body> 
<div id="n"></div>

</body>
</html>

Open in new window

AJAX_PROCESSAR.PHP
<?php

$x = $_POST['redirect'];

if($x == 1){
     echo "http://www.google.com";
}
else if($x == 2){
mail("geral@gloradin.com", "hello", "variable 2");
     echo "done";
}
else if($x == 3){
     echo "done";
}

?>

Open in new window

Thanks for both.

The best regards, JC
0
 
Lukasz ChmielewskiCommented:
LOL I saw the space before but I assumed that this was just something about copy/paste.
This is clear now, that output was " done" instead of "done", so the page was redirected.
0
 
Pedro ChagasWebmasterAuthor Commented:
Hi, just one more thing if you can, one explanation:
What this line do:
"console.log('ajax is done');"?

~JC
0
 
Lukasz ChmielewskiCommented:
If you're using some debugger, like this:
http://getfirebug.com/logging
there is a console present, so that you can view log messages.
0
 
Pedro ChagasWebmasterAuthor Commented:
Thank you for all.

~JC
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.