I have been looking around for help trying to fix my old system of inserting returned search results from Amazon into a form.
The way it worked was I have a PHP based form for saving book information. The user typed in the ISBN and clicked a button, then a JavaScript program generated a signed request that returned the data in XML form. The JS program used an xslt file that converted it to a json type of results that then was inserted into the form fields. The reason it all stopped working is Amazon stopped supporting any xslt requests to their server. I have been able to substitute with googleapis, but I would rather use Amazon if possible.
EDIT:
I'm looking at it a new way. The original way will never work again, thanks to Amazon's changes. I have found a good start on this blog: http://anchetawern.github.io/blog/2013/02/10/getting-started-with-amazon-product-advertising-api/. That lead me to making this search.php:
require_once('amazon_product_api_class.php');
$public = //amazon public key here
$private = //amazon private/secret key here
$site = 'com'; //amazon region
$affiliate_id = //amazon affiliate id
$itemID = $_POST["ASIN"];
$amazon = $amazon = new AmazonProductAPI($public, $private, $site, $affiliate_id);
$single = array(
'Operation' => 'ItemLookup',
'ItemId' => $ASIN, //'0718177517'
'ResponseGroup' => 'Medium,ItemAttributes,OfferFull'
);
$result = $amazon->queryAmazon($single);
$json = json_encode($result);
$array = json_decode($json, true);
echo json_encode($result);
This works exactly like I need, except it's in php, so I can't use it to fill in the form blanks. The sequence of events needs to be like this:
User opens PHP generated HTML book entry form and enters ISBN# into text field and clicks search button -> ISBN# is sent to some search function -> search function returns results -> results sorted and entered back into the original book entry form -> user then continues to fill out form and saves it when done.
What I did was call search.php from a jquery script using this is a function:
$.post('search.php', {SRCHISBN: srchASIN}, function(response) {
var items = JSON.parse(response);
$.each(items.Items, function () {
$("#edit-field-book-title-und-0-asin").val(this.ASIN);
});
$('#example').html(response);
});
The $('#example').html(response); prints out (simplified version):
Array
(
[Items] => Array
(
[Item] => Array
(
[ASIN] => 0718177517
[ItemAttributes] => Array
(
[Author] => Mark Owen With Kevin Maurer
[Binding] => Hardcover
[EAN] => 9780718177515
[ISBN] => 0718177517
[Label] => PENGUIN BOOKS
[Manufacturer] => PENGUIN BOOKS
[ProductGroup] => Book
[ProductTypeName] => ABIS_BOOK
[PublicationDate] => 2012-01-01
[Publisher] => PENGUIN BOOKS
[Studio] => PENGUIN BOOKS
[Title] => No Easy Day
)
)
)
)
So far the only one I can get to work is $("#edit-field-book-title-und-0-asin").val(this.ASIN). I can't seem to figure out how to get further into the returned results. I need to pull out the Author, EAN, Title, etc., and insert them into my form. Maybe I don't even need the the $.each? Is there a simpler way to access the data directly from items = JSON.parse(response)?
I think I might have found an answer. I don't know if this is the best or most efficient way of doing it though.
$.post('search.php', {SRCHISBN: srchASIN}, function(response) {
var parsedJSON = $.parseJSON(response);
$("#edit-field-book-title-und-0-asin").val(parsedJSON.Items.Item.ASIN);
$("#edit-field-author-und-0-value").val(parsedJSON.Items.Item.ItemAttributes.Author);
$("#edit-title").val(parsedJSON.Items.Item.ItemAttributes.Title);
$("#edit-field-publisher-und-0-value").val(parsedJSON.Items.Item.ItemAttributes.Publisher);
});
This does take the items from the returned Amazon data in json format, then inserts them into the blanks on my book form, like #edit-title. It works, but like I said, I don't know if it the best way. The items I need out of the returned data will always be the same, so I don't think a for next, or each loop is needed. The list of form items is longer that what I'm showing here. I just cut it short to save space.
Related
Newbie question here.
There is data fetched from API (Django) and on the frontend (React) the user selects what he wants to have displayed. I'm struggling with passing the chosen data to filter/mapping - if i pass it as a variable then it is simply displayed literally
somecode ................
(data fetched)
let comparison = this.state.to /*(this is what user choses to have displayed via form)
let output =item.${ comparison }; /* this transforms it into the text I would like to pass into the mapping function) */
{items.filter(item => this.state.from === item.country)
.map(item => ({item.country} {item.country2} {output} ))}
*/ and here I would like to first filter the data based on the user choice (this.state.from) and then display the data chosen by user (output). Ouput displays the string literally but i would like it to actually map the data corresponding to the choice.
so it will display
Data
Data
item.(userchoice) (coming from {output})
Sorry if it is chaotic or obvious... :(
I want to submit a form using Ajax but I want it to be in an array, not serialized.
var form = $(this);
data: {data:form.serialize()};
gives me this in my PHP:
firstname=John&lastname=Doe&phone=123123412345
and I have to run this code in PHP to get it into the format I want:
parse_str($_POST['data'], $data);
Just seems super unnecessary and I would like to remove that step. How can I just pass the form in an array format? Thanks
// var form = $(this);
var form = this;
data: {data: Object.fromEntries(new FormData(form))}
then you will get the $_POST variable like this:
Array
(
[data] => Array
(
[firstname] => John
[lastname] => Doe
[phone] => 123123412345
)
)
You're over-engineering your Javascript.
In this line:
data: {data:form.serialize()};
you're creating an object with data as a key and your serialized data as its value. When you pass that to jQuery for an AJAX call it passes that in that form. Hence you're finding your serialize string in $_POST['data'] and you have to unpack it.
You should send your serialised data to jQuery without packing it in an object:
data: form.serialize()};
jQuery will recognise that and send the daya with the correct keys so that you can read it directly in $_POST['firstname'], $_POST['lastname'], etc.
For a site that I'm making, I wanted to have an additional feature which uses this plugin on GitHub called cratedigger that uses WebGL and Three.js. It is a 3D virtual crate that contains vinyl records, and simulates "crate digging" of albums. The plugin gets the data for the vinyl titles, artists, and covers through a string in JSON format that is parsed through JSON and stored in a const variable. The original code (index.js):
const data = JSON.parse('[{"title":"So What","artist":"Miles
Davis","cover":"http://cdn-
images.deezer.com/images/cover/63bf5fe5f15f69bfeb097139fc34f3d7/400x400-
000000-80-00.jpg","year":"2001","id":"SOBYBNV14607703ACA","hasSleeve":false},
{"title":"Stolen Moments","artist":"Oliver Nelson","cover":"http://cdn-
images.deezer.com/images/cover/99235a5fbe557590ccd62a2a152e4dbe/400x400-
000000-80-00.jpg","year":"1961","id":"SOCNMPH12B0B8064AA","hasSleeve":false},
{"title":"Theme for Maxine","artist":"Woody Shaw","cover":"http://cdn-
images.deezer.com/images/cover/bb937f1e1d57f7542a64c74b13c47900/400x400-
000000-80-00.jpg","year":"1998","id":"SOMLSGW131343841A7","hasSleeve":false}]
');
You can view the source code here. The above code is in line 3.
For my site though, I want the titles, artists, covers, etc. to come from my MySQL database. So what I did is when I click a button found in my main site, it will run the sql query of my database and then convert it into a .json file:
//getdatabase.php
<?php
include 'includes/session.php';
include 'includes/header.php';
$conn = $pdo->open();
$data = $conn->query("
SELECT name as title,
artist_name as artist,
concat('http://website.com/images/', photo) as cover,
year(date_created) as year,
id,
hasSleeve
from products
where category_id = '5';
")->fetchAll(PDO::FETCH_ASSOC);
foreach($data as &$row){
$row['hasSleeve'] = filter_var($row['hasSleeve'],
FILTER_VALIDATE_BOOLEAN);
}
$json_string = json_encode($data);
$file = 'cratedigger.js/src/htdocs/data.json';
file_put_contents($file, $json_string);
$pdo->close();
header('location: cratedigger.js/lib/index.html');
?>
Afterwards, it will be redirected to the index of the cratedigger plugin. To retrieve the data in the .json file, I used fetch API in the index.js file under the src folder of this plugin. So I replaced the original code in the plugin with this:
//replaced the long line of const data=JSON.parse('[{"title":...]'); with
this:
let data = [];
fetch('data.json').then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data); //outputs data from my database
return data;
});
console.log(data); //output is 0 or none
I use node.js to build and test this plugin, and when I test it with the code I used, the crate appears but with no records in it (a blank wooden crate). In the console, the log inside the fetch api does output the data from the json file, but the log outside the fetch outputs zero or none. I figured that it was that fetch is asynchronous, so the second console.log didn't output any data because it didn't wait for fetch to finish.
And that's my problem. I want to replace the original code that uses a string in JSON format, and replace it with data from my database. Some of the solutions that I came up with that didn't work are:
Use await and async - This is still asynchronous so it couldn't store my data in the variable.
XMLHttpRequest is mostly asynchronous too and its synchronous part is already deprecated.
Place fetch inside a function - My problem with this code is that the variable "data" used in the original code is used/called in other parts of the source files like these examples:
function fillInfoPanel(record) {
if (record.data.title) {
titleContainer.innerHTML = record.data.title;
}
}
//or this//
cratedigger.loadRecords(data, true, () => {
bindEvents();
});
So calling a function like myData(); to get the data from fetch wouldn't work as I need it to be inside the data variable. I'm not sure how I'm supposed to replace data variable used in other parts of the code with a function.
Any suggestions that might work? I don't necessarily need to use fetch to retrieve data. I'm more into HTML, PHP & CSS, and not that familiar with Javascript, so I'm stuck here. Node.JS was something that I've learned a week ago so the codes initially confused me. I've read articles and watched YouTube tutorials about javascript, json, etc. but they confused me more than help with my problem.
Ok i have an array setup to pull information from the game server, such as current map and player count, there is more that one server in the array, i need to display all the information in different sections on the site, such as i want to display the informaton from one server under a section then another in a different section, here is the code that i have
HTML To display the information
<li><div id="serverstats-loading">Please wait ...<br /></div>
<div id="serverstats-wrapper" style="display: none"></div>
<script type="text/javascript">
$(document).ready(function(){
$.post("query.php", {},
function (data) {
$('#serverstats-wrapper').html (data);
$('#serverstats-loading').hide();
$('#serverstats-wrapper').show ();
});
});
</script>
Array in php
$servers = array (array ('name' => 'DatGamer PvP Sever',
'ip' => '89.163.145.206',
'port' => 5000),
array ('name' => 'DatGamer RP Server',
'ip' => '89.163.145.206',
'port' => 19000));
$cachelifetime = 30;
$cachefile = './cache/servers.html';
$output = '#name#<br />#map# #players#/#maxplayers#<br /><br />';
?>
Screenshot of what it looks like on the site
http://imgur.com/n9EAZ6G#
The pvp sever stays, but the RP one needs to displayed under a different location.
Thanks for taking the time to read this, if you need any more information on this i will do my best to give it.
Thank you
-AcidzDesigns
Well if I got you correct you need to change the logic you use.
1) Return from server not links but json with properties and key "PvP"/"RP" value
2) use
some html template to render retuned json into proper section
or if you need to return html from server than return two arrays/dictionary for PvP and RP separately
When the website is loaded I want to do one ajax call to a PHP script that returns a json array of data (max 200 pieces), and store it in lawnchair. See http://brian.io/lawnchair/
I preload the data to not have to wait every time for PHP/MySQL to answer the ajax request. I want an autocomplete field that returns values while typing. The result comes from lawnchair so no more calls are made to the MySQL server.
So consider we have this dataset:
Apple, http://image.com/url/apple.jpg, $0,25
Pear, http://image.com/url/pear.jpg, $0,34
Pineapple, http://image.com/url/pineapple.jpg, $0,55
When the user types "p", all of the above needs to be shown. When the user types "app" only Apple and Pineapple are shown.
Thus I need to search through the dataset with a MySQL WHERE LIKE "%string%" equivalent code. I have looked on Brian's website website, but I see only exact match searches possible with query? See: http://brian.io/lawnchair/plugins/
Thanks in advance for any hint in the right direction.
A quick glance at the (relatively poor) documentation suggests, that the following would work:
var hits = [],
searchExpr = RegExp.escape(searchValue);
fruitStorage.where('/' + searchExpr + '/i.test(record.name)', function (record) {
hits.push(record);
});
// now do something with hits
Without looking deeper into the source code, this might work as well.
var hits = [],
searchExpr = new RegExp(RegExp.escape(searchValue), "i");
fruitStorage.where(
function (record) { return searchExpr.test(record.name); },
function (record) { hits.push(record); }
);
BTW, RegExp.escape() is taken from this answer.