626
626

Reputation: 1159

jQuery AJAX pass url as string

I have a ajax function that is passing a string of variables to my script but I have one variable that needs to contain a full url with parameters.

What happens is that var1 and var2 become $_POST variables but I need to save the whole url variable as a string.

var url = "http://domain.com/index.php?var1=blah&var2=blah";

var dataArray = "rooftop_id=" +rooftop_id+ "&url=" +url;

        $.ajax({
            type: "POST",
            url: "/scripts/error_check.php",
            data: dataArray,
            dataType: 'json'
        }); 

I would like my $_POST variable to look like this:

$_POST['rooftop_id'] would be '1234'
$_POST['url'] would be 'http://domain.com/index.php?var1=blah&var2=blah'

Thanks in advance!

Upvotes: 2

Views: 17326

Answers (2)

Quentin
Quentin

Reputation: 944443

Don't try to build your form data by hand. jQuery will encode it for you (with appropriate escaping) if you pass it an object.

var url = "http://domain.com/index.php?var1=blah&var2=blah";

$.ajax({
    type: "POST",
    url: "/scripts/error_check.php",
    data: { url: url, rooftop_id: rooftop_id },
    dataType: 'json'
}); 

Upvotes: 0

Danijel
Danijel

Reputation: 12719

Use encodeURIComponent() on url variable:

var url = "http://domain.com/index.php?var1=blah&var2=blah";

var dataArray = "rooftop_id=1&url=" +encodeURIComponent(url);

$.ajax({
    type: "POST",
    url: "/scripts/error_check.php",
    data: dataArray,
    dataType: 'json'
}); 

Upvotes: 8

Related Questions