Pankaj Khurana
Pankaj Khurana

Reputation: 3271

Javascript error while executing alert function through php

I am using fusion maps in one of my application.

In one of the example i have to pass the value from one map to another charts,

I am facing one problem if the data passed is numeric its displaying alert message correctly but if it is a string it generates an error:

NM is not defined

javascript:alert(NM)()

My code is as below:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(".($rs1['Internal_Id']) . ")'  />";

If i change the link part (passing single quotes in alert)that is:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert('".($rs1['Internal_Id']) . "')'  />";

It displays invalid xml data.

Please help me on this

Thanks

Pankaj

Upvotes: 1

Views: 258

Answers (3)

Yacoby
Yacoby

Reputation: 55445

Use \" rather than ' to surround the JavaScript string.

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(\"".($rs1['Internal_Id']) . "\")'  />";

What is happening is that the xml produced is like so:

<entity id='NM' value='1' link='javascript:alert('NM')'/>

Which as you should be able to see from SOs syntax highlighting ends the value for the link attribute after javascript:alert(' as you are using the same quotes for the javascript as you are using for surrounding the attribute values.

Using a different quote (" rather than ') doesn't end the attribute value (again see the syntax highlighting)

<entity id='NM' value='1' link='javascript:alert("NM")'/>


In PHP we have to escape the quote (Using \) so it isn't interpreted as a special character by the php interpreter and used to end the string, which is why in php you have to write \"

Upvotes: 1

Rob Grant
Rob Grant

Reputation: 7348

Try:

$strXML .= "<entity id='" . $rs1['Internal_Id'] . "' value='" . round((($rs1['datap'] /  $sumdata) * 100),2) . "' link='javascript:alert(\"".($rs1['Internal_Id']) . "\")'  />";

Basically escaping your alert quotation marks :)

Upvotes: 0

DKSRathore
DKSRathore

Reputation: 3063

You should change your

ink='javascript:alert('".($rs1['Internal_Id']) . "')'

by

ink='javascript:alert(\"".($rs1['Internal_Id']) . "\")'

Upvotes: 0

Related Questions