I am trying to access the Shopify backend to update a customer's email, phone, and name via Ajax request.
I'm receiving a 404 error. while in postman and in google chrome the values are returned correctly and in postman, I am able to modify the values with PUT type.
my code:
let custFN = document.getElementById("customerFirstName").getAttribute("value") ;
let custLN = document.getElementById("customerLarstName").getAttribute("value") ;
let custEM = document.getElementById("customerEmail").getAttribute("value") ;
let custPH = document.getElementById("customerPhone").getAttribute("value") ;
let custID = document.getElementById("customerId").getAttribute("value") ;
let customerdata = {
"customer": {
"id": custID,
"first_name": custFN ,
"last_name": custLN,
"email": custEM,
"phone": custPH,
}
};
var customer_data_json = JSON.stringify(customerdata);
jQuery.cookie("session", null);
jQuery.ajax({
url:'https://{api key}:{api password}#{mysotre}.myshopify.com/admin/api/2022-04/customers/{customer_id}}.json',
type: 'PUT',
cache: false,
data: customer_data_json,
crossDomain: true,
dataType: "JSONP",
contentType: "application/json; charset=utf-8",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log("-------------------------------- <ERROR> --------------------------------");
console.log(response);
console.log("-------------------------------- </ERROR> --------------------------------");
}
});
I placed the values noted with {} above.
I have changed to JSONP from JSON to avoid and fix the CORS policy error.
keep in mind that the response readyState is 4.
P.S: As mentioned by Shopify documentation, I created a private app, and did all the steps required to CRUD using API in Shopify are done.
Related
I've checked the gizillion answers to this question and for some reason I can't get this to work.
I get the error:
401 (Unauthorized)
My route is an api route guarded.
My data:
let ajaxMainTemplate = {
'mainTemplate': mainTemplate,
'templateId': templateId,
'_token': accessToken,
}
My ajax call:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
data: {
_token: ajaxData._token,
ajaxData
},
success: function(response) {
console.log(response)
}
})
I've tried the above to test based on another response. I put the token outside of the ajaxData object. I get the same error. I've also attempted:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
headers: { 'X-CSRF-TOKEN': ajaxData._token },
data: ajaxData,
success: function(response) {
console.log(response)
}
})
Same.
I've also confirmed the token is there by adding a console.log Any ideas what I'm doing wrong with this?
My url was behind the api protected route so I had to do an ajax call to login into it via ajax.
The credentials are in a variable ajaxData.
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8000/api/login',
data: ajaxData,
success: function(response) {
shopifyToken = response.success.token;
getListProducts(shopifyToken);
}
});
With the shopify token generated from this login it worked.
I want to consume REST api and for that I have only url and the authentication token. I am using Jquery Ajax call for this purpose. I am getting error
Uncaught SyntaxError: Unexpected token :
Below is my code sample
$.ajax({
type: 'GET',
url: "https://xxxx",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
data: { "api_token": "xxxx", "api_token_secret": "xxx" },
success: function (data) {
console.log(data);
},
error: function (data) {
alert("error");
}
});
this code is in jsfile and that js file I am included in index.html page. on document ready I am calling this function.
If I didn't add the datatype : jsonp it is giving error of
XMLHttpRequest cannot load Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value
Can anyone please help me? What is the issue?
This line:
data: { "api_token": "xxxx", "api_token_secret": "xxx" },
should be this:
data: { api_token: "xxxx", api_token_secret: "xxx" },
You shouldn't quote the data keys.
I have this ajax POST code, which works directly on browser, but when i want to make a POST using the same data on Fiddler or SoapUI or using httpClient or HttpWebPost it doesn't work, always returns ERRROR. Below are the Ajax code and Fiddler. Thank you in advance.
$.ajax({
type: "POST",
url: "http://IP/address/post/something",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "text",
data:
{ message: 'testMessage', destination: '8888888888', campaign: 'UATTest', agent: 'TestingAgent'}
,
success: function (resp) {
if (resp != "ERROR") {
} else {
}
},
error: function (e) {
}
});
Update :
Does anybody know how to consume a REST API using FormParam ? how is it differ from JSON and XML ?
params:
#FormParam("destination"), #FormParam("message"), #FormParam("campaign"), #FormParam("agent")
I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:
$json = file_get_contents('php://input');
$data = json_decode($json,true);
I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:
[
{ "name": "John", "location": "Boston" },
{ "name": "Dave", "location": "Lancaster" }
]
Here is my jQuery ajax POST code (with hard coded data)
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
success:function(data) {
$('#save_message').html(data.message);
}
});
Here is the code in my Controller that receives the POST
public function store(Request $request)
{
dd($request->all());
}
But all I get is:
[]
Any ideas on how I can retreive my data?
You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType to contentType and add the processData option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());
$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.
Just a mention with jQuery v3.2.1 and Laravel 5.6.
Case 1: The JS object posted directly, like:
$.post("url", {name:'John'}, function( data ) {
});
Corresponding Laravel PHP code should be:
parse_str($request->getContent(),$data); //JSON will be parsed to object $data
Case 2: The JSON string posted, like:
$.post("url", JSON.stringify({name:'John'}), function( data ) {
});
Corresponding Laravel PHP code should be:
$data = json_decode($request->getContent(), true);
You can use getContent() method on Request object.
$request->getContent() //json as a string.
As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the
JSON data via the input method as long as the Content-Type header of
the request is properly set to application/json. You may even use
"dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all() should work.
My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all() in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.
Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.