Jump to content

Problem: Ajax -requests getting 301 redirects


foobar123
 Share

Recommended Posts

Hello,

I have a problem with all AJAX -requests getting 301 redirect. AFAIK this leads to the POST -data sent with the request getting cleared.

Below I is an example about what I'm trying to do.

My question is:

  • Is there something I don't understand about Processwire or internet technology which is causing this behaviour?
  1. I have page with a button.
  2. When you click this button, an HTML overlay popup (done with Foundation and Reveal) with option to enter email is displayed
    • (The content of this popup is a processwire template which is loaded with AJAX -request. Causes also 301 redirect, but this doesn't use POST -data, so I didn't realise the problem at this point)
  3. Then this data is sent as POST -request with payload to processwire for processing
  4. The processing is done by special API -template, which exists solely for this purpose of processing data.
  5. However the payload in the POST -request never reaches the API -template
  6. I believe this is because a 301 redirect happens before the the POST -request reaches the API -template

Thanks for reading and special thanks for any answers!

Example code:

Popup (HTML & JavaScript):

<!-- use onsubmit to override the standard 'sending form to self' -behaviour
<form onsubmit="WEBSITE.dialog.download.mail($('#email').val(), event); ">
   <label>email:</label>
   <input id='email' name='email' type='email' value=''>
   <input type="submit" value="Send">
</from>

The function which sends the POST -request to processwire template (which processes  API requests) (the function is in separate .js file)

// I've translated this from CoffeeScript to JS without testing, hope there's no errors 

dialog = {
 download: {
   mail: function (email, ev){

     // Prevent default behaviour of submit -functionality
     ev.preventDefault(); 
     
     // Success and error callbacks
     success = function(response){
        console.log('success', response);
     }
     error = function(response){
        console.log('error', response);
     }

     // Do ajax -request with jQuery
     request = $.ajax({
       url: '/api/mailer/send/',
       method: "POST",
       data: {email: email},
       success: success,
       error: error
     });
  }
 }
}

I've also tried this with doing the request without jQuery, but result is the same.

 

The API template (PHP):

?php

  // Redirect non-ajax calls
  
  // Get the API address from url
  $api_url = explode('/api/', $page->url);

  if(!isset($api_url[1])){
    // This url is not in correct format, send error
    die(createJSONResponseError(
        1,
        'Invalid url format.'
      )
    );
  }

  switch ($api_url[1]):

    case 'mailer/send/':

      // This is where it stops every time, though I've checked from Chrome dev console that the email key/value pair exists (at least when request is made)
      if($input->post->email === null){
         die(createJSONResponseError(
             2,
             'Insufficient params.'
           )
         );
      }else{
        // Create the response
        $response = createJSONResponse(
          'success', 
           null
        );
      }
      break;

    // Default action - needs to be last of the list
    default:
      // So this api does not exist, send error
      die(createJSONResponseError(
          1,
          'Unknown API.'
        )
      );
      break;

  endswitch;

  // Send the response
  die($response);

?>

Here's how the responses are created (from a helper methods file):

/**
* Create JSON response for httpXMLRequest
*
* @param status - a string that represents the status of this operation. Recommended values: 'success' or 'error'
* @param result - the data resulting this request.
*
* @return JSON object
*
*/
function createJSONResponse($status, $result){
  return json_encode(
    array(
      'status' => $status,
      'result' => $result
    )
  );
}

/**
* Create JSON error response for httpXMLRequest
*
* @param code - error code
* @param msg - error message
*
* @return JSON object
*
*/
function createJSONResponseError($code, $msg){
  return createJSONResponse(
    'error', 
     array(
      'code' => $code,
      'msg' => $msg
      )
  );
}
Link to comment
Share on other sites

What is your slash setting on the template? If you have no trailing slash turned on it would get redirected from domain/url/ to domain/url — and as you have trailing slash in the JS, it could be that you've turned it off.

(also, it seems you're using input segments. Those have have the trailing slash setting as well)

Link to comment
Share on other sites

What is your slash setting on the template?

"Should page URLs end with a slash?" is set to "Yes".

(also, it seems you're using input segments. Those have have the trailing slash setting as well)

Actually I have page structure to reflect the structure of the api. The "Allow URL Segments?" -setting is set to "No".

Link to comment
Share on other sites

So I found  the reason behind redirects:

  1. I'm using the multilanguage version of Processwire, and it adds the language id to URLs (e.g mysite/en/page/)
  2. My request URLs didn't have this language string in them (e.g mysite/page/) which caused them to be 301 redirected

I was able to find this out by using this plugin, which gives more detailed information about headers than Chrome dev tools (redirects are not bundled into one entry):

https://chrome.google.com/webstore/detail/live-http-headers/iaiioopjkcekapmldfgbebdclcnpgnlo

Thanks for the help I received

  • Like 1
Link to comment
Share on other sites

  • 6 years later...

Oh yes, it´s a old post. But now i have the same issue and find the same results at a multilingual site (post before).

What i can do to prevent a redirect?

Pass the correct url or i can set some template parameters? 

Greetings

 

edit

This setting causes an endless redirection, if get the url by an other language. But one redirect is still running, eg. for france

https//domain.com/ajaxpage => https//domain.com/fr/ajaxpage and there lost the post parameters.

image.thumb.png.f3a19fc36ca5ec9e9f39f858f730e121.png

Link to comment
Share on other sites

  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...