0

I have adapted some code to populate drop-down selection boxes via MySQL queries, and my final 'result' needs to be appended to a new "search" URL.

var result = $("select#model option:selected").html();
$.post (location.href="advanced_search.php?" + "keywords=" + result, function(data){;

My problem is result includes spaces that I need to convert to +, so:

/advanced_search.php?keywords=2001-2004 Honda Civic TypeR

needs to read:

/advanced_search.php?keywords=2001-2004+Honda+Civic+TypeR

I've spent all evening looking for a solution, but I am having a very hard time finding something I can implement with my limited skills!

5
  • This seems to be what you are looking for, since other values which are not ASCII may cause problems as well I guess: stackoverflow.com/questions/332872/… Commented Oct 16, 2012 at 23:32
  • why are you setting location.href at the same time as trying to post to it? Commented Oct 16, 2012 at 23:36
  • What I don't understand is why you'd use $.post instead of $.get. Commented Oct 16, 2012 at 23:40
  • Methinks this is an XY Problem. Commented Oct 16, 2012 at 23:43
  • 2
    FYI, location.href = ... will blow away your POST data, so while you may think you are POSTing these parameters to the server, you are actually just redirecting and using GET parameters. Commented Oct 16, 2012 at 23:44

5 Answers 5

5

Use the data parameters of jQuery's AJAX methods and you won't need to escape anything - it'll all be done for you by jQuery.

Furthermore, this query is probably supposed to be a GET, rather than a POST. When you assign to location.href you cause a page reload of the new URL, rather than a true AJAX request.

var result = $("select#model option:selected").html();
$.get("advanced_search.php", {
     keywords: result
}, function() { ... });

IMHO there is almost never a good reason to create POST or GET parameters by hand - it's far simpler to use an object of key / value pairs.

Sign up to request clarification or add additional context in comments.

9 Comments

That's why I'm an amateur, I guess?! Thank you for your input anyway. Andy.
Sorry, @Alnitak, your answer is much better than mine, but I can still give you a +1.
@Kolink no worries, you just have to figure how to answer the question the OP really needed answering, and not the one he actually asked ;-) Heck, you still got accepted...
Sorry if I've sparked something off with my inadequate knowledge. It's kind of why I've muddled through it up to this point without posting on a technical forum in the first place! I have changed my snipped to 'get' now, but I am clueless as to why! This is my first attempt at anything like this, and I'm trying to learn. I don't know why everyone is so harsh on each other over 2 lines of code though! $.get (location.href="advanced_search_result.php?keywords=" + result.replace(/ /g,'+'), function(data){; Works perfectly for what I want to do. Andy.
To illustrate why there's a debate, see what happens if you search for This#breaks
|
1

You want encodeURIComponent which not only replaces spaces but anything else that may cause issues.

..."keywords=" + encodeURIComponent( result )

Comments

1
location.href="advanced_search.php?" + "keywords=" + result

should probably be

location.href="advanced_search.php?keywords=" + encodeURIComponent(result)

since if result contains a # then that will become part of the fragment instead of part of a query parameter. encodeURIComponent will properly escape a string so that your server returns result when you ask for the value of the "keywords" GET parameter.

As Mozilla's docs explain

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair.


If you have an already constructed URL, then

encodeURI('/advanced_search.php?keywords=2001-2004 Honda Civic TypeR')

== '/advanced_search.php?keywords=2001-2004%20Honda%20Civic%20TypeR'

The builtin encodeURI function takes a string and replaces all characters that can't appear in a URL with the %-encoded equivalent.

Encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Any server should treat %20 in a URL as equivalent to + except that %20 works outside the path part of the URL.

If for some reason, you really need +, then after encodeURI it should be safe to replace %20 with + thus.

var myUrl = '/advanced_search.php?keywords=2001-2004 Honda Civic TypeR';
encodeURI(myUrl).replace(/%20/g, '+')

6 Comments

@cwolves, I edited my post to make it clear when encodeURI is appropriate and when encodeURIComponent.
this is all unnecessarily complicated - $.post has a means to automatically escape parameters - the OP should use it!
@Alnitak, If you write an answer that explains $.post, I'll be happy to upvote. If the user is posting, they shouldn't be passing GET parameters.
@MikeSamuel in my answer I've left the script using $.post, but the parameters will end up in the message body, not at GET parameters.
@Alnitak, Apologies. I didn't see your answer earlier. I'm still unclear as to whether the user wants to GET or POST so I'll leave this answer here in the meantime.
|
1

I would suggest you revisit your code just slightly, as POSTing data but just sending the information over the QueryString (everything after the ? in the URL) is missing the point just a little.

You should be sending your keywords in an object, like so:

var result = $("select#model option:selected").html();
$.post("advanced_search.php", { keywords: result }, function(data){
    // success callback code goes here
});

If your PHP looks for the $_POST['keywords'], you should find your data in there when the $post is executed by jQuery.

Sending it across the QueryString is not undoable, but in that case you really should be doing something along the lines of:

var result = $("select#model option:selected").html();
$.get("advanced_search.php", 
    { keywords: result }, 
    function(data){
        // success callback code goes here
    });

However, you should get used to POSTing data properly, as sending data over the querystring is both unsecure and prone to issues due to encoding and URL length limits.

Also, this begs the question: Why are you encoding the HTML from within the tag? Why are you not simply putting a simple key in your , like this:

<select id="model">
    <option value="key1">2001-2004 Honda Civic TypeR</option>
    <option value="key2">2005-2008 Honda Civic TypeR</option>
    <option value="key3">2009-2012 Honda Civic TypeR</option>
    <option value="key4">2013-2015 Honda Civic TypeR</option>
</select>

var result = $("select#model option:selected").val();
$.post("advanced_search.php", { keywords: result }, function(data){
    // success callback code goes here
});

Should be simpler to run the query, as well, considering you can have your values shortened and not require any mucking around with encoding/decoding values, unless you don't have keys for each select option, in which case, I guess I understand the approach you're taking.

2 Comments

even with $.get() he should use a key/value object instead of a manually constructed query string.
The <option></option> part is not hard coded. (Is that the correct term?) The option tags are populated according to the data queried from the database. The next drop-down section box is then dependant on the parent category of the previous box. The last box lists all my items by their "item description" in the database table. I am using that text description to append to the search result page. Very crude, I am sure. But it works, and that's what I need! I have all the time in the world to work on it and refine it, but I just need it working for now. Thank you for your input. Andy.
-3

Just .replace(/ /g,'+') it, although I must admit I'm confused as to what your code is doing exactly.

13 Comments

@cwolves, there's a difference between doing what's right, and doing what the OP asks for. See the XY Problem as a good example of when not to answer the question.
@cwolves, "this answer is not useful" (as per the [title] on the down arrow). I think an answer such as this one that doesn't fix the problem, but only the symptoms is not useful. Obviously you feel differently.
This answer will only send the OP further down the wrong path. It only takes a little insight to recognize the actual problem presented here, this does not fix it... and now it's been accepted (shakes head...).
@user1742819 it didn't fix your problem - it merely masked the symptoms.
In agreement with all the others, here. This is the worst sort of monkeypatching. @user1742819, you need to take a hard look at all the other suggestions, as getting it wrong now will only cause you hours of rework in the future if you don't learn better practices, now.
|

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.