1

I have a string that terminates prematurely because of '&q' (I'm guessing) being escaped in the original string. How should I handle this if I want to retain the original string in PHP?

Original string

'http://answers.onstartups.com/search?tab=active&q=fbi'

Result of var_dump

'["http://answers.onstartups.com/search?tab=active'

JS

var linksStr = $("#links").val();
var matches = JSON.stringify(linksStr.match(/\bhttps?:\/\/[^\s]+/gi));

    $.ajax({
      type: 'GET',
      dataType: 'json',
      cache: false,
      data: 'matches=' + matches,
      url: 'publishlinks/check_links',
      success:                    
        function(response) {
        alert(response);

        }
    })    

check_links

$urls = $this->input->get('matches');        
var_dump($urls);
el_pup_le
  • 11,711
  • 26
  • 85
  • 142
  • Reposts are not appreciated. http://stackoverflow.com/questions/7044409/json-escaped-character – mario Aug 12 '11 at 19:37

3 Answers3

3

You can encode the JSON string:

    data: 'matches=' + encodeURIComponent(matches),

You could also write it like:

    data: { matches: matches }

and then jQuery should do the encode step for you.

Pointy
  • 405,095
  • 59
  • 585
  • 614
3

Your url as returned from jQuery .val() is:

'http://answers.onstartups.com/search?tab=active&q=fbi'

The .match() regex will return an array:

new Array("http://answers.onstartups.com/search?tab=active&q=fbi")

Which JSON.stringify() correctly outputs as:

["http://answers.onstartups.com/search?tab=active&q=fbi"]

However if you attach it as raw GET parameter here:

 data: 'matches=' + matches,

Then the enescaped & in the URL will terminate the GET value. Use encodeURIComponent

mario
  • 144,265
  • 20
  • 237
  • 291
2

Change data: 'matches=' + matches,

To: data: {"matches": matches},.

So that jQuery will figure out the encoding for you. Otherwise you'll have to encode the uri using encodeURIComponent()

Paul
  • 139,544
  • 27
  • 275
  • 264