Javascript send href without clicking?

I'm not sure if this is possible. I have a link like this

<a id="addCart" href="http://mydomain.foxycart.com/cart?name=test-product&price=10.00">Add to Cart</a>

      

This link, when clicked, sends the values ​​to the user's json cart on another server.

However, I have a situation where I need to send similar values ​​using this href link, but not clicking. eg:

$('.name').each(function() {
    while (y < data.products.length-1) {
        if($(this).text() === data.products[x].name) {
            $('.price').eq(x).text(data.products[x].price);
            //href here!
        }
        x++;
        y++;
    }
    x=0;
    y=0;
});

      

I need to pass this href:

href="http://mydomain.foxycart.com/cart?value=true"

      

in // href here! above without clicking. Hope I make sense with my request. Is there a way to do this?

thank

+3


source to share


7 replies


try it

 window.location="http://mydomain.foxycart.com/cart?value=true";

      

OR

window.location.href="http://mydomain.foxycart.com/cart?value=true";

      



however it requires a browser if that's what you want

OR without leaving the page .. you can use ajax.

jQuery.ajax({
    type: 'post', 
    url: 'http://mydomain.foxycart.com/cart?value=true',
    success: function(data) {
        // do your stuff
    }
});

      

0


source


This will bring up the url without leaving the site you are on.

jQuery.ajax({
    url: 'http://mydomain.foxycart.com/cart?value=true',
    success: function(data) {}
});

      



I'm not 100% sure if you can call another domain if the javascript works on another. So maybe you need to do:

jQuery.ajax({
    url: '/cart?value=true',
    success: function(data) {}
});

      

0


source


var href = "...";

if($(this).text() === data.products[x].name) {
   $('.price').eq(x).text(data.products[x].price);

   //put this code
   $.ajax(href, function(resp) {
        //do something
   });
}

      

0


source


Am I wrong, but you're just not trying to do

$.ajax({
    url: "http://mydomain.foxycart.com/cart/",
    type: "get",
    data: { value : true }
});

      

0


source


You can parse Url Href values ​​with JSON.parse and do your processing with your loop, etc. Prevent link click ...

Check here http://jsfiddle.net/RKc6f/

$(function() {
    $("#addCart").on('click', function(e) { 
        var url = $(this).attr("href");
        var urlParams = url.substring(url.indexOf("?")+1);

        var myProduct = (JSON.parse('{"' + decodeURI(urlParams.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}'));
        console.log(myProduct.name);
        console.log(myProduct.price);
        //do the processing    
        e.preventDefault();//preven going to other page   
    });
});

      

0


source


The short answer to your problem is: yes , you can. However, this requires you to have access from the other side in order to modify the script to accept cross-site requests. However, you have to be very careful with this because it involves many security risks.

You can do it like this:

link:

<a href="http://mydomain.foxycart.com/cart?value=true" id="send_without_click">There is a link</a>

      

Javascript / JQuery code:

$(document).ready(function () {
    var a_handler = "#send_without_click";
    var $a = $(a_handler);
    var a_url = $a.attr('href');
    $.ajax({
        type: 'POST',
        url: a_url,
        crossDomain: true,
        data: {
            href: a_url
        },
        beforeSend: function () {
            //Do something before send. If not just remove the "beforeSend" part...
        },
        success: function (responseData, textStatus, jqXHR) {
            //the responseData is what you will get as response from the server
            var value = responseData.someKey;
        },
        error: function (responseData, textStatus, errorThrown) {
            alert('POST failed.');
        }
    });
});

      

On the server side, your page that receives the post request must have specific headers in order to be able to receive the AJAX call. This will allow your script to do cross domain POST, GET and OPTIONS. Here's an example in PHP:

example cart.php file

switch ($_SERVER['HTTP_ORIGIN']) {
    case 'http://from.com': case 'https://from.com':
    header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Content-Type');
    break;
}

      

All of the above will follow this sequence:

  • The browser sends OPTIONS to the server . This is a security metric in the browser to see if the server allows messages / requests to the cross-site site (regardless of the server).
  • The server then responds with "Access-Control-Allow-Origin" telling the browser to allow you to POST | GET | ORIGIN if the request originated from " http://from.com " or the secure form https://from.com ".
  • Since the server is fine, the browser will make the POST request you requested.

* Notes

  • It is good practice that your client dictates the type of content they submit, so you need to allow that as well.
  • The server will execute 2 requests per operation
  • The safety implications are increasing. "Access-Control-Allow-Origin: *" is dangerous.
  • This does not work in very old browsers and possibly mobile browsers.
  • Always return the headers above, not just OPTION requests .

EDIT:

Also I found a way to get the data if you know the website (external) is using JSONP Ajax.

//JSON format:
{"name":"stackoverflow","id":5}
//JSONP format:
func({"name":"stackoverflow","id":5});

      

If you know example.com serves JSON files that look like JSONP, then you can use code like this to get it even if you're not on example.com:

function func(json){
    alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

      

0


source


This might be a little late, but since no answer is accepted and no one has mentioned it yet: You can also use a virtual image element and pass your url src to it, triggering a pull request that has no CORS restrictions. In these lines:

var getter = document.createElement('img');
getter.src = href; //url got from the $('#addCart') element or whatever you need

      

0


source







All Articles