So I made a form using JavaScript that allows the user to put in how many ever inputs they want, but I ran into two problems. The first is that if they put extra fields and don't use them I run into errors on the other side since there is no input in those fields, and the second is that they cannot go back and edit the input if necessary. I am relatively new to JavaScript so I am not sure how to fix it, but if someone could help fix the input problem by auto deleting any empty fields that aren't used when submitted and add a protocol to be able to edit the input, I would be very grateful. Thanks so much for all your help and the code is below!
In your PHP you should always check to see that your request variables aren't empty before attempting to use them. The foreach loop should look more like this:
foreach ( $_POST['data']['address'] as $address ) {
if ( !empty( $address ) ) {
$addresses[$counter] = $address;
$counter++;
}
}
This will prevent the $addresses array from having empty fields.
As for the the users not being able to "go back" and edit input fields, it's not apparent from your code sample why that would be the case. If you mean you want your users to be able to change their data after it has been submitted and processed by the server you won't be able to do it with small modifications to your existing code. You'll need to add significantly more functionality to both the front and back ends.
There are few ways to handle this, but they involve re-structuring your application in a few ways.
Restrict the system so they can't add a new address until the previous ones are filled in.
Before submitting the form, run a sanity check and remove any blank addresses, renaming the fields as needed.
Convert the form to an Ajax object and submit that way. You'll need to rework the backend to make sure it accepts the JSON properly.
Make your PHP smarter and better with checking/validation of incoming data.
I would just check for an empty string, and continue if it is empty... trim the $address to weed out inputs that are just spaces.
foreach ($_POST['data']['address'] as $address){
if(empty(trim($address)) continue;
$addresses[$counter] = $address;
$counter++;
}
Related
I'm currently working on the following example found on http://www.webslesson.info/2017/07/live-add-edit-delete-datatables-records-using-php-ajax.html (entire code has been listed on this page) - everything works well for me apart from NewLine/Carriage return.
Whenever I press 'enter' key in the First Name or Last Name field, in order to add a new line, it basically won't recognize it.
In the source page file I added the code listed below after the: function fetch data() - please see the link: http://jsbin.com/yufovobinu/edit?html,output
but seems like it didn't help and carriage return/new line is still not recognized in Last Name field. I'm using Last Name field as a generic example, but it will happen to any text i would input to that field.
Additionally I'm including a video to visualise what happens when i type text in 'Last Name' field and then hit on 'enter' key and in order to insert data to mysql database (it sends data without new lines and returns it without new lines ): http://www.filedropper.com/issue
Please help! Thanks in advance!
$(document).ready(function() {
$('#user_data').keyup(function() {
$('#data2').html($(this).val().replace(/\r?\n/g, '<br />'));
Ok now I understood what are you trying to do exactly. You don't need at all the keyup event, also you can send the data by ajax as it is, and store it in the database with the new line character unchanged in the text.
For displaying correctly the stored values when you print the table you have to output from PHP:
echo nl2br(htmlentities($row['columnName']));
Where htmlentities prevents other HTML tags from being executed (XSS vulnerability) and then replaces in a smart way all kind of new lines (\r, \r\n, \n) with a <br> tag using the PHP's native optimized function nl2br.
I understand that if I use a checkbox value of name[], then I will receive a data array on the server (when using PHP), named 'name[]'. This has worked fine for me, but I'm running into some URL sizes that could cause issues with less robust IE browsers and all the encoded square braces are killing me in this area, easily causing the URL length to be at least 4-6 times longer than what it could possibly be, if another way were available. Is there a reliable method using javascript (jquery syntax even better) to intercept a checkbox forms values and convert them into something like this:
"&checkboxarray=1-23-45-13-67"
I figure that on the other end I can easily explode $_GET['checkboxarray'] into an actual array and go from there as I usually do with matching the selection array against the options array, etc... I just don't know if it's possible or how to create alter the submit process.
Side note, isn't passing "name[]" to a URL non-standards compliant anyways? Every browser I've used auto encodes it, but not Mozilla, however it seems to work fine.
EDIT: I need to create paginated links, which is why I'm using GET, instead of POST. This is also and industrial search, very comprehensive, lots of power user options.
UPDATE & Answer: I managed to come up with my own answer. For anyone else who wants to take advantage of $_GET's easy pagination workflow but you need to pass large data arrays and are worried about URL length, here's a simplistic way to compact it all down into one variable with dash separated values:
NOTE: I HIGHLY suggest you first make sure any dynamic arrays generated from queries start with 1 rather than 0 if your going to recheck values after submit, here's how, since 0 can be a real pain in the neck to work with in PHP conditional statements:
$your_array= array();
array_unshift($your_array,'');
unset($your_array[0]);
In your HTML code, set all checkbox input names to "something[]" and underneath this set of inputs, create a hidden input with the name "something", I suggest you make them match, but I suppose you could use another name, just make sure the hidden one is missing the square braces, also set the hidden input value to "":
<input type="text" name="something[]" value="1">
.....
<input type="text" name="something[]" value="20">
<input type="hidden" name="something" value="">
Javascript: NOTE, requires jquery... this grabs all the "something[]" input values and forms a dashed array while killing off "something[]" values from being submitted and only submitting "something".
$('#submitbutton').click(function(){
var searchIDs = $('input[name="something[]"]:checked').map(function(){
return $(this).val();
}).get();
var IDstring = searchIDs.toString();
var newvar = IDstring.replace(/,/g, '-');
$('input[name="something"]').val(newvar);
$('input[name="something[]"]:checkbox').prop("checked", false);
});
On the server side, simply explode the 'something' value from $_GET.
$somethingArray = explode('-',$_GET['something']);
There it is! Hope it helps someone in the future make their GET sent arrays more compact. Bonus: Avoids sending unsafe characters in the URL, Mozilla doesn't appear to auto encode square braces, at least not my version of it on Linux Mint ;)
Update:
I just implemented this code on a big country checkbox form with 284 possible selections. With my old code, even using 'c[]' as the name, my character count was around 3100 characters, with the new approach, my character count now rings in at just 1109. Worth the effort.
You can use POST instead of GET method.
GET has URL length limitations.
POST is useful in passing long data, e.g. an array in your case.
There is a default limit of POST method which is 2MB which is way higher than GET. If needed, it can easily be increased in php.ini file post_max_size 10MB.
Replace $_GET with $_POST in your script.
I have the server programmed in Cherrypy and I use also Mako Template.
And I have the variable dict (variable Mako that contain information's work) for working with the user( this I have to use Mako and JAvascript).
I have one problem that I can not pass the value's Mako to Javascript.
MAKO --->>> JAVASCRIPT and vicecersa Not can to pass.
When the user wants change the information, I need to use the form.
The information is for example the data is the identifying a person.
When I connect when the server localhost:8100 and I have in automatically dict on Url.
The user pushes the button's send.(submit) in case of change.
The server receipt the value in Javascript with the separator in Js and the old in MAko.
I have the problem for read and to convert the separator in Javascript.
It possible to change the string's submit's form While or before to sending?
I want to program the submit's form because I want to use the other delimiter(not & and =).
This is possible?
Now I write one example:
www.theuser.com/?Name=IBM&surname=PC
With if the function programmable while sending
www.thepc.com/?Name%24+IBM+%23%+Surname%24+PC
Repeat: when I sent the parameter, I not want this separator & or = and I want to use the others.
Separator
javascript Mako
= %24+
& +%23+
This Query String is the original for the my project:
http://localhost:8100/index2?json_data=demo_title%24+Demo+title+%23+proc1_script%24+script.sh+parameters+%23+proc1_chk_make%24+on+%23+outputp2_value%24++%23+demo_input_description%24+hola+mundo+%23+outputp4_visible%24+on+%23+outputp4_info%24++%23+inputdata1_max_pixels%24+1024000+%23+tag%24++%23+outputp1_id%24+nanana+%23+proc1_src_compresion%24+zip+%23+proc1_chk_cmake%24+off+%23+outputp3_description%24++%23+outputp3_value%24++%23+inputdata1_description%24+input+data+description+%23+inputp2_description%24+bien%3F+%23+inputp3_description%24+funciona+%23+proc1_cmake%24+-D+CMAKE_BUILD_TYPE%3Astring%3DRelease++%23+outputp2_visible%24+on+%23+outputp3_visible%24+on+%23+outputp1_type%24+header+%23+inputp1_type%24+text+%23+demo_params_description%24+va+bien+%23+outputp1_description%24++%23+inputdata1_type%24+image2d+%23+proc1_chk_script%24+off+%23+demo_result_description%24+win%3F+%23+outputp2_id%24+nanfdsvfa+%23+inputp1_description%24+funciona+%23+demo_wait_description%24+boh+%23+outputp4_description%24++%23+inputp2_type%24+integer+%23+inputp2_id%24+papapa+%23+outputp1_value%24++%23+outputp3_id%24+nananartrtrt+%23+inputp3_id%24+pepepe+%23+outputp3_type%24+header+%23+inputp3_visible%24++off+%23+outputp1_visible%24+on+%23+inputdata1_id%24+id_lsd+%23+outputp4_value%24++%23+inputp2_visible%24+on+%23+proc1_source%24+lsd-1.5.zip+%23+inputp3_value%24+si+%23+proc1_make%24+-j4+-C++%23+images_config_file%24+cfgmydemo.cfg+%23+outputp2_type%24+header+%23+proc1_subdir%24+xxx-1.5+%23+proc1_url%24+http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...+%23+inputdata1_image_depth%24+1x8i+%23+inputp1_id%24+popopo+%23+inputp1_value%24+si+%23+inputp2_value%24+no+%23+demo_data_filename%24+data_saved.cfg+%23+inputdata1_info%24+info_lsd+%23+outputp3_info%24++%23+inputdata1_image_format%24+.pgm+%23+outputp1_info%24++%23+inputdata1_compress%24+False+%23+inputp1_visible%24+on+%23+proc1_id%24+lsd+%23+outputp4_id%24+nana+%23+outputp2_description%24++%23+outputp4_type%24+header+%23+outputp2_info%24++%23+inputp3_type%24+float+%23+&tag=&inputp4_id=hi&inputp4_type=text&inputp4_description=hello+program&inputp4_value=no&inputp4_info=bol&inputp4_visible=on
For the moderator:
I read on the post https://stackoverflow.com/questions/13353539/how-to-change-how-the-url-is-encoded-when-a-form-is-submitted
But this was not interested in me.
P.s. The solution in Jquery or Javascript is equal for me.
Well I'm pretty sure your reasons for doing this don't justify doing it, but to answer the question, this is how you would change the tokens. I'm assuming jQuery, it's not entirely necessary but makes the code shorter.
HTML:
<form id="myform" action="myparser.php">
<input ...>
</form>
JavaScript:
$('#myform').submit(function(e){
e.preventDefault();
var q=$(this).attr('action'),f=this.elements,i;
for(i=0;i<f.length;++i){
q+=(i===0?'?':'+%23%+')+f[i].name+'%24'+f[i].value;
}
document.location.href=q;
return false;
});
That's slightly minified, so here's the gist. We begin by binding to the submit event, which we prevent (preventDefault and return false to be doubly sure), then get all the form's elements (this.elements) and iterate through them. By the end of the loop, q is a full URL which we want to submit to (using the action property and filling in all the names/values), so we just set the HREF to it and off we go. In this case to myparser.php.
Note that this does no character substitution whatsoever. You should make f[i].value safe in some way. From your question, it seems obvious that you don't want standard URL encoding, but you will need to do something to prevent bad characters being used.
Finally, this is just the sending side. You'll still need to do something clever on your server-side to actually read these values.
I connect up to my DB and a user submit their email address. This is stored in the DB. This is something I have grabbed from a turorial.
I'd like a user-unique code generated through JS on document load..
Format should be 6 digits in length and only using only A-Z and 0-9. ie: F4DRB6
Once that is done I'd need to store that unique code for that user in the DB.
The generator should check if the unique code exists in the DB, to ensure it is actually unique.
The trouble I am having is; I don't know how to create the unique code in the above format, checking if it is unique from the DB, and then storing it in the DB corresponding to that user. I'd assume another column to match the row somehow?
Thanks!
EDIT: I have attempted with this.. if there is any error please do point it out. Thanks
function genRandomString() {
$length = 5;
$characters = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
do {
$random_string = $this->genRandomString();
} while (mysql_num_rows(mysql_query("SELECT referralcode FROM ".coming_soon_emails." WHERE rand_string='{$random_string}'")));
$q = "INSERT INTO ".coming_soon_emails." SET referralcode='{$random_string}'";
$result = mysql_query($q);
why you need that to be created in client-side? Why can't you just create the code when the client submits the "final" form?
You can create this code randomly and you put the column that handles the code as unique. If you get a violation error, you generate another and try again.
Well, this is one of the ways to do...
Its simple math,
6^36 is large enough that creating a random id is mostly unique.
If you wanna be 100% sure use AJAX to check the generated ID in database and recreate if existing.
In a causal way, a simple walk-through would be:
write a function/SP in mysql :
First, generate a random code, as AbiusX said, depends on your user pool size, the new code is probably rarely used.
This will generate one Hex character for you and should get you started.
SELECT conv(FLOOR((RAND() * 16)),10,16);
Then you will need to check if this code has been used already.
`
SELECT * FROM usertable where code =
generatedcode
if so, generate a new one.
In a more robust setting, I always pre-generate the unique codes, and store them in a table "unused code" etc, so I can just grab any code off there and ensure it is unique and not used.
I hope somebody could help me out, I have no idea how to solve this problem.
so first, here's a php array: http://pastie.org/private/s99d8w7cbhjd2yucdijw
if i do print_r for mysql ID=1, it would be like that: http://pastie.org/private/5b9n86dnxlp96afpiwvjeg
now i'm pushing data to javascript:
var sec_0_f = [];
<?php foreach ($action_events["2nd"]["0"]["Free"] as $key => $value) : ?>
sec_0_f.push('<?php echo $value; ?>');
<?php endforeach ?
and so on..
Array contains messages, which varies each time, depends on mysql ID call. However, I would need to make some sort of a sequence. So message would display in #notice ( http://pastie.org/private/ge5ceqpihkbl82hs3ya3g ). And then each #notice would trigger an animation, so #notice animation1, #notice animation2 etc, depends on number of messages.
So there would be max 20 javascript arrays filled with data..
Here comes the needed "system", which is splitted into 2 sections. So the 1nd one would sequentaly display 2 "Free" and 1 "Corner" message in #notice and each will trigger the function, but not in the exact order, if you know what i mean. For each messages of "Free", "Corner" etc, I have premade functions. Names of functions are "Event"+"Team"+"Number".
Here's example: http://pastie.org/private/9j6rcf5f8lb5jmegbbqtog
(would actually need to put some callback there, when it's done..). But for each mysql ID, the same function would need to be grabbed.. So I'm thinking about creating additional field under each ID which some data and make sure that each time calls the same..
Sorry for a long message, but I've been trying to come up with something for days, without success. Does anybody have any idea how should I approach this? Did I take the right method to do this?
If I get it right, is this (click for demo) what are you trying to do?
It basically fills the actions in an array (like you do in php), then steps in that array, takes the first object and display it, then waits a second, then goes to step into the next object, and so on till all the actions are sequentially displayed.