AddSlahes Javascript / PHP - javascript

I have an HTML page with a form. When a user fills the input field, I search the database for a match. A list is displayed with possible matches and can be clicked, the possible match will then be copied to the input field. All works well for "normal" text, but when a record contains an ' the possible match is not copied to the input field. Although in the PHP script I did an "addslashes", but it seems that I can't pass the value to the Javascript.
The PHP code is this:
$SafedbCheck = addslashes($dbCheck_result[1]);
<li class='CheckListItem' onClick='n0400AddResults_Click(<?php echo( $jsCheck)?>,"<?php echo( $SafedbCheck)?>")'><?php echo($dbCheck_result[1])?></li>
Which results in the following HTML lines:
<li class='CheckListItem' onClick='n0400AddResults_Click(1,"Gabe\'s Brand New Brand")'>Gabe's Brand New Brand</li>
and
<li class='CheckListItem' onClick='n0400AddResults_Click(1,"Gabrie")'>Gabrie</li>
For testing the Javascript function:
function n0400AddResults_Click( jsCheck, SearchItem )
{ alert( SearchItem ); }
Which works fine for the second line, but not for the first line even though the var I'm passing to the Javascript is slashed. Do I need to do some extra slashthingy?

You have three layers of code here.
Some data
Some JavaScript
Some HTML
Let's start with the data:
$jsCheck
You need to escape the data in a fashion suitable for inserting in the JavaScript.
In PHP, this is best done using the json_encode function which, despite the name, will convert any basic data structure into a JavaScript literal (not just objects and arrays).
Note that this will also add the appropriate quote characters so you should not include them yourself.
json_encode($jsCheck);
You then need to escape the data in a fashion suitable for inserting into the HTML.
In PHP, this is best done using the htmlspecialchars function.
htmlspecialchars(json_encode($jsCheck));
Putting this with the rest of your code gives you:
<li class="CheckListItem" onClick="n0400AddResults_Click(<?php echo htmlspecialchars(json_encode($jsCheck)); ?>,<?php htmlspecialchars(json_encode($SafedbCheck)?;>)">
That said, the approach has a couple of issues.
List items are not interactive items. The user will only be able to activate them using a mouse or other pointing device … and you have an anchor already (which is an interactive element).
onclick attributes are not unobtrusive
You'd probably be better off with something that stores the data in the URL you pass to the href attribute or, failing that, in data-* attributes and then binding a JavaScript event handler with addEventListener.

Related

PHP, ajax, javascript, mysql: New Line/Carriage Return in a table not recognized

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.

Passing php array to javascript function from external php file

I'm working on autofilling an html form based on data from a sqlite database.
I'm using a modified version of the code from this site and in its basic feature it works as expected.
The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.
The script returns a string to update the input form:
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
The javascript function "fill" is as follows:
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
"#inputstring" is simply an input element.
What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html.
The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value.
I've tried:
$valuetopass = json_encode($query_result);
whithout
echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>';
and with quotes
echo ''.$query_result['text'].'';
And both fail.
I'm aware that similar question have been already asked 1, 2,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".
How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?
Or alternatively how can I rework the problem so that I don't need to do it at all?
Your JSON string is likely to contain ", so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.
Using PHP’s htmlspecialchars should be able to fix this in this instance.
In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.

How to read / get values from node's field using JavaScript in Drupal?

Let's say I have three field machine names in Drupal on a content type in Drupal:
company_color_schema , company_logo , and company_some_picture
I would like to retrieve the company_color_schema which will give me a plain text hex color code using JavaScript so that I can use it for a div background color.
Is there a way to access these values using JavaScript? I've looked at available documentation, but none seems to cover it.
You should use drupalSettings for this.
You can attach them in hook_node_view or similar depending on your needs
Actually, you don't need javascript to set div background. The better way is to use hook_preprocess_HOOK:
mymodule_preprocess_node(&$vars) {
$vars['background'] = $vars['node'][WHATEVER_VALUE];
}
Put this code into your module, clear caches and then you can use $background variable in your node.tpl.php
One way you can do this is to place JavaScript code in a view template file, at least part of it. So let's say you have a JavaScript row like this:
<?php $value_you_get_from_php = ... ; ?>
<script>
var bcgColor = <?php echo $value_you_get_from_php; ?>;
</script>
So you'll get your color field value from PHP and print it out inside inline JavaScript code, exactly at position where you defined your JavaScript variable value. Then you can use that JavaScript variable anywhere you need it.
Another way would be making an Ajax call with i.e. the node id as parameter, but the first option is easier, if it's acceptable.
Or, the easiest solution (inspired by Artreaktor's answer): Just shoot color directly from a template file - add the style tag attribute and set color from that. Artreaktor's solution may be more by rules, but mine is easier to implement.
Oh, yes. In drupal 8:
Create a view, build it's query to show your fields
Go to Admin/extend and enable "RESTful Web Services" module
Add REST export display to it
Create path for your REST export display
select format "serializer" with settings:
Force using fields - checked;
json - checked;
You're pretty done. Ajax the url in your script, parse the JSON and you have your fields in JS.

Other separators I want use (not & and =) when I submitting a form

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.

Need help with an AJAX workflow

Sorry I couldn't be more descriptive with the title, I will elaborate fully below:
I have a web application that I want to implement some AJAX functionality into. Currently, it is running ASP.NET 3.5 with VB.NET codebehind. My current "problem" is I want to dynamically be able to populate a DIV when a user clicks an item on a list. The list item currently contains a HttpUtility.UrlEncode() (ASP.NET) string of the content that should appear in the DIV.
Example:
<li onclick="setFAQ('The+maximum+number+of+digits+a+patient+account+number+can+contain+is+ten+(10).');">
What is the maximum number of digits a patient account number can contain?</li>
I can decode the string partially with the JavaScript function unescape() but it does not fully decode the string. I would much rather pass the JavaScript function the faq ID then somehow pull the information from the database where it originates.
I am 99% sure it is impossible to call an ASP function from within a JavaScript function, so I am kind of stumped. I am kind of new to AJAX/ASP.NET so this is a learning experience for me.
First of all, if you're pulling the questions from the db on page load you most likely have all the answers too, so just keep going with your current approach by jamming the answers into the page as your code sample is doing. Unless your FAQ list has thousands and thousands of questions, doing it the "AJAX way" by hitting the db on each click of the list item doesn't give you much here IMO. If it does have that many questions then a straight list is the wrong way to go anyway.
Secondly, two things to keep in mind re your approach:
you're placing html inside an html attribute
the attribute is specifying a javascript function to call
So you need to make sure your "answer" escapes both html and is valid js. By valid js I mean it can't have new lines and must escape quotes properly. For example, the following html - although valid html - won't fire the onclick and you'd just get a js syntax error:
<li onclick="setFAQ('This line's
multi line and has a single quote in it!')"
To account for these I would say HttpUtility.HtmlAttributeEncode in tandem with System.Web.Script.Serialization.JavaScriptSerializer is more appropriate to the markup you've shown.
JavaScriptSerializer json = new JavaScriptSerializer();
string answerString = "This line's\nmulti line and has a single quote in it!";
string onClickJS = String.Format("setFAQ({0})", json.Serialize(answerString));
string onClickAttr = HttpUtility.HtmlAttributeEncode(onClickJs);
Even better, use .NET's ListItem object and lose HtmlAttributeEncode altogether:
ListItem faqItem = new ListItem(questionString);
faqItem.Attributes.Add("onclick", String.Format("setFAQ({0})", json.Serialize(answerString)));
The html portion is escaped automatically for you, plus it's a lot cleaner.
As for your javascript, you don't have to decode anything in setFAQ(). Just take its argument and put it in into you "answer" div:
function setFAQ(answer) {
document.getElementById('answer').innerHTML = answer
}
I think just using HttpUtility.HtmlEncode may solve your problem. I'm not sure I follow completely though : \

Categories