Snipcart Return JSON - javascript

Any guidance or an example of exactly what I need to do to return the information below would be great.
I'm using js, jquery & HTML
I need to add this: Content-Type header is application/json
When the request comes I need to reply with the Json below
https://docs.snipcart.com/configuration/json-crawler#validating-the-request
When Snipcart makes the request to the URL, if your response
Content-Type header is application/json, we'll use our JSON validator
instead of the HTML one.
You must return us a JSON having the following properties.
{
"id": "20",
"price": 50.00,
"url": "https://snipcart.com/products/1.json"
}

I ended up doing this in PHP and getting the values using the URL.
<?php
header('Content-Type: application/json');
$myID = $_REQUEST['scene'];
$myPrice = $_REQUEST['price'];
$data = [
"id" => $myID,
"price" => $myPrice,
"url" => "https://yoursite.com/shop/test/snipcart.php"
];
echo json_encode( $data );
?>

Related

Structured data

Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>
Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);

Create JavaScript Object from PHP to hold user list with user data fields

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

How to extract parts of response of AJAX from PHP

Need some help here, i've been searching for related issues here but nothing seems to answer my problem. Ok so here how it goes
I have a simple search function that search through my database and I used an ajax to pass the data and get back the response and I manage to do that but my problem is that I can't seem to display the response the way I wanted to.
Here's my Ajax
$.ajax({
url: url, /// defined url
type: type, ///defined type
data: data, ///defined data
success: function(response){
//here I want to display something like
$('#display').html(the name of the employee);
}
});
Here's the ajax response
{
"employee": [{
"badgeno": "123 ",
"name": "John G. Doe",
"success": true
}]
}
{
"employee": [{
"badgeno": "456 ",
"name": "Jane G. Doe",
"success": true
}
I want to get the employee Name in there and display it in my page. How exactly am I gonna do that?
Thanks in advance. I'm still a newbie BTW
Here's the PHP
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
echo json_encode($data);
}
print_r($data);
//$this->load->view('admin/home', $data);
}
Try:
employee_name= data.employee[0].name;
$('#display').html(employee_name);
Link to fiffle:
https://jsfiddle.net/fcz53htw/
If you have more then one name, first add them to array, only then print then json_encode of the array.
Now its wont wont work because you printing twice.
Try change your php to this:
$getEmp = $this->Employee_model->search_emp($employee);
$count = count($getEmp);
if($getEmp){
for ($i=0; $i < $count; $i++) {
$data['employee'][$i] = array(
'badgeno' => $getEmp[$i]->BADGENO,
'name' => $getEmp[$i]->NAME,
'success' => true
);
//echo json_encode($data);
}
echo json_encode($data);
//$this->load->view('admin/home', $data);
}
On php you are write the results twice delete the printr only use json_encode

Sencha Touch : How to get the simple json file as response using JSONP?

I am trying to make a simple JSONP call to get a json file which is loaded on the remote server.
Here is my simple json file loaded on the server.
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
My Controller code which calls this file to get the data
Ext.data.JsonP.request(
{
url : 'http://xx.xx:8080/ThemeSelector.json',
callback : 'someCallback' ,
someCallback: function(success, result) {
var text = result.responseText;
var object = Ext.decode(text);
themeName = object['homePage'][0].themename;
}
});
I am getting the error "Uncaught SyntaxError: Unexpected token : "
I know that the response should be wrapped in the object but not able to make the exact correction in json file and my code. Any help please?
Thanks
JSONP requires that the response be in the form of a JavaScript function call, passing the actual JSON object as the parameter. Plain JSON won't (can't) work.
The exact details of how the function call should look (in particular, the function name) can vary, but usually it's a parameter added to the HTTP request. The server should construct the response based on that parameter's value.
To work with JsonP, your json response should contain the callback parameter you've sent. Without that, callback function will not get called and produces error since it does require that. In your case, you just have plain JSON file on server to serve. So you cant use JsonP directly with this file.
If you've some control over server, then you can write a script that can do this for you like -
<?php
header('Content-Type: text/javascript');
$response = file_get_contents('ThemeSelector.json');
echo $_GET['someCallback'] . '(' . $response .' );';
?>
Then received json response will look something like -
Ext.data.JsonP.callback2 (
{
"login": [
{
"themename": "NO",
"themeId": "1"
}
],
"homePage": [
{
"themename": "NO",
"themeId": "1"
}
],
"transactionDetails": [
{
"themename": "NO",
"themeId": "1"
}
]
}
)

jQuery getJSON Undefined Error

Alright, so I've done a bit of searching and trying with no luck. I'm hoping that someone here can point me in the right direction. I have a JSON feed that I'm working with, which is supposed to output a variety of data. Currently, it just sends back and "UNDEFINED" response for all variables. Here is the JS I'm using:
$("#loaduserdata").click(function(){
$("#userdata tbody").html("");
$.getJSON("trendFetch", function(data){
$.each(data.list, function(i, data){
var jsondata = data.action;
console.log (jsondata);
});
}
);
I'm not sure where the problem exists, because console isn't giving me any kind of errors or any reason to think that the JSON isn't formatted correctly: http://i.imgur.com/ySpdR.png
For whatever it's worth, here is the code I'm using to generate the JSON - maybe there is an issue on that end?
$curl = curl_init();
$url = 'http://api.site.com';
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
if($resp){
echo $resp;
header("Content-Type: application/json", true);
}
else {
echo 'Error - no response!';
}
curl_close($curl);
EDIT - including JSON output:
{
"status": "ok",
"list": {
"list_id": "2gz",
"title": "Test List",
"description": "description text...",
"image": [
"http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"http://cdn.list.ly/logos/default-list-image.png"
],
"views": 0,
"item_count": 1,
"curator_count": 1,
"follower_count": 1,
"listly_url": "http://api.list.ly/list/2gz-test-list",
"items": [
{
"item": {
"name": "Link 1",
"image": "http://t2.gstatic.com/images?q=tbn:ANd9GcTz6_4aV6oHsI2kgJRRoSFCTWbew5ChTeBrAmXYh4Gez2J7usm8nwMOsA",
"note": null,
"url": null,
"likes": 0,
"dislikes": 0
}
}
],
"suggested_items": []
}
}
echo $resp;
header("Content-Type: application/json", true);
should be:
header("Content-Type: application/json", true);
echo $resp;
You need to send HTTP headers before you output any content.
Set the header before any output
header("Content-Type: application/json", true);
echo $resp;
Musa was able to solve this for me, so in case someone Googles, the problem was that I was trying to use $.each when I didn't need to. Here is the correct code in case anyone is interested:
$.getJSON("trendFetch",function(data){
var tblRow =
"<tr>"
+"<td>"+data.list.list_id+"</td>"
+"<td>"+data.list.title+"</td>"
+"<td>"+data.list.description+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
}
);
It'd help if you provided the JSON response.
When I'm having these types of issues, I typically take a step back (in the code) and console.log() earlier. For example, console.log(data) within the function(data) {}.
I think -- from looking at the output -- that your problem is that list isn't actually a list. data.list is, in fact, an object. Therefore .each() will iterate over the individual items (like list_id, title, etc). None of these have a .action property.
I can't see any action property, so I can't make a solution suggestion. It's possible that it's within the list object -- but you're still treating it like an array (as if it's list: [{}, {}] rather than list: {}). In this case, you either need to fix the returned JSON or get rid of the $.each(), and just console.log(data.list.action).

Categories