0

I have one problem with function in Javascript. When I insert text in textarea, function sends text to PHP script with AJAX, but I have problem when I insert two or three words, e.g Bosnia and Herzegovina then the script does not work. I used string replace :

    function provjeraDrzave(rijec) {
        rijec = rijec.replace(" ", "%20");
        $.ajax({
            type: "GET",
            url: "/drzava.php?slovo=" + randomslovo + "&drzava=" + rijec,
            success: function (odgovor) {
                $('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
            },
            error: function () {
                alert('Doslo je do pogreske');
            }
        });
    }

It should work as follows: When I insert Bosnia and Herzegovina that must change to Bosnia%20and%20Herzegovina but that change to Bosnia%20and Herzegovina and that does not work. Where is the problem ??

3 Answers 3

2

Why don't you use, for example, the native encodeURIComponent function, which is made for this?

Or, even better, let jQuery take care of URL encoding for you, using the data config param:

function provjeraDrzave(rijec) {
    $.ajax({
        type: "GET",
        data: {
            slovo: randomslovo,
            drzava: rijec
        },
        url: "/drzava.php",
        success: function (odgovor) {
            $('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
        },
        error: function () {
            alert('Doslo je do pogreske');
        }
     });
}
Sign up to request clarification or add additional context in comments.

Comments

2

jQuery $.ajax can receive url arguments via the data property and should automatically serialize it for you.

data

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests... Object must be Key/Value pairs...

$.ajax({
    type: 'GET',
    url: '/drzava.php'
    data : {
        'slovo' : randomslovo,
        'drzava' : rijec          //no need  to replace
    }
    success: function (returndata) {...},
    error: function () {...}
});

Comments

0

If you absolutely want to do this way try

rijec = rijec.replace(/\ /g, "%20");

but encodeURIComponent would be more appropriate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.