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.
Related
Let's say i want to open a PHP page and without another request, pass some JSON data directly to the browser, so it will be accessible to my Javascript functions.
I don't know the right way to do it, but what i do currently is something like this :
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
I put the data inside a invisible textarea and now the data inside 'mydata' textarea is accessible by JS doing something like this :
var myData = JSON.parse($('#mydata').val());
Although this works, somehow it does not seem to me the right way to do it... I know i could avoid to 'dirty' the html code by getting the data using Ajax after the page opens, but what i'm trying to do here is avoid more requests, so with only one request, everything will be accessible. Actually in my application i have about 5 textareas like these, so with only 1 request to the server i get all data needed.
Thanks
From PHP's perspective, there is no difference between this:
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
and this:
var myData = [{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}];
Both of the above take the form of:
[a string][the serialized object][a string]
Whether you're surrounding the values with HTML or with JavaScript, that surrounding decoration is just raw output strings as far as PHP is concerned. So there's no need to add the extra step of outputting the JSON to a form element and then using JavaScript to get the form element's value as a string and parse it back to an object. You can just emit the object itself directly to JavaScript code.
i have just begun using jquery datatables in my project and I do like it so far. I have many tables, sometimes 2-3 on a page. Rather than have to keep track of what initialization string I am using for a specific table and trying to remember what webpage its on, I have built an xml file to store all the initialization strings. I built some jquery functions to retrieve the strings on document ready but it never dawned on me how to actually inject the json into the method as a parameter.
If i was doing it manually you would call
selector.dataTables(json initializer string here);
Once I have that string how do I actually inject it into the method call? Or do I have to create that whole code line and inject it into my script?
If the json data comes in as something like this:
{"order": [[ 3, "desc" ]]}
You could use jquery to get the JSON via a HTTP GET request.
$.getJSON('somejson.json',function(data){
someSelector.dataTables(data)
});
Because you are using getJSON it will expect the JSON to be in that format and do the parsing for you.
Or if the JSON is available already(since you are using jquery you can use it to parse the JSON data just in case there may be a browser support issue since IE7 and below does not support JSON.parse.):
var options = $.parseJSON(someData);
someSelector.dataTables(options)
you can assign the json string to a variable...
var tableSettings = theJsonString;
selector.dataTables(tableSettings);
you may need to convert the string to an object first...
//javascript
var tableSettings = JSON.parse(theJsonString);
//jquery
var tableSettings = $.parseJSON(theJsonString);
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.
What are the steps for having jQuery UI's autocomplete use a database?
Specifically, how do I pass this script the entered value? How does autocomplete receive the script's json?
What I know:
1) Change the 'source option' to a script that queries the database.
2) ?
Current code:
$("#searchInput input").autocomplete({
source: "script_that_queries_the_db.php"
});
step 2? Have your php page mysql_query based on $_GET['term'] and return the results using json_encode.
Edit: Also, make sure the array you pass to json_encode is a flat array, otherwise jQueryUI won't read it as well as we'd like without writing more custom code.
The simplest way is to have your server return the results in json. See this example:
http://jqueryui.com/demos/autocomplete/#remote
Another way to do it is to make the request and parse the response yourself, by passing a function as source. See this example:
http://jqueryui.com/demos/autocomplete/#remote-with-cache
In either case the data passed to autocomplete must be an array of objects each with a label and a value.
I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.