0

I'm using ajax to request data and and echoing a string containing a number of variables and trying to parse this data using javascript.

Echo eg. fullname=Joe Soap&companyname=banana&website=mywebsite.com

In my javascript, I understand I could use string functions to search and extract, but this seems a bit cumbersome.

I'm assuming there is a much more elegant solution which I don't know about (I haven't been coding in PHP and javascript for very long) and I'm keen to learn the best practices.

What is the best way to achieve this?

  1. Is this the best way to echo multiple values back to my javascript?

  2. What is the best way in javascript to parse the data?

Thanks in advance.

singhakash
  • 7,891
  • 6
  • 31
  • 65
Diego
  • 89
  • 1
  • 11
  • 3
    This is what JSON was designed to do. – JJJ Feb 01 '15 at 11:02
  • http://php.net/manual/en/function.json-encode.php and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – Ruan Mendes Feb 01 '15 at 11:05
  • The second answer on the duplicate better explains the solution to what you ask. Long story short, you `echo` JSON, using PHP's `json_encode()` function, and then JavaScript can easily parse that. – Madara's Ghost Feb 01 '15 at 11:06
  • JSON worked perfectly here thanks! Always good to learn something new – Diego Feb 01 '15 at 13:16

1 Answers1

1

You probably need json_encode

http://php.net/manual/en/function.json-encode.php

Matt Evanoff
  • 966
  • 4
  • 9
  • Perfect thanks, thats the push in the right direction I needed. Used json_encode on my php side and JSON.parse on my javascript side. – Diego Feb 01 '15 at 13:14