0

how to redirect the request to specified php page by ajax call, below is my code structure

index.html

<html>
<script>
function shift(str)
 {

$.ajax({
   url: 'destination.php',
   type:'POST',
   data: {q:str}
}).done(function( data) {
    $("#result").html(data);

    });

     return false;
   }
 </script>

  <body>
  <input type='button' value='test' onclick="shift('test');">
  <div id='result'></div>
 </html>

destination.php

   <?php
    $string=$_REQUEST['q'];

     if($string=="something")
      {
        header('something.php');
       }
      else
       {
        echo "test";
        }
     ?>

this is my code structure if posted string is same as then header funtion should be work else echo something, but header funstion is not working via ajax

4 Answers4

1

You should specify header parameter to Location. Use the code below

<?php
    $string=$_REQUEST['q'];

     if($string=="something")
      {
        header('Location:something.php');
       }
      else
       {
        echo "test";
        }
     ?>

Hope this helps you

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
0

Go With This

You can check the string in jquery like below..

First you must echo the variable in php page.

then,

 $.ajax({
 url: 'destination.php',
 type:'POST',
data: {q:str}
}).done(function( data) {
if(data=="something")
 {
      window.location.assign("http://www.your_url.com");    //
 }

});

 return false;

}

Jishad
  • 2,876
  • 8
  • 33
  • 62
0

You should always retrieve the response in json format and based on that decide where to redirect. use below code for your requirement.

function shift(str) {
    $.ajax({
        url: 'destination.php',
        type: 'POST',
        data: {
            q: str
        }
    }).done(function (resp) {
        var obj = jQuery.parseJSON(resp);
        if (obj.status) {
            $("#result").html(obj.data);
        } else {
            window.location..href = "YOURFILE.php";
        }
    });

    return false;
}  

Destination.php

<?php
$string=$_REQUEST['q'];
$array = array();

if($string=="something")
{
    $array['status'] = false;
    $array['data'] = $string;  

}else {
    $array['status'] = true;
    $array['data'] = $string;  
}
echo json_encode($array);
exit;
?>
Dhaval Bharadva
  • 3,053
  • 2
  • 24
  • 35
0
function shift(str) {
$.ajax({
    url: 'destination.php',
    type: 'POST',
    data: {
        q: str
    }
}).done(function (data) {
    if (data=="something") {
    window.location.href = 'something.php';
    }
    else {
        $("#result").html(data);
    }
});

return false;
}  

in Destination.php

<?php
$string=$_REQUEST['q'];

 if($string=="something")
  {
   echo "something";
   }
  else
   {
    echo "test";
    }
 ?>
Priyank
  • 3,778
  • 3
  • 29
  • 48