0

I have in frontend a javascript request and in backend a php that is using as url a php file. I want to know how can you redirect this? In one case I will initMap if table has data and another case I redirect.

PHP file api.php

$response = [
    'status' => 'ok',
    'data'   => $database->resultset(),
];
if (empty($response['data'])) {
    Flash::set_alert("Property details has successfuly saved. ");
    $response=[
        'status' => 'redirect',
        'data' => '/search.php',
    ];
}

This is my response. An I don't know how in javascript to make a switch that handle the response, if the table is emtpy to redirect to search.php.

Javascript code

$(document).ready(function () {

    $('#propertySearch').submit(function (e) {
        e.preventDefault();
        $.ajax({
            url: 'api.php',
            type: "POST",
            dataType: 'json', // add json datatype to get json
            data: $('#propertySearch').serialize(),
            success: function (data) {
                console.log(data);
                initMap(data.data);

            }
        });
    });

});
Daniel
  • 99
  • 9
  • 1
    [location.replace](https://developer.mozilla.org/en-US/docs/Web/API/Location/replace) `data.status === 'redirect' && location.replace(data.data)` – Vadim Aidlin Jun 26 '18 at 12:09
  • @VadimAidlin in one case , the first `$response` I have data in array and I want to `initMap`, if no data , the second `$response` -> redirect and no `initMap` – Daniel Jun 26 '18 at 12:13
  • `data.status === 'redirect' ? location.replace(data.data) : initMap(data.data);` – Vadim Aidlin Jun 26 '18 at 12:15

1 Answers1

2

Check your returned status then redirect using location.href

$.ajax({
    url: 'api.php',
    type: "POST",
    dataType: 'json', 
    data: $('#propertySearch').serialize(),
    success: function (data) {
        if(data.status && data.status === 'redirect' && data.data) {// Check all condition
            location.href = data.data;
        }
        else {
            initMap(data.data);
        }
    }
});

Also, check out this answer: How do I redirect to another webpage?

Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
Lord Grosse Jeanine
  • 1,111
  • 10
  • 29