user849137
user849137

Reputation:

how to use this data echoed from PHP in JQuery or JavaScript?

I have an AJAX request on a php file, which returns some data, like this:

21-12-12:::visits;45;;pageviews;344---22-10-10:::visits;71;;pageviews;34---15-01-11:::visits;4;;pageviews;30

Notice the pattern^^ It's like a multidimensional array, but only not an array, just a string.

I need a way to separate that string, and use the value of visits and pageviews for each date.

I already know how to split the string up in JQuery, but i have no idea how to get the value of visits for a specific date from that string, example, get the number of visits for the date 15-01-11.

Any suggestions or better alternatives would be great. Please don't mention JSON though, I've just given up with that.

Thanks

Upvotes: 0

Views: 106

Answers (3)

Tilman Schweitzer
Tilman Schweitzer

Reputation: 1487

Do you have control over the output format? If so switch to JSON, otherwise split the data with some RegEx.

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

Assuming you have the above string available in a variable named string, you can do:

var parts = string.split('---'), visits = 0, pageviews = 0;
for(var i=0; i<parts.length; i++) {
  if(parts[i].indexOf('01-01-01')!=-1) { // ex: looking up 01-01-01
    parts = parts[i].split(':::')[1];
    parts = parts.split(';;');
    visits = parts[0].split(';')[1]; // visits for 01-01-01
    pageviews = parts[1].split(';')[1]; // pageviews for 01-01-01
  }
}

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318508

JSON is the alternative and extremely easy since you are using PHP and jQuery. Actually, everything else would be either a huge mess (parsing a string like you want to do) or much more complicated (using XML instead of JSON).

In your PHP code you simply echo json_encode($arrayWithYourData); and the response argument of your AJAX success callback will contain the same object.

Since you want to get data for a certain date, you might want to use the data as the array key - then you can just use e.g. response['01-01-01'] to access the corresponding array element.

Upvotes: 3

Related Questions