Edit 2 : even better, multiple values works
Actually, one simply has to give a "value" field that fills the box. No need for the "id/label" field, but value field is required. This is working :
foreach ($queries as $query)
{
$results[] = [
'zip' => $query->zip,
'value' => $query->commune,
'libelle' => $query->libelle,
'lieudit' => $query->lieudit
];
}
return Response::json($results);
Edit : here is the solution, thanks to Adyson's answer
The script should be json formatted and returning
An array of objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
(jQuery API documentation)
So, modifying the PHP script like this will work :
foreach ($queries as $query)
{
$results[] = [
'id' => $query->zip,
'value' => $query->commune,
];
}
return Response::json($results);
Original question
Using Jquery Autocomplete, querying a script.
The list shows as many rows as there are results (when I set my script to return X results, there are X rows as well in the list) :
But it doesn't fill the rows with the data. What could have gone wrong there ?
The data returned is some json :
Request URL:http://localhost:8000/search/autocomplete?term=750
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Response Headers
view source
Cache-Control:no-cache
Connection:close
Content-Type:application/json
Date:Tue, 15 Nov 2016 14:53:07 GMT
Host:localhost:8000
And here is the data :
[{"zip":"75004","commune":"PARIS 04","libelle":"PARIS","lieudit":""},
{"zip":"75005","commune":"PARIS 05","libelle":"PARIS","lieudit":""},
{"zip":"75003","commune":"PARIS 03","libelle":"PARIS","lieudit":""},
{"zip":"75006","commune":"PARIS 06","libelle":"PARIS","lieudit":""},
{"zip":"75008","commune":"PARIS 08","libelle":"PARIS","lieudit":""},
{"zip":"75012","commune":"PARIS 12","libelle":"PARIS","lieudit":""},
{"zip":"75015","commune":"PARIS 15","libelle":"PARIS","lieudit":""},
{"zip":"75016","commune":"PARIS 16","libelle":"PARIS","lieudit":""},
{"zip":"75017","commune":"PARIS 17","libelle":"PARIS","lieudit":""},
{"zip":"75010","commune":"PARIS 10","libelle":"PARIS","lieudit":""},
{"zip":"75018","commune":"PARIS 18","libelle":"PARIS","lieudit":""},
{"zip":"75001","commune":"PARIS 01","libelle":"PARIS","lieudit":""},
{"zip":"75009","commune":"PARIS 09","libelle":"PARIS","lieudit":""},
{"zip":"75014","commune":"PARIS 14","libelle":"PARIS","lieudit":""},
{"zip":"75002","commune":"PARIS 02","libelle":"PARIS","lieudit":""},
{"zip":"75007","commune":"PARIS 07","libelle":"PARIS","lieudit":""},
{"zip":"75011","commune":"PARIS 11","libelle":"PARIS","lieudit":""},
{"zip":"75013","commune":"PARIS 13","libelle":"PARIS","lieudit":""},
{"zip":"75019","commune":"PARIS 19","libelle":"PARIS","lieudit":""},
{"zip":"75020","commune":"PARIS 20","libelle":"PARIS","lieudit":""}]
Here is my JS :
$(function(){
$( "#fromzip" ).autocomplete({
source: "/search/autocomplete",
dataType: 'json',
minLength: 3,
});
});
The HTML :
<input
id="fromzip"
name="fromzip"
type="text"
class="form-control"
placeholder="69003"
pattern=".{5}"
title="5 numbers zip"
maxlength="5"
required >
And the PHP (Laravel Input, DB and Response facades) :
public function autocomplete(){
$term = Input::get('term');
$results = array();
$queries = DB::table('zips')
->where('zip', 'LIKE', $term.'%')
->orWhere('libelle', 'LIKE', $term.'%')
->take(30)->get();
foreach ($queries as $query)
{
$results[] = [ 'zip' => $query->zip,
'commune' => $query->commune,
'libelle' => $query->libelle,
'lieudit' => $query->lieudit];
}
return Response::json($results);
}
Have a look at http://api.jqueryui.com/autocomplete/#option-source. It states that the data must be in the format
[ { label: "Choice1", value: "value1" }, ... ]
Your sample data items don't have either of those properties (label or value).
You can modify your server-side script to output the right format, or if you can't/won't do that, you could use the source-as-a-function option in the plugin to write a function that transforms the data.
Related
I want to update all users in my database with an age value which I get from my request.
How do I manage this?
I somehow need the current value in the db and multiple it.
DB::table('customers')
->update([
'age' => DB::raw('column1 * 2'),
]);
Let's assume that the name of the field in your $request is multiple, you can iterate over your customer records and update each of them, applying your multiple value to their age:
// grab the `multiple` value from your request
$multiple = $request->get('multiple');
// get all your customers, loop over them and update each record
Customer::all()->each(function ($customer) use ($multiple) {
$customer->update(['age' => $customer->age * $multiple]);
});
If you want to use the QueryBuilder rather than Eloquent, then you can do the following:
DB::table('customers')->get()->each(function ($customer) use ($multiple) {
DB::table('customers')
->where('id', $customer->id)
->update(['age' => $customer->age * $multiple]);
});
Maybe you want to update a column based on a value as an input that is provided by the user.
Also notice I have used double quotation.
DB::table('your_table')
->where('some_column', $someValue)
->update(array(
'column1' => DB::raw("column1 * $your_input_variable")
));
To avoid the N+1 problem, I will advise you use the Eloquent's "WhereIn" method. The idea is that you build the list of items to update within the logic instead of hitting the db server N no of times in a loop as others suggested.
$itemTypes = [1, 2, 3, 4, 5]; //loop through your request payload and make this list.
$columns = [[
'name' => 'Ezugudor',
'age' => '18',
'rank' => 13
],[
'name' => 'Mathew',
'age' => '13',
'rank' => 1
]]; //loop through your request payload and make this list.
ItemTable::whereIn('item_id', $itemTypes)
->update($columns);
A cleaner way to do that
$items = Model::all();
$insertData = collect();
foreach ($items as $item)
{
$insertData->push([
'id' => $item['id'],
'otherstuff' => $item['name']),
'age' => $item['age'] * 2,
'more other stuff' => $item['itmPrice'],
]);
}
// chunks of 1000 insert into db
foreach ($insertData->chunk(1000) as $chunk)
{
DB::table('table_name')
->upsert(
$chunk->toArray(), // array of data that is going to be inserted or updated
['id'], // array of the column names that should be used for finding the updatable row
[ 'age'] // values that will be updated
);
}
upsert docs here
I have the following php array in a laravel variable called $salaries which is passed to a blade view:
array:4 [▼
2 => "£8, Per hour"
3 => "£10, Per hour"
23 => "Up to £10000, Per annum"
24 => "£10,000 - £15,000, Per annum"
]
In my blade view I have a drop which when changed, I want to load a select2 dropdown with the above options. Below is my code:
$(document).on("change", ".js-selector", function() {
var options = {!! json_encode($salaries) !!};
$("#salary_list").empty().select2({
data: options
});
})
However nothing is getting loaded into the dropdown. So I've narrowed it down to the options data for select2 not being in the correct format.
When I output options variable to console I'm getting the following object as opposed to a javascript array?
{2: "£8, Per hour", 3: "£10, Per hour", 23: "Up to £10000, Per annum", 24: "£10,000 - £15,000, Per annum"}
How do I transform the options into correct format for the select2 data?
You have to transform your data to the correct format, here you can see the correct data format:
var data = [
{
id: 2,
text: '£8, Per hour'
},
{
id: 3,
text: '£10, Per hour'
}
];
You could pass the array in the correct format to the view, something like:
$salaries = \App\Models\Salary::all(); // eloquent collection
$salaries = $salaries->map(function ($salary) {
return ['id' => $salary->id, 'text' => $salary->text];
})->toArray();
It would give result in something like this:
array:1 [▼
0 => array:2 [▼
"id" => 2
"text" => "£8, Per hour"
]
0 => array:2 [▼
"id" => 3
"text" => "£10, Per hour"
]
]
Or you can transform the array in javascript, the Select2 documentation explains here how you can transform your data:
Select2 requires that the id property is used to uniquely identify the
options that are displayed in the results list. If you use a property
other than id (like pk) to uniquely identify an option, you need to
map your old property to id before passing it to Select2.
If you cannot do this on your server or you are in a situation where
the API cannot be changed, you can do this in JavaScript before
passing it to Select2:
var data = $.map(yourArrayData, function (obj) {
obj.id = obj.id || obj.pk; // replace pk with your identifier
return obj;
});
In your case it would be something like this:
$(document).on("change", ".js-selector", function() {
var options = {!! json_encode($salaries) !!};
var data = $.map(options, function (value, key) {
return {id: key, text: value};
});
$("#salary_list").empty().select2({
data: data
});
})
exactly as Serhii said, simply extract the values from you associative array before encoding it:
$(document).on("change", ".js-selector", function() {
var options = {!! json_encode(array_values($salaries)) !!};
$("#salary_list").empty().select2({
data: options
});
})
Your array must have the structure like this:
[
[
'id' => 2,
'text' => "£8, Per hour"
],
[
'id' => 3,
'text' => "£10, Per hour"
],
[
'id' => 23,
'text' => "Up to £10000, Per annum"
],
[
'id' => 24,
'text' => "£10,000 - £15,000, Per annum"
],
]
https://select2.org/data-sources/arrays
I am building a Project management app using JavaScript and PHP.
Many of my JavaScript files will need access to a user list from my backend database. To increase performance or server hits I would like to build the user list with user data attached 1 time in PHP and print it to the screen as a JavaScript Object which my other JavaScript files can then access to get users data.
Assuming I have 20 users.
I need to have access to these user fields in ALL my JavaScript app/objects:
User name
User ID
User ACL role
User gravatar image URL
I am uncertain if I should generate a JavaScript Object with my PHP of the userlist or if it needs to be generated as JSON?
Also which ever it be, object or JSON, can you please show how it should be formatted to include multiple user records in the list and then how I would access a users data from my other JavaScript files assuming I have the user's ID.
So if I have user ID 1, I can call a function or object from my other JavaScript files and they will have access to all data for that user with ID 1 by getting it from the JavaScript that my PHP would print into the header of page.
Any help please?
Ideally I think something like being able to call:
var user = cureentJsObject.getUser(userId);
user.gravatarUrl // https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG
user.username // JasonDavis
user.role // admin
Being able to do something like that inside of my other JavaScript object/apps based on the data in the header of screen for userlist would be really nice but I am not certain how to do it?
UPDATE
I think this PHP would generate what I want. Just have to figure out the best way to access it in all of my objects in other JS files in the page
<?php
// PHP array
$userList = array(
array(
'id' => '1gdfgdfkn123423423',
'username' => 'JasonDavis',
'role' => 'admin',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '2gdfgdfkn123423423',
'username' => 'John Doe',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
array(
'id' => '3gdfgdfkn123423423',
'username' => 'Rick James',
'role' => 'user',
'gravatar' => 'https://www.gravatar.com/avatar/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG'
),
);
?>
var users = <?php echo json_encode($userList) ?>;
JSON output:
var users = [{
"id": "1gdfgdfkn123423423",
"username": "JasonDavis",
"role": "admin",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "2gdfgdfkn123423423",
"username": "John Doe",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}, {
"id": "3gdfgdfkn123423423",
"username": "Rick James",
"role": "user",
"gravatar": "https:\/\/www.gravatar.com\/avatar\/7ab1baf18a91ab4055923c5fd01d68a2?s=48&d=identicon&r=PG"
}];
UPDATE 2
I can now access the user from the above...
<script>
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
var users = <?php echo json_encode($userList) ?>;
var id = '2gdfgdfkn123423423';
var user = findById(users, id);
alert(user.gravatar);
</script>
I would say using JSON.
You can make a multidimensional array in PHP which encodes to JSON.
After you parse the JSON in JS you can access it like an object. E.g.:
myUserData[1].name
If you will always need all your users data, you can write an array of users in your PHP template as a JS array of objects. You don't need JSON. Something like:
<?php
$users_JS = array_map(function($user) {
return "{name: '{$user->name}', gravatar: '{$user->gravatar}'}";
}, $users)
?>
<head>
<title>PHP to JS</title>
<script>
window.MyApp.users = [
<?php echo implode(',', $users_JS); ?>
];
</script>
</head>
Now you can access your user list in window.MyApp.users.
If you need user data on demand (you don't know what data your app will need), you can do a little API in PHP that returns a user on JSON format:
<?php
$user = getUserFromId($_GET['id']);
header('Content-type: application/json');
echo json_encode($user);
And in JS:
$.ajax({
type: 'GET',
url: '/getUser.php', // URL of previuose PHP
data: {id: 3}
}).done(function(user3) {
// Do awesome things with user3
});
Obviously, this code needs validation, 404 if user id doesn't exists, etc, etc...
HTH!
You can use json_encode passing your user object to it.
The better way is to create a string with concatenating with '.' operator and in javascript use JSON.parse to make it a JSON object
I'm using this plugin called TagHandler. Link: http://ioncache.github.io/Tag-Handler/
May I know how can I assign tags from the database and not hard code to jquery? Example, to assign tags is
$("#array_tag_handler").tagHandler({
assignedTags: [ 'C', 'Perl', 'PHP' ],
availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
autocomplete: true
});
But I want it from mysql database.
They only gave example for available tags which is using the getData buildin function
$("#ajaxget_tag_handler").tagHandler({
getData: { id: 'user123', type: 'user' },
getURL: '/ajaxtest/get',
autocomplete: true
});
I need the php example. I don't know how to retrieve data in JSON format.
From the website..."By supplying a "getURL" for the tags to be retrieved via AJAX.
When using this method, the server must supply a JSON formatted array named "availableTags" and optionally an additional array named "assignedTags"."
On the clientside you want to load the tag handler like so:
$(document).ready(function()
{
$("#array_tag_handler").tagHandler({
dataType: 'json',
getURL: '/admin/tag/list',
autocomplete: true
});
});
This calls the '/admin/tag/list' route and expects json back.
On the server side you want to retrieve the list of tags and pass them back in json format.
$result = getTags(); // Returns eg array('tag1', 'tag2', 'tag3', etc)
Then build your array with the correct indices according to the Tag Handler documentation:
$data = array('availableTags' => $result);
Note that if you want to preload some tags (eg tag1 and tag2) then just modify the array above so that it looks like this:
$data = array('availableTags' => $result, 'assignedTags' => array('tag1', 'tag2'));
Then you need to json encode this array before returning it to the client:
return json_encode($data);
I tried posting a previous question, but i believe it was convoluted.
Basically, i was told "can you make the data come thru like this?" - keep in mind that this data is not derived from a form, but but by data that is driven via a search on the client side.
This is what is suppose to be sent to the server. So if you dumped the error_log, it would look this. This is all dynamic, so the object below will be that format BUT the data will change.
{
"matchedItems" :
[
{ "itemID1" :
{ "Cost" : "12",
"Size" : "small",
"Colors" : [ "blue", "red" ]
}
},
{ "itemdID2" :
{ "Cost" : "33",
"Size" : "large",
"Colors" : [ "yellow" ]
}
}
]
}
so, I run thru the some things on the page and bundle up the data and return data sets, thus the hashes within the array.
BUT for the life of me, I can't get anything to look good in the actual .ajax post. When I console.log the data out, it looks good. Its an array of hashes. etc... looks fine. BUT the following is what is actually sent when I look at the params of the request. So below is what I am actually sending. It did some weird merging and such, it looks like.
{
'matchedItems[0][itemid1][Color]' => 'Blue',
'matchedItems[0][itemid1][Size]' => 'small',
'matchedItems[0][itemid1][Cost]' => '33.90',
'matchedItems[1][itemid2][Color][]' => ['Silver'],
'matchedItems[1][itemid2][Size]' => 'small',
'matchedItems[1][itemid2][Cost]' => '44',
'matchedItems[2][itemid3][Color][]' => ['blue','Red'],
'matchedItems[2][itemid3][Size]' => 'large',
'matchedItems[2][itemid3][Cost]' => '23'
};
I tried to $.params the data, no luck. I tried various data settings in dataType, no luck. I am at a loss on how to format the data I send that mimics what I posted first.
Any ideas?
You should json_encode() your output from PHP
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
You can use jQuery to decode the json you got back from the ajax reply:
var json_reply = jQuery.parseJSON('{"a":1,"b":2,"c":3,"d":4,"e":5}');
alert( json_reply.a ); // alerts "1"