How to send Jquery variable content to an html textarea?

Asked

Viewed 237 times

1

I’m having a hard time sending the contents of a variable JS for a <textarea> (in a bootstrap modal) and with XML formatting defined in the variable. Both the JS as to textarea are in the same html. The code is based on this (which only generates html results): http://www.yogihosting.com/implement-tmdb-api-with-jquery-ajax

This is the variable:

var xmlString = "<channel>" + "  <title><![CDATA[" + title + "|"+ to + "(" + ano + ")]]></title>" + "  <logo_30x30><![CDATA[" + image + "]]></logo_30x30>" + "  <description><![CDATA[<center><img height=\"254\" width=\"200\" src=\"" + poster + "\"</img><br>"+ sin +"</center>]]></description>" + "  <stream_url><![CDATA[" + escape(country) + "]]></stream_url>" + "  <subtitle><![CDATA[" + escape(zip) + "]]></subtitle>" + "</channel>";

And this is the textarea:

<textarea class="texto" id="ctext" name="ctext" cols="86" readOnly></textarea>

Can anyone help? If there is a suggestion to improve this part of the code, you are welcome.

I edited to include the full code:

<!DOCTYPE html>

Search on Tmdb

<div class="container">
    <div id="apiDiv">
        <h4>Digite o Título do Filme em Qualquer Língua e Clique em Buscar</h4>
        <input type="text" id="searchInput" placeholder="Busca Filme no TMDb" />
        <button id="submit">Buscar</button><button id="reset">Limpar »</button>
        <div class="imageDiv">
            <img src="Image/loading.gif" />
        </div>
        <div id="message">
        </div>
    </div>
    <ul id="pagination"></ul>
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" id="modalTitleH4"></h4>
            </div>
            <div class="modal-body" id="modalBodyDiv">
            </div>
            <div class="modal-footer">
                <p><textarea class="texto" id="ctext" name="ctext" cols="86"></textarea></p>
                <button class="button" id="clipboard" onclick="clipboard()">CopiarXML</button>
                <button id="bd" type="button" class="btn btn-default">Add MySQL</button>
                <button id="close" type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

            </div>
        </div>
    </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="js/jquery.twbsPagination.js"></script>

<script>
    $(document).ready(function () {
        $("#reset").click(function (e) {
            location.reload();
        });

        $("#submit").click(function (e) {
            var validate = Validate();
            $("#message").html(validate);
            if (validate.length == 0) {
                CallAPI(1);
            }
        });

        $("#message").on("click", ".result", function () {
            var resourceId = $(this).attr("resourceId");
            $.ajax({
                url: "https://api.themoviedb.org/3/movie/" + resourceId + "?append_to_response=credits&language=ptbr&include_image_language=pt-BR,null",
                data: {
                    api_key: ""
                },
                dataType: 'json',
                success: function (result, status, xhr) {
                    $("#modalTitleH4").html(result["name"]);

                    var title = result["title"] == null ? "No information available" : "" + result["title"];
                    var image = result["poster_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w185/" + result["poster_path"];
                    var poster = result["backdrop_path"] == null ? "Image/no-image.png" : ""+ "https://image.tmdb.org/t/p/w500/" + result["backdrop_path"];
                    var to = result["original_title"] == null ? "No information available" : ""+ result["original_title"];
                    var sinopse = result["overview"] == null ? "No information available" : "" + result["overview"];
                    var ano = result["release_date"] == null ? "No information available" : ""+ result["release_date"];

                    var resultHtml = "<p class=\"text-center\"><img src=\"" + image + "\"/></p><p>" + title + "</p>" + to + "</p>" + poster + "</p>" + ano + "</p>" + sinopse + "</p>"; 

                    //resultxml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"+"<items>"+"\n<playlist_name><![CDATA["+"]]></playlist_name>"+"\n\t<channel>"+"\n\t\t<title><![CDATA[<font color=\"#ffff00\">"+title+ "|" + to + "(" + ano + ")" + "</font>]]></title>"+"\n\t\t<logo_30x30><![CDATA["+image+"]]></logo_30x30>"+"\n\t\t\<description><![CDATA[<center><img height=\"254\" width=\"200\" src=\""+poster+"\"/><center><br>" +sinopse+ "</center>]]></description>"+"\n\t\t<playlist_url><![CDATA["+"]]></playlist_url>"+"\n\t\t<stream_url><![CDATA["+"]]></stream_url>"+"\n\t\t<subtitle><![CDATA["+"]]></subtitle>"+"\n</channel>\n</items>";


                    $("#modalBodyDiv").html(resultHtml) +

                    $("#myModal").modal("show");
                },
                error: function (xhr, status, error) {
                    $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                }
            });
        });


        $(document).ajaxStart(function () {
            $(".imageDiv img").show();
        });

        $(document).ajaxStop(function () {
            $(".imageDiv img").hide();
        });

        function CallAPI(page) {
            $.ajax({
                url: "https://api.themoviedb.org/3/search/movie?language=pt-BR&query=" + $("#searchInput").val() + "&page=" + page + "&include_adult=false",
                data: { "api_key": "" },
                dataType: "json",
                success: function (result, status, xhr) {
                    var resultHtml = $("<div class=\"resultDiv\"><p>Names</p>");
                    for (i = 0; i < result["results"].length; i++) {

                        var image = result["results"][i]["poster_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w500/" + result["results"][i]["poster_path"];

                        resultHtml.append("<div class=\"result\" resourceId=\"" + result["results"][i]["id"] + "\">" + "<img src=\"" + image + "\" />" + "<p><a>" + result["results"][i]["title"] + "&nbsp; (" + result["results"][i]["release_date"] + ")" +"</a></p></div>");


                        var xmlString = "<channel>" + "  <title><![CDATA[" + title + "|"+ to + "(" + ano + ")]]></title>" + "  <logo_30x30><![CDATA[" + image + "]]></logo_30x30>" + "  <description><![CDATA[<center><img height=\"254\" width=\"200\" src=\"" + poster + "\"</img><br>"+ sinopse +"</center>]]></description>" + "  <stream_url><![CDATA[" + escape(country) + "]]></stream_url>" + "  <subtitle><![CDATA[" + escape(zip) + "]]></subtitle>" + "</channel>";

                        $("textarea#ctext").val(xmlString);  

                    }

                    resultHtml.append("</div>");
                    $("#message").html(resultHtml);

                    Paging(result["total_pages"]);
                },
                error: function (xhr, status, error) {
                    $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                }
            });
        }


        function Validate() {
            var errorMessage = "";
            if ($("#searchInput").val() == "") {
                errorMessage += "► Enter Search Text";
            }
            return errorMessage;
        }

        function Paging(totalPage) {
            var obj = $("#pagination").twbsPagination({
                totalPages: totalPage,
                visiblePages: 5,
                onPageClick: function (event, page) {
                    CallAPI(page);
                }
            });
        }


        function clipboard() {
            var x = document.getElementById("ctext").value;
            document.getElementById("modal-footer").innerHTML = x;
        }

    });
</script>

  • What mistake it makes?

  • Nothing happens. I tried using $("#ctext").val(xmlString);

  • Leo Caracciolo. That didn’t work for me.

  • With text sends without problem (had already tested). Does not work with variable

  • $("textarea#ctext"). val(xmlString);

  • I tried them all. I tested them one by one. The curious thing is that there is already another variable that sends to the modal in html and works perfectly. The problem is to send text to the textarea. Do you need to convert the variables?

  • Put the variables in the question

  • $("#ctext"). val(xmlString); here with me it doesn’t work. q works is $("textarea#ctext").val(xmlString);

  • I put a function in the reply to exchange accented words for not accented to avoid error Result: error Internal Server Error 500 Internal Server Error

Show 4 more comments

3 answers

1


The code has 2 problems:

1 - The variables country and zip not defined in the code

2 - In function function CallAPI(page) { has only defined var image

    var image = result["results"][i]["poster_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w500/" + result["results"][i]["poster_path"];

remaining to define the other

var title = result["results"][i]["title"] == null ? "No information available" : "" + result["results"][i]["title"];
var poster = result["results"][i]["backdrop_path"] == null ? "Image/no-image.png" : ""+ "https://image.tmdb.org/t/p/w500/" + result["results"][i]["backdrop_path"];
var to = result["results"][i]["original_title"] == null ? "No information available" : ""+ result["results"][i]["original_title"];
var sinopse = result["results"][i]["overview"] == null ? "No information available" : "" + result["results"][i]["overview"];
var ano = result["results"][i]["release_date"] == null ? "No information available" : ""+ result["results"][i]["release_date"];

For the purpose of testing set the country and zip variables in the function function CallAPI(page) { thus

var country = "Falta_definir_country"; 
var zip = "Falta_definir_zip";
var title = result["results"][i]["title"] == null ? "No information available" : "" + result["results"][i]["title"];
.......................
.......................

and see here working online

I realized that if you type accented words this error occurs Result: error Internal Server Error 500 Internal Server Error

To avoid this type of error occurs to put a function that changes the accented letters by letters without accents!!

Here is a suggestion:

put this script in your code

var letrasSemAcento = document.getElementById("searchInput");
    letrasSemAcento.addEventListener("input", function (event) {
    event.target.value = foldToASCII(event.target.value);
});

library

   <script src="seu_diretorio/fold-to-ascii.js"></script>

filing cabinet fold-to-ascii.js - github

see here working online

  • Leo Caracciolo, thanks for your attention. As text sends no problem. I don’t know if you noticed that inside xmlString there are variables: image, title, etc. With text sends, but the contents of these variables do not.

  • @Antoniooliveira put 2 variables

  • Leo Caracciolo. Very strange. Here it didn’t work. I will edit the post and put the whole code.

  • Leo Caracciolo didn’t work. I edited and includes the full code.

  • @Antoniooliveira country and zip variables are not defined

  • Refiz and it worked. Thank you!

Show 1 more comment

1

It can be something with your xml tags. In this case, try to do so:

 $("textarea#ctext").html(xmlString);

If it doesn’t work, post the result of:

console.log(xmlString);

1

Your mistake is on these lines:

var title = result["title"] == null ? "No information available" : "" + result["title"];
var image = result["poster_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w185/" + result["poster_path"];
var poster = result["backdrop_path"] == null ? "Image/no-image.png" : ""+ "https://image.tmdb.org/t/p/w500/" + result["backdrop_path"];
var to = result["original_title"] == null ? "No information available" : ""+ result["original_title"];
var sinopse = result["overview"] == null ? "No information available" : "" + result["overview"];
var ano = result["release_date"] == null ? "No information available" : ""+ result["release_date"];

When you define variables with var within a function, these variables will only exist within the function itself, and if you try to access them outside the function, it will generate error of "undefined variable".

So by putting these variables outside the function where they are on this line:

var xmlString = "<channel>" + "  <title><![CDATA[" + title + "|"+ to + "(" + ano + ")]]></title>" + "  <logo_30x30><![CDATA[" + image + "]]></logo_30x30>" + "  <description><![CDATA[<center><img height=\"254\" width=\"200\" src=\"" + poster + "\"</img><br>"+ sin +"</center>]]></description>" + "  <stream_url><![CDATA[" + escape(country) + "]]></stream_url>" + "  <subtitle><![CDATA[" + escape(zip) + "]]></subtitle>" + "</channel>";

will generate error and nothing will happen.

If you open the browser console (F12), you will see several errors from guy title is not defined, image is not defined...

Solution

Remove all the var variables, so they are accessible in other parts of the code (learn more about global variables at this link):

title = result["title"] == null ? "No information available" : "" + result["title"];
image = result["poster_path"] == null ? "Image/no-image.png" : "https://image.tmdb.org/t/p/w185/" + result["poster_path"];
poster = result["backdrop_path"] == null ? "Image/no-image.png" : ""+ "https://image.tmdb.org/t/p/w500/" + result["backdrop_path"];
to = result["original_title"] == null ? "No information available" : ""+ result["original_title"];
sinopse = result["overview"] == null ? "No information available" : "" + result["overview"];
ano = result["release_date"] == null ? "No information available" : ""+ result["release_date"];

EDIT

Not to mention the variables country and zip do not exist in the code (at least not posted in the question).

  • Does not work - Functional example :D missing see your http://kithomepage.com/sos/dvd.htmlsolution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.