1

I found the way to get query string from this question. But i cannot get the URL inside requested page via ajax.

Example:

<div class="result"></div>
<script>
    $(function() {
        $.ajax({
            url: 'ajax_inner.html',
            type: 'GET',
            data: 'somename=someval',
            dataType: 'html',
            success: function(data) {
                $('.result.).html(data);
            }
        });
    });
</script>

This is main.html page. And below is ajax_inner.html page.

<p>your query string is: <span class="qsval"></span>.</p>
<script>
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }// getParameterByName

    $(function() {
        $('.qsval').text(getParameterByName('somename'));
    });
</script>

I cannot get anything from query string passed to ajax page. I tried to alert(location); inside ajax page but it returns the main.html page.

How to get query string inside ajax page?

Community
  • 1
  • 1
vee
  • 4,506
  • 5
  • 44
  • 81

2 Answers2

2

You have to remember that using .html to inject <script> tags will make the script execute on the calling page, not the target page. You would need to get the server to change the content of ajax_inner.html depending on QueryString.

Then you have to ask yourself, why are you trying to execute the script on the target, rather than inside your success callback? Why not do this:

success: function(data) {
    $('.result').html(data).find(".qsval").text("someval");
}

Where "someval" can come from any local variable.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • I can't use .find after that because in my ajax_inner.html have to load data and set it to select box. To find select box with option[value="someval"] and make it selected with this method is not possible because once ajax_inner.html loaded .find inside success: works while js inside ajax_inner.html is not finish their work. However i will find the other way to change it. Thank you :) – vee Sep 26 '14 at 10:34
2

Basically the problem is that there is no "Ajax page" with a URL of its own, only some HTML content you load dynamically and insert into the other/only page. Your ajax_inner.html contents would have been in the same context had they been in the page from the beginning instead of loaded dynamically (though the contained script would obviously have executed sooner if on the page at load time). It has no scope of its own and location thus simply refers to the parent/only page's location property.

You might be confusing dynamically loading of HTML contents with <iframe>s, which have their own page scopes, so to speak.

Peter Herdenborg
  • 5,736
  • 1
  • 20
  • 21