Git Product home page Git Product logo

jquery.redirect's Introduction

jQuery.redirect

A simple HTTP POST and GET Redirection Plugin for jQuery

  • Easy to use
  • GET and POST requests
  • Compatible with jQuery, jQlite and Zepto.js
  • Supports nested objects and arrays

How does it work?

The function jQuery.redirect will create a form and populate it with the data (it supports nested values).

Installation

Using Bower

bower install jquery.redirect

Using NPM

npm install --save jquery.redirect

Using Yarn

yarn add jquery.redirect

Manual Installation

Just download jquery.redirect.js and include it in your html after jquery.js

<html>
<head>
    <!-- other headers -->
    <script src="jquery-XXX.js"></script>
    <script src="jquery.redirect.js"></script>
</head>
<body>
    <!-- your content -->
</body>
</html>

CDN

If you prefer, you can use RawGit CDN hosted version

Usage

/**
* jQuery Redirect
* @param {string} url - Url of the redirection
* @param {Object} values - (optional) An object with the data to send. If not present it will look for values as QueryString in the target url.
* @param {string} method - (optional) The HTTP verb can be GET or POST (defaults to POST)
* @param {string} target - (optional) The target of the form. If you set "_blank" will open the url in a new window.
* @param {boolean} traditional - (optional) This provides the same function as jquery's ajax function. The brackets are omitted on the field name if its an array.  This allows arrays to work with MVC.net among others.
* @param {boolean} redirectTop - (optional) If its called from a iframe, force to navigate the top window.
* @param {boolean} shouldKeepBlankFields - (optional) If shouldKeepBlankFields is false, blank fields will be removed.
*/
$.redirect(url, [values, [method, [target, [traditional, [redirectTop, [shouldKeepBlankFields]]]]]])

/**
* jQuery Redirect
* @param {string} opts - Options object
* @param {string} opts.url - Url of the redirection
* @param {Object} opts.values - (optional) An object with the data to send. If not present will look for values as QueryString in the target url.
* @param {string} opts.method - (optional) The HTTP verb can be GET or POST (defaults to POST)
* @param {string} opts.target - (optional) The target of the form. "_blank" will open the url in a new window.
* @param {boolean} opts.traditional - (optional) This provides the same function as jquery's ajax function. The brackets are omitted on the field name if its an array.  This allows arrays to work with MVC.net among others.
* @param {boolean} opts.redirectTop - (optional) If its called from a iframe, force to navigate the top window.
* @param {boolean} opts.shouldKeepBlankFields - (optional) If shouldKeepBlankFields is false, blank fields will be removed.
*/
$.redirect(opts)

Example of use with Object

<html>
<head>
    <!-- other headers -->
    <script src="jquery-XXX.js"></script>
    <script src="jquery.redirect.js"></script>
    <script>
     jQuery(function($){
     //OnClick testButton do a POST to a login.php with user and pasword
      $("#testButton").click(function(){
       $.redirect("/login.php", {user: "johnDoe", password: "12345"}, "POST", "_blank");
      });
     });
    </script>
</head>
<body>
   <button id="testButton">Test Redirect</button>
</body>
</html>

Example of use with links

<html>
<head>
    <!-- other headers -->
    <script src="jquery-XXX.js"></script>
    <script src="jquery.redirect.js"></script>
    <script>
     jQuery(function($){
     //OnClick link do a POST to a login.php with query string
     // data (user and pasword in this case)
      $("body").on("click",".post-redirect", function(){
        $.redirect($(this).attr("href"));
      });
     });
    </script>
</head>
<body>
   <a href="/login.php?user=johnDoe&password=12345" class="post-redirect">Test redirect</a>
</body>
</html>

Running Tests with Yarn

yarn install
yarn test

jquery.redirect's People

Contributors

akankov avatar amotl avatar andresgalante avatar ccjmk avatar cortexelus avatar dhpaulino avatar dquark avatar fab-c avatar felipsbreno avatar h0jezvgoxfepbq2c avatar kurtpreston avatar lipemenezes avatar mb16mb16 avatar mgalante avatar mjs330 avatar mwarnock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.redirect's Issues

How to post json data

Hi, Can I Post Json Data?
var data = '{keys:' + JSON.stringify(selectedKeys) + '}';

array data

How can I do this?
$.redirect("{% url "/login.php", {'id[]': [1, 2]}, 'GET');

can I transfer an object only?

On submit parameter name change value

Hi I'm experimenting a strange behavior, during the form submit if a parameter is named for example "test" the script change his name to "0[test]".

Is this normal?

Redirect from an iframe page with jQuery redirect

I am using this library to redirect from a page to another one, which work like a charm. But we wanted to host this page in an iframe, and when we do that the redirection happens on the iframe level only and not the parent window. Is there a way to force parent page redirection in a clean way using this library.

TypeError: method.toUpperCase is not a function

Estoy agregando un headers con un token:
var csrfToken = <?php echo json_encode($this->request->getParam('_csrfToken')); ?>;
$.redirect('<?php echo Router::url(["controller" => "Users", "action" => "previo"]); ?>', {headers: {'X-CSRF-Token': csrfToken}} ,{filtro : 'Cliente'});
Pero me muestra el error: "TypeError: method.toUpperCase is not a function" en esta línea del jquery.redirect:
$.redirect = function (url, values, method, target, traditional) { method = (method && ["GET", "POST", "PUT", "DELETE"].indexOf(method.toUpperCase()) !== -1) ? method.toUpperCase() : 'POST';

$.redirect is not a function

Hello,

I am using redirect.js and send this request:

$.redirect('details.php', {'return': 'yes'}, 'post');

but i am getting error of $.redirect is not a function

Remove form from DOM after submit

Supposing that you submit your form using a target='_blank' attribute, i think it's a good idea to remove the form from the DOM, cause i've made some tests and it create a new form for each $.redirect call.

For instance:
#38

access values from redirected page

I am sending AJAX POST request from the page and redirecting to another page on the same domain.

$.ajax({
    type: form.method,
    url: form.action,
    data: $(form).serialize(),
    dataType: 'json',
    success: function(response) {
        // redirect with response
        $.redirect({
            url: <my_url_here>,
            values: { payload: response },
            target: '_blank'
        })
    }
})

How can I access payload from the redirected page?

How can I use this with React?

Hi, I am trying to use this Lib in a react project, but I can not get it working. Do you have an Idea how I can go about it?

how to send the headers

May I send headers' data ?

$.redirect('/auth/home', {headers: createAuthorizationTokenHeader()});

    function createAuthorizationTokenHeader() {
        var token = getJwtToken();
        if (token) {
            return {"Ok": "Bearer " + token};
        } else {
            return {};
        }
    }

Target _self doesn't work

Hi All,

Target _self doesn't work. I don't see any issue in console.
With _blank target is working.

`$(document).ready(function(){
$('#userlogin').submit(function(){

		var captcha = $('#captcha').val();
		var randomcaptcha = '<?php echo $captcha; ?>';
	
	if(captcha == randomcaptcha){
		
		var username = $('#username').val();
		var password = $('#password').val();

		$.redirect("<?php echo URL ?>login/check", {username , password}, "POST"); 
	
	}else{

		$.redirect("<?php echo URL ?>login/wrong", {username , password}, "POST"); 
	
	};
});

});`

Error

method.toUpperCase is not a function

A way to add global headers or parameters

Hello,

First, thank you for providing this very unknown and useful library.

I am trying to add headers for CSRF security to the system I'm developing. I found that adding global headers to the jQuery Ajax requests is possible through $.ajaxSetup().
Do you think there is a way to add headers to the $.redirect() calls (only POST requests)? Maybe modifying the code of the library a little. Or should I add them manually to every call of the redirect library?

Thanks

Edit: The CSRF fields can also be parameters of the request and not request headers.

Feature request: hook to transform inputs

I'd like to modify one or more of the inputs before submitting the form. It would be helpful to have a transformation hook to accomplish this. Say, something like:

$.redirect(url, data, function(name, value) {
     // Transform and return value.
});

Is there a better way to do this?

Issues with POSTing an array of objects

Hello,

I think I may have discovered a bug.

I have this object, which I've encoded as JSON.

{
  "survey":{
    "questions":[
      {
        "editUrl":"/survey/partials/textQuestion",
        "isEditing":false,
        "name":"test"
      }
    ],
    "configurationId":"FAA2A792-5EF9-4736-9AD1-FD30A587945E"
  }
}

When this is POSTed, it looks like the keys in the questions array are being put split into arrays. Here is what I get when I run var_dump() on the "survey" object that's posted.

Array
(
    [questions] => Array
        (
            [0] => Array
                (
                    [editUrl] => /survey/partials/textQuestion
                )

            [1] => Array
                (
                    [isEditing] => false
                )

            [2] => Array
                (
                    [name] => test
                )

        )

    [configurationId] => FAA2A792-5EF9-4736-9AD1-FD30A587945E
)

I expected "editUrl", "isEditing", and "name" to keys in the "questions" array, but they are encoded differently, which I think is a bug.

Hope this helps, and thanks for the library :)

Submit name conflict

This plug is working fine for me except one scenario. I am having one parameter with name submit. when i am using this plug in whit that parameter it is creating a hidden element as name="submit"

So my form is not submitting due to this.

Can anyone help me out.

Adding a license

Hi!

First of all, I'd thank you for creating this useful software! Could you please also consider adding a kind of license header to clarify the conditions under which we can use of it? Is it distributed under the same license as jQuery itself (namely https://jquery.org/license/)?

I understand that this sounds a bit bureaucratic, but is really important for those who'll try to make a us of.

Thank you very much!

Valentin

utf-8 in content-type

Hello
I'm using your code and it's great !.
but when i send Object that contains UTF-8 words(like persian words) , params isn't sent properly because in content type we don't have charset="utf-8" .
do you have any solution ?
thank you ;D.

blank fields are removed

Any fields that have a blank string as a value are removed. This does not match $.ajax()

For example $.ajax() would send:
foo[bar]: beep
foo[test]:
foo[bla]: boop

but $.redirect() sends:
foo[bar]: beep
foo[bla]: boop

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.