Why additional " is adding to argument string with spaces when receiving a function as string using ajax?

StackOverflow https://stackoverflow.com/questions/21154265

  •  28-09-2022
  •  | 
  •  

Pregunta

I am using ajax to get StateName and StateID and display a picture with received StateName. Clicking on that picture will call a javascript function callState(id,state_name). My issue is if state_name = "Tamil Nadu" is the received value, the function won't invoke. I come to know that the issue is with spacing. From console I understood that the function is called in the following form : callState(1,'Tamil"Nadu'); - An additional " comes in spacing between Tamil and Nadu.

Below are my codes, ajax redirect to processing_search_state.jsp page where I process and get the data.

responce = responce
                + "<figure> <a href='#'> <img src=../images/tim1.jpg alt='' onclick=callState("
                + id + ",'" + state_name + "')></a> <figcaption>"
                + state_name + "</figcaption></figure>";

AJAX :

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("Received Data" + xmlhttp.responseText);
            document.getElementById("sLocfigID").innerHTML = xmlhttp.responseText;
        }

alert : Received Data will print correctly with out issues. Below is the alert

<figure> <a href='#'> <img src=../images/timl.jpg alt="
onclick=callState(2,'tamil nadu')</a> <figcaption>tamil
nadu</figcaption> </figure>

But on Console the value is:

<figure> <a href="#"> <img src="../images/tim1.jpg" alt="" onclick="callState(2,'tamil" nadu')=""></a> <figcaption>tamil nadu</figcaption></figure>

For your info: These codes works fine If state_name = Goa or state_name = Kerala because these are one words or words without spacing's in it. It successfully invokes callState() function.

¿Fue útil?

Solución

Rafa is correct that you are missing quotes around your HTML attributes, but it only causes a problem from the missing quotes around your onclick attribute, not the src (since it is okay to have unquoted attributes which do not have spaces in their values).

Add an escaped double quote (\") here onclick=callState(", like so:

onclick=\"callState("

And here "')></a> <figcaption>" like so:

"')\"></a> <figcaption>"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top