SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    ri
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    problems generating javascript string variables with php..

    i'm trying to create some javascript string variables using php. i'm running into a problem because some of the variables span multiple lines and this is causing a problem. here is a sample of what i'm trying to do:

    var thetext1=new Array()
    thetext1[0]="info for #1 goes here"
    thetext1[1]="info for #2 goes here"
    thetext1[2]="info for #3 goes here"

    etc.... the array values are output from a mysql db using php and used for a script i have on my page.

    the problem is some of my strings span multiple lines and end up making it look like:

    thetext1[36]= "this is an example
    of how some stuff spans
    multiple lines"

    Using the javascript console in firefox i see the problem is: "Error: unterminated string literal." I believe it is because the string I am trying to input is spanning multiple lines. any idea on how to fix this?

    i'm using php/mysql to create these javascript variables so i have access to their functions. i tried doing this:
    str_replace( "\n", '', $row['text']);
    to replace the newlines with nothing but they're still there.

    any ideas on how to get around this?

    i greatly appreciate any help

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could try urlencoding it with php, and then urldecoding with the javascript function unescape(), e.g.

    thetext1[0]=<?php echo urlencode($result); ?>;
    thetext1[0] = unescape(thetext1[0]);

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    ri
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i figured it out... my function to remove the newlines should be:
    str_replace( "\r\n", '<br>', $row['text']); // if i want <BR> instead of newlines

    NOT
    str_replace( "\n", '', $row['text']);

    i was missing the \r which i guess screwed everything up

    thanks for your help

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i was missing the \r
    It's different for different systems:

    windows: \r\n
    mac: \r
    unix: \n


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •