5

I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.

The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.

Here're the problems I'm facing:

  1. If a dropdown/input hasn't been touched, I want to leave it out of the URL.
  2. If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
  3. When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").

Here's the code for the jQuery:

<script>
    var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";

    $(document).ready(function() {
        window.setTimeout(LoadSignature, 1500);
    });

    $("#signature_type").change(function() {
        url += "&type="+$(this).val();

        LoadSignature();
    });

    function LoadSignature()
    {
        $("#loadingsignature").css("display", "block");
        $('#loadsignature').delay(4750).load(url, function() {
            $("#loadingsignature").css("display", "none");
        });
    }
</script>

Here's the code where I load the image:

<div id="loadsignature">
    <div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>

I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.

Thank you for your help!

EDIT:

Here's the current code:

<script>
    var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";

    $(document).ready(function() {

        window.setTimeout(LoadSignature, 1500);

    });

    $("#signature_type").change(function() {
        url = updateQueryStringParameter(url, 'type', $(this).val());

        LoadSignature();
    });

    function LoadSignature()
    {
        $("#loadingsignature").css("display", "block");
        $('#loadsignature').delay(4750).load(url, function() {
            $("#loadingsignature").css("display", "none");
        });
    }

    function updateQueryStringParameter(uri, key, value)
    {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
        separator = uri.indexOf('?') !== -1 ? "&" : "?",
        returnUri = '';

        if (uri.match(re))
        {
            returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else
        {
            returnUri = uri + separator + key + "=" + value;
        }

        return returnUri;
    }
</script>

EDIT2:

Here's the code for signatureload.php

<?php
    $url = "signature.php?";

    $count = 0;
    foreach($_GET as $key => $value)
    {
        if($count > 0) $url .= "&";
        $url .= "{$key}={$value}";
    }

    echo "<img src='{$url}'></img>";
?>
Magnus
  • 340
  • 1
  • 5
  • 31
  • Still having issues? Still no & in the generated url? How do the current code look when generated? (that is not the server side code) – NiKiZe Aug 27 '13 at 21:44
  • @NiKiZe @noam signatureload.php generates a code with help from the parameters and here are the outputs from it after I've changed the select in the dropdown: `` – Magnus Aug 28 '13 at 08:45
  • But this is the .php script, how does it look when you do view source in the browser? (I want to know where the & is lost, is it when the page is generated or is it something else when the javascript is executed) – NiKiZe Aug 28 '13 at 12:36
  • It looks exactly like what I posted above. I guess it's when the javascript is executed or inside the php script. I've updated the question with the code in signatureload.php – Magnus Aug 28 '13 at 13:42
  • Would it not be more effective to set the img src with jquery? Other then that a `$count++;` in the foreach loop would probably fix this last issue of yours. – NiKiZe Aug 28 '13 at 15:01
  • Oh my god, thank you soo much. How could I miss that one? It's always the small details which mess code up. Thank you! – Magnus Aug 28 '13 at 16:07

4 Answers4

2

If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.

This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,

function updateQueryStringParameter(uri, key, value) {
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
        separator = uri.indexOf('?') !== -1 ? "&" : "?",
        returnUri = '';

    if (uri.match(re)) {
        returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        returnUri = uri + separator + key + "=" + value;
    }

    return returnUri;
}

$('#signature_type').change(function () {

    // Update the type param using said function
    url = updateQueryStringParameter(url, 'type', $(this).val());

    LoadSignature();
});
Community
  • 1
  • 1
federico-t
  • 11,157
  • 16
  • 58
  • 108
  • It won't create the parameter if it doesn't exist, will it? – Magnus Aug 26 '13 at 18:40
  • @MagnusBurton Yes, it will. If it doesn't exist it will create it. If it does, it will just change it's value. – federico-t Aug 26 '13 at 18:43
  • It doesn't seem like it's setting the url variable to the variable with the added parameter. Therefore, I modified it abit and now it still won't add the *&*-sign: url = updateQueryStringParameter(url, 'type', $(this).val()); – Magnus Aug 26 '13 at 18:48
  • @MagnusBurton Yes, I forgot to assign the value to the url variable. Also, I think the function had some errors. Check if it works with the updated version. – federico-t Aug 26 '13 at 18:54
  • I appreciate your help but the & still doesn't show up. Am I doing something weird or? Updated the question with what my current code looks like. – Magnus Aug 26 '13 at 19:10
  • @MagnusBurton Hmm that is strange. It is working for me http://jsfiddle.net/Jp68X/1/. – federico-t Aug 26 '13 at 19:15
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36282/discussion-between-magnus-burton-and-campari) – Magnus Aug 26 '13 at 19:32
1

Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example

var type= 'default_value';

    $("#signature_type").change(function() {        
        type = $(this).val();
    });

then using ajax call it like this (you could do this in your "change" event function):

$.ajax({
    type: 'GET',
    url:    'signatureload.php', 
    data: {
        user: <?php echo $_SESSION['sess_id']; ?>,
        type: type,
        ... put other variables here ...
    },
    success: function(answer){ 
        //load image to div here
    }
});
Dexa
  • 1,631
  • 9
  • 21
1

Maybe something like this:

<script>
    var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";

    $(document).ready(function() {
        window.setTimeout(function(){
            LoadSignature(baseUrl);
        }, 1500);
    });

    $("#signature_type").change(function() {
        var urlWithSelectedType = baseUrl + "&type="+$(this).val();
        LoadSignature(urlWithSelectedType);
    });

    function LoadSignature(urlToLoad)
    {
        $("#loadingsignature").css("display", "block");
        $('#loadsignature').delay(4750).load(urlToLoad, function() {
            $("#loadingsignature").css("display", "none");
        });
    }
</script>
noamtcohen
  • 3,992
  • 1
  • 17
  • 14
  • It would work but upon change it'd just add another *&type=* to the url instead of replacing the current one. – Magnus Aug 27 '13 at 13:39
  • Actually you wouldn't be adding/appending another &type= because you are not changing the baseUrl, the LoadSignature function will always receive a clean url that is the baseUrl plus the &type=, there is no accumulating concatenation. – noamtcohen Aug 27 '13 at 17:49
  • Oh okay, sorry then. Javascript isn't my top language as you might notice. I've tried your solution and the '&'-sign keeps dissappearing. – Magnus Aug 28 '13 at 08:43
  • That's strange, maybe there is something in the sess_id? can you post an example baseUrl – noamtcohen Aug 28 '13 at 09:56
  • Are you setting `$_SESSION['sess_id']` somewhere in your code? – noamtcohen Aug 29 '13 at 06:14
1

Here is a variant where all the data is keept in a separate javascript array

<script>
    var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
    var urlparams = {};

    $(document).ready(function() {
        window.setTimeout(LoadSignature, 1500);
    });

    $("#signature_type").change(function() {
        urlparams['type'] = $(this).val();

        LoadSignature();
    });

    function LoadSignature()
    {
        var gurl = baseurl; // there is always a ? so don't care about that.
        for (key in urlparams) {
            gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
        }

        $("#loadingsignature").css("display", "block");
        $('#loadsignature').delay(4750).load(gurl, function() {
            $("#loadingsignature").css("display", "none");
        });
    }
</script>

With this color or any other parameter could be added with urlparams['color'] = $(this).val();

NiKiZe
  • 955
  • 7
  • 19
  • If this still do not generate & on the correct place try using "\u0026" instead of '&'. But in that case there is something more to this that is the root issue. – NiKiZe Aug 27 '13 at 22:26
  • This was a really neat solution to the problem, thank you! The only problem left is the '&' which keeps dissappearing. – Magnus Aug 28 '13 at 08:41
  • And you have also tested with `gurl += "\u0026" + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);` instead ? (but please note that you should find the cause for why it disapears, even if it is out of scope of this question) – NiKiZe Aug 28 '13 at 12:38