[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

jQuery append() / remove

Posted on 2011-10-24
11
Medium Priority
?
516 Views
Last Modified: 2012-05-12
I currently have a dropdown box full of a country listing, to allow for multiple countries to be selected and thus submitted on the form I am using jQuery to add or remove a selected drop down item using the append or remove statement.  My current code is listed here:
                $('#addCountry').click(function(){
                    var selectedCountryID = $('#countrySelection option:selected').val();
                    var selectedCountryName = $('#countrySelection option:selected').text();
                    if(selectedCountryID != "" & $('#'+selectedCountryID).length==0){
                        $('#countrySelection').append("<span class=\"countryName\"><input id=\""+selectedCountryID+"\" type=\"hidden\" name=\"countrySelection["+
                            i+"]\" value=\""+selectedCountryName+"\"/>"+selectedCountryName+"<img class=\"removeCountry\" id=\""+selectedCountryID+"\" src=\"/img/icons/badge-circle-minus-16.png\" alt=\"Remove Country\"/></span>");
                    }
                    i++;
                });
                $('.removeCountry').live('click',function(){
                    $(this).parent().remove();
                });

Open in new window


My question is, this will break the input from the form if a user adds 2 countries, removes the first country, then adds another country creating an array not only missing element[1] but also having a duplicate element[2].  I am currently at a loss for how to resolve this and have an array which does not break for form submission so the PHP file can parse the data within the array using a while loop.  Any suggestions would be most welcome!
0
Comment
Question by:PhillipsPlastics
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 2

Expert Comment

by:jmgst116
ID: 37022234
Since there is no html can not really see what country selection is so I just made it a select
also so moved the append around to better see how works and changed hidden to text to see if insert remove working and so was easier to inspect element.

here is js fiddle should get you started
http://jsfiddle.net/KRpNC/2/

0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 total points
ID: 37023833
Whatever the client side of things produces and sends to the server in the request, you must validate the input on the server side.  One of the tools that is your best friend is the PHP function var_dump()
http://php.net/manual/en/function.var-dump.php

You can use var_dump($_REQUEST) to see the client variables that have been sent to the server.  Once you see the data, it should be obvious how to filter it.  So please add that statement to the action script, recreate the problem and post the output here.  Then we can begin to see whether we need to amend the action script or the jQuery stuff.  Thanks, ~Ray
0
 
LVL 9

Expert Comment

by:crazedsanity
ID: 37027647
There's some stuff you can do on the front end to make it simple for the user, but the bottom line (which Ray hit on) is that you'll have to validate the input once it hits the server.  If an array is getting sent to the server, just have it remove empty values, and use array_unique() [http://php.net/array_unique] to make sure there are no duplicates in there.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:PhillipsPlastics
ID: 37027983
So I can essentially ignore where the how the array is indexed and just deal with it on the PHP side of things?  Because it is a dropdown coming from a database there is not a lot of validation that must be made since it is also not going back into the database just into an email.  But using the var_dump() or array_unique() should solve the issue correct?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37028677
Let's be clear about this part: var_dump() does not solve any issue.  It's like checking your bank balance.  How you earn and spend is up to you -- the ATM just tells you the consequences of your choices.  Var_Dump() simply creates a visual representation of the internal variables so the programmer can resolve the issue through programming.  I am not sure whether array_unique() is in play or not.  I would need to use var_dump() on a collection of request variables to see if array_unique() was something I wanted to use.  For this reason professionals generally create test data sets and run them against every build of the software.
0
 
LVL 9

Expert Comment

by:crazedsanity
ID: 37029257
The most important aspect is the back-end (PHP script): make certain that the data is cleaned & validated there.  As long as that is done, it won't matter if the javascript isn't dealing with duplicates properly.

As far as var_dump()... that's not going to solve anything.  As Ray explained, var_dump() is a good way of seeing the data structure, but it has few real usages--most, if not all of them, are for debugging.
0
 

Author Comment

by:PhillipsPlastics
ID: 37030681
Okay so the output on the PHP side of things using the vardump() is:
array(2) { [0]=> string(9) "Country 3" [1]=> string(9) "Country 1" }

Open in new window


How do you access it on the PHP server side then?
0
 
LVL 9

Expert Comment

by:crazedsanity
ID: 37030723
I'm not exactly sure what you mean by "access it on the PHP server side"; wherever you put the var_dump() call is (I would think) where you would want to do filtering and validation.
0
 

Author Comment

by:PhillipsPlastics
ID: 37030741
Yes so now that I know how the javascript is being fed into the PHP file I can output each of the array elements but am not sure how to do so.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37030814
Did you apply var_dump() to $_REQUEST?  If so, you might want to stop work on this and hire a professional to help you.  What you have in the post at ID:37030681 is a numerically indexed array and that should not occur in a commonsense GET or POST request.

However if you applied var_dump() to one of the named elements of the $_REQUEST, it is a different matter.  Let's say what we are looking at with ID:37030681 is the output of something like this:

var_dump($_REQUEST["selectedCountryName"]);

Then you might use something like this to access each of the elements in the array.

foreach ($_REQUEST["selectedCountryName"] as $x)
{
    var_dump($x);
}
0
 
LVL 9

Accepted Solution

by:
crazedsanity earned 1000 total points
ID: 37030871
@Ray: the numerically-indexed array is probably being generated by Javascript, though I can't say for sure.

@PhillipsPlastics: just loop through the array:
foreach($_POST['nameOfArray'] as $index=>$value) 
{
    echo "Index #". $index .", value=". $value ."\n";
}

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question