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>";
?>
6
  • Still having issues? Still no & in the generated url? How do the current code look when generated? (that is not the server side code) Commented Aug 27, 2013 at 21:44
  • @NiKiZe @noam signatureload.php generates a <img> code with help from the parameters and here are the outputs from it after I've changed the select in the dropdown: <img src="signature.php?user=1type=6"> Commented Aug 28, 2013 at 8: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) Commented Aug 28, 2013 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 Commented Aug 28, 2013 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. Commented Aug 28, 2013 at 15:01

4 Answers 4

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();
});
Sign up to request clarification or add additional context in comments.

7 Comments

It won't create the parameter if it doesn't exist, will it?
@MagnusBurton Yes, it will. If it doesn't exist it will create it. If it does, it will just change it's value.
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());
@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.
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.
|
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();

3 Comments

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.
This was a really neat solution to the problem, thank you! The only problem left is the '&' which keeps dissappearing.
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)
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
    }
});

Comments

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>

5 Comments

It would work but upon change it'd just add another &type= to the url instead of replacing the current one.
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.
Oh okay, sorry then. Javascript isn't my top language as you might notice. I've tried your solution and the '&'-sign keeps dissappearing.
That's strange, maybe there is something in the sess_id? can you post an example baseUrl
Are you setting $_SESSION['sess_id'] somewhere in your code?

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.