How to submit JQuery variable content to an html textarea?

2

I'm having a hard time sending the contents of a JS variable to a <textarea> (in a modal bootstrap) and with the XML formatting defined in the variable. Both JS and textarea are in the same html. The code is based on this (which only generates results in html): link

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 here's the textarea:

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

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

I have edited to include the complete code:

<!DOCTYPE html>

    Search in 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><scriptsrc="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>

    
asked by anonymous 02.12.2017 / 21:14

3 answers

1

The code has 2 problems:

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

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

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

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 test purposes, I defined the country and zip variables in the function CallAPI(page) { function in this way

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 running online

  

I noticed that typing accented words causes this error Result: error Internal Server Error 500 Internal Server Error

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

Here's 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>

file fold-to-ascii.js - github

See here working online

    
02.12.2017 / 21:59
1

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

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

If it does not work, post the result of:

console.log(xmlString);
    
02.12.2017 / 22:58
1

Your error is in 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, those variables will only exist inside the function itself, and if you try to access them outside the function, it will generate variable not defined .

So, by putting these variables out of the function where they are in 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 (F12) console, you will see various   type title is not defined , image is not defined ...

Solution

Remove all% of variables, so they will be accessible in other parts of the code (learn more about global variables 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

Without citing that the variables var and country do not exist in the code (at least in the posted question).

    
02.12.2017 / 23:10