error with posting ajax

impressionexpress
impressionexpress used Ask the Experts™
on
Im posting 2 variables using formdata via ajax

my php does what it needs to do and then tries to re-direct header('location: someotherwebsite.com')

Ajax is returning an error. page does not re-direct

Im not expecting any results

what im basically doing in the script is unsetting session variables session_destroy() then moving them away from the current page back to the home page
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,

What is the exact error message?
you can also check in your PHP logs

If you only clear the session you can just use a page like logout.php
that have destroy session function and redirection to your page

Ajax and JS may give you cors error on redirection to other domain for example
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
You're not going to be able to do what you want in the way that you're trying.

You say you post values to the server, and the PHP script handles that. You can't then use a header redirect at the server level as the content of what you've redirected to will be sent back to the AJAX call as the content.

What you would need to do is pass the variable off to PHP, do whatever you need there and then return a value to your AJAX call. In the success handler of the AJAX call, you would then need to call your redirect.
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
I wonder if what you mean to do is to take the redirection out of php and instead put the redirection in your success/done function using javascript
window.location.replace("http://mysite.com/someotherpage");

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Just to expand on what Chris and Scott have said.

An AJAX call is a SEPARATE HTTP call to the server - it does not have any link to the page that is displayed in the browser. Think of it as opening a completely separate tab and typing in the URL (or posting a form) in that new window. Whatever happens with the backened script happens ONLY in that tab. If you want the original tab to do something you have to code that into the page in the second tab.

So when you issue a redirect from PHP you are telling the "second tab" to redirect - not the original page.

The typical approach is to do the following

<?php
$response = (object) [
   "status" => false;
];

$var1 = isset($_POST['var1']) ? $_POST['var1'] : false;
$var2 = isset($_POST['var2']) ? $_POST['var2'] : false;

if ($var1 && $var2) {
   // do your thing here
  $response->url = 'someotherwebsite.com';
  $response->status = true;
} else {
   $response->error = 'The data submitted was missing or incorrect';
}
die(json_encode($response));

Open in new window


Client side
$.ajax({
   url: 'script.php',
   data: {var1: 'Mickey', var2: 'Mouse'},
   type: 'POST',
   dataType: 'JSON'
}).then(function(resp) {
   if (resp.status) {
     // ALL GOOD. REDIRECT TO SITE USING URL RETURNED FROM THE SERVER
     window.location.href = resp.url;
   } else {
     alert(resp.error);
   }
});

Open in new window


In the above code the server still controls where we redirect to - we just implement that redirect in the browser.

Author

Commented:
I get it. it actually works out better like this. what I would need to do now though is detect if the server is sending back a URL or text. Im guessing this would best be done with a regex? the url could have a subdomain at times and other times not. if a url is not returned, it will most likely be an error from the server.. I would like to display to screen for the user. Can someone help me with a javascript or jquery to validate a url such as: domain.com, www.domain.com, subdomain.domain.com.

Thanks in advance
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
You shouldn't need to validate anything on the client site (in your AJAX Call).

Just send back from the server what you need. Julian's example shows you what we mean - the server sends back a JSON result. That result will have the status property set to either true or false. If it's true, the response will also include the URL to redirect to. If it's false, then it will contain an error message.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Im guessing this would best be done with a regex?
The transaction between server and client is done through an agreed interface. In other words (if you are in control of the server) create a protocol for how data will be exchanged and stick to it.

In my sample I used a standard response object with a status indicating success / failure and then either the url property or an error depending on the outcome.

My script then knows it can check the status - if it is true it knows it will find a URL property - if not an error property.

You can structure this however you like - in accordance with the requirements of your application.

If you are not in control of the server then simply understand what the server sends back and code around that.

As Chris says - no validation required - if you get a success from the server assume the url is correct - otherwise your server process is not worth it.

Author

Commented:
The Server will give a url when all conditions are met, otherwise I display an error message such as "no results"

on ajax success I do window.location.href = data

if the url is correct then we have nothing to worry about.

if the server sends back a message it gets set as the data variable and the page will then likely show a error pg 404

this is why I would like to make sure the response is a url

maybe im going about this the wrong way. if so.. please tell me a better way
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
When you get the response from the server, that response will have a property call status - it will be set to either TRUE or FALSE. If it's set to TRUE, then you know you have a URL. If it's set to FALSE, then you have an error:

if (resp.status) {
    // status is set to TRUE so you KNOW you've got a URL!
    window.location.href = resp.url;
} else {
    // status is set to FALSE so you KNOW you've got a error!
    alert(resp.error);
}

Open in new window

Author

Commented:
I noticed Julian is using ".then" in his ajax call, whats the difference between .success and .then?

also do I need to use JSON.parse(data); on the client side before working with the data from the server ?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Traditionally jQuery used handlers called success() and error(), but they're now deprecated in favour of done() and fail(). The then() method is standard Javascript used with Promises and get's fired when the Promise resolves. You could just as easily use done() if you prefer.

And no - you don't need to Parse the JSON, because you've already told your AJAX call to expect JSON back with the dataType property, so it'll get parsed automatically:

$.ajax({
    url: 'script.php',
    data: {var1: 'Mickey', var2: 'Mouse'},
    type: 'POST',
    dataType: 'JSON'
}).then(function(resp) {
    ...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial