I would like to place the data from the $data variable (ajax.php) into my this.products[ ] (store.js) array in the javascript file. How would i do this? Bearing in mind they are in to seperate files, can i link the two?
The ajax.php file returns the database data in webpage as follows:
[{"0":"100001","SKU":"100001","1":"Key Ring","Name":"Key Ring","2":"Personalised Key Ring","Description":"Personalised Key Ring","3":"5","Price":"5"}
ajax.php
<?php
//database settings
$connect = mysqli_connect("localhost", "root", "", "wrightr");
$result = mysqli_query($connect, "select * from storeitems");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
store.js - originally this.product[ ] contained LocalStorage values, but i would like then to contain the values from the JSON file in order from the database table.
//----------------------------------------------------------------
// store (contains the products)
//
function store() {
this.products = [
//example new product (**field1**, **field2**, **field3**, etc...),
//example new product (**field1**, **field2**, **field3**, etc...),
}
store.prototype.getProduct = function (sku) {
for (var i = 0; i < this.products.length; i++) {
if (this.products[i].sku == sku)
return this.products[i];
}
return null;
}
-
You need to use AJAX. There's lots of examples onlineKevin Jantzer– Kevin Jantzer2017年03月07日 19:56:50 +00:00Commented Mar 7, 2017 at 19:56
1 Answer 1
You need to use AJAX. Here are two options (you would use this in your store.js file)
Using jQuery [docs]
$.get('ajax.php', function(resp){
// do something with resp
console.log(resp) // [{"0":"100001"...
})
Vanilla JavaScript [docs]
var req = new XMLHttpRequest();
req.addEventListener("load", function(){
if(req.status === 200) {
var resp = JSON.parse(req.response)
}
});
req.open("GET", "ajax.php");
req.send();
answered Mar 7, 2017 at 20:01
Kevin Jantzer
9,5112 gold badges31 silver badges53 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Razold1406
how would the data be place into the this.product[ ] array?
Kevin Jantzer
this.products = respRazold1406
so i tried this and it worked in the console, but its not reading in to the webpage as i expected as if i put it in manually
Kevin Jantzer
Sorry, guess you'll have to do more testing and research.
default