0

Using ajax I post data to php file where I have loop with code below.

Part of my code where I can't properly format onclick event:

$result .= '<a href="#" onclick="$("#element").dialog("open");" ></a>';

I tried to escape double quotes with backslash, but no luck. Using backslashes, in console I see: Somehow from nowhere "=" appears, also all backslashes are printed. Code doesn't work.

Could someone help to figure out where I made a mistake in syntax? Thank you.

Grufas
  • 1,350
  • 4
  • 21
  • 33

3 Answers3

1

When parsing the HTML, the browser will read the onclick="$("#element" part, and infer that attribute onclick equals "$(", because it thought it found the closing double quotes. So, you'll need to escape the double quote character after the $(. Since you're using $result .= 'some_string' (I want to empasize on the single quote being used here), you are unable to escape the double quote character within the single quoted string. Thus, you'll need something like this: $result .= '<a href="#" onclick="$(\'#element\').dialog(\'open\');" ></a>';

Now, php will translate \' to just ' while rendering, so the final output of the string will be

<a href="#" onclick="$('#element').dialog('open');" ></a>

I hope this helps.

Damodar Dahal
  • 559
  • 4
  • 16
1

In your string there are double quotes, followed by content wrapped again in double quotes. The second quotes should be single quotes, but that would terminate the string. So you will have to escape them.

The desired html code should look like this:

<a href="#" onclick="$('#element').dialog('open');"></a>

to achieve this, you will have to change your PHP code to the e.g. the following:

$result .= '<a href="#" onclick="$(\'#element\').dialog(\'open\');"></a>';
Eydrian
  • 10,258
  • 3
  • 19
  • 29
-2

Double quotes should be escaped

$result .= '<a href="#" onclick="$(\"#element\").dialog(\"open\");" ></a>';

Another way is

$result .= `<a href="#" onclick="$('#element').dialog('open');" ></a>`;
prashant
  • 127
  • 2
  • 10