receive undefined value in hidden input
return Response::make($this->filepond->getServerIdFromPath($filePath), 200, [
'Content-Type' => 'text/plain',
]);
HTTP/1.0 200 OK
Cache-Control: no-cache, private
Content-Type: text/plain
Date: Mon, 25 May 2020 11:01:01 GMT
eyJpdiI6Ik1wWEY0UmNSNlRJR.....==
response generated correct but in filepond hidden receive undefined
<input type="hidden" name="filepond" value="undefined">
this is my server setting
FilePond.setOptions({
server: {
url: 'http://localhost/gadmin/public/filepond/api',
timeout: 7000,
process: {
url: '/process',
method: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
onload: (response) => response.key,
onerror: (response) => response.data,
ondata: (formData) => {
return formData;
}
},
}
});
The onload function is only needed if for example your server returns a JSON string and you need to select a certain property from it. In your situation the process end point returns a text/plain response with an id, this allows FilePond to automatically use the returned id as the file id. So that's why the onload function isn't needed.
See: https://pqina.nl/filepond/docs/patterns/api/server/#process
server returns unique location id 12345 in text/plain response
Related
I want to cache response returned from server using etags. Below is my java based configuration:
#Bean
public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() {
FilterRegistrationBean<ShallowEtagHeaderFilter> filterRegistrationBean = new FilterRegistrationBean<>(
new ShallowEtagHeaderFilter());
filterRegistrationBean.addUrlPatterns("/endpoint");
filterRegistrationBean.setName("etagFilter");
return filterRegistrationBean;
}
Controller:
#GetMapping("/endpoint")
public ResponseEntity<WrappedList> getList(
#RequestHeader(value = HttpHeaders.IF_NONE_MATCH, required = false) String inm,
#RequestParam int page) {
System.out.println(inm);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(0,TimeUnit.SECONDS).cachePrivate().mustRevalidate())
.body(service.getList(page));
}
I send requests with axios:
Scenario that works (endpoint returns status 304 if resource is not modified):
var etag = '';
document.getElementById("someBtn").addEventListener('click', (event) => {
event.preventDefault();
axios({
method: 'get',
url: 'http://localhost:8080/endpoint',
params: {
page: 1,
},
headers: {
'If-None-Match': etag
}
})
.then(function (response) {
etag=response.headers.etag;
});
});
In this case I store etag in variable and after second request I get status 304. However, storing etags is not something I want to do.
Scenario that doesn't work, but it should(server returns status 200 each time)
document.getElementById("someBtn").addEventListener('click', (event) => {
event.preventDefault();
axios({
method: 'get',
url: 'http://localhost:8080/endpoint',
params: {
page: 1,
}
})
.then(function (response) {
etag=response.headers.etag;
});
});
First request: 'If-None-Match' header is not set.
First repsonse: etag header is present.
Second request: 'If-None-Match' header is set with exact same value from first response.
Second response: etag header is present and has the same value as first response etag, however status is 200 and whole response is present. There's also no information that response body was taken from cache.
What am I missing here?
I have tried many different ways but to no avail
API Spec - https://developers.facebook.com/docs/graph-api/reference/page/videos/
Param - content_tags ( list ) --> is what required
Below is my form data that is being posted
const formData = {
file_url: postOptions.filepath,
title: postOptions.title,
description: postOptions.description,
content_tags: ['tags', 'hello', 'hi']
};
HTTP Request Options
const options = {
url: https://graph-video.facebook.com/v9.0/${pageId}/videos?access_token=${accessToken},
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
formData,
};
Error response returned.
{"error":
{
"message":"(#100) Param content_tags[0] must be a valid ID string (e.g., \"123\")",
"type":"OAuthException",
"code":100,
"fbtrace_id":"ANoCbTSnh4uL960SjyE6XBV"
}
}
As per documentation, seems it has to be not just any string but NUMBER string which are predefined IDs of the tag list<numeric string>
From documentation
Tags that describe the contents of the video. Use search endpoint with type=adinterest to get possible IDs.
Example:
~~~~
/search?type=adinterest&q=couscous
~~~~
Here's full path of the above example shown by facebook, how you can get some IDs:
https://graph.facebook.com/search?type=adinterest&q="home"&limit =10&access_token={{access_token}}
I would like to a check for max-age so I remove items from cache when they get old, but I can't get my own header back for some reason.
export function cacheResponse(url, response) {
caches.open('my-cache').then(function(cache) {
cache.put(url, new Response(JSON.stringify(response), {
headers: {
'Cache-Control': 'max-age=1',
'Content-Type': 'application/json;charset=UTF-8'
}
}));
});
}
cacheResponse('/hello', {hello: "world"})
I can see this working in the Application tab in chrome and I can see those 2 headers in the preview, but when I pull the item back out the headers object is null.
cache.match(url).then(async function(object) {
console.log(object.headers) // null
var body = await object.clone().json(); // {hello: "world"}
})
The object looks like this
object: Response
body: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: ""
type: "default"
url: ""
Seems like I should be able to lookup the headers from calling match() no?
That should work; you should be able to call response.headers.get('cache-control') to retrieve the value (assuming this is a same-origin response).
Here's a snippet of code that I just tested which worked when run in the JS console:
async function test() {
const constructedResponse = new Response('test', {
headers: {'cache-control': 'max-age=1'}
});
const cache = await caches.open('test');
cache.put('/test', constructedResponse);
const matchedResponse = await cache.match('/test');
console.log(`cache-control: ${matchedResponse.headers.get('cache-control')}`);
}
Trying to create a switch for a global session variable the ajax call never returns "success" nor "error".
The actions are called and the Session keys are set, but the success/error functions are never fired.
It is weird because I use the same structure with other calls to replace divs and it works.
Javascript
doesn't work
function SwitchHelpMode() {
debugger;
var helpmode = true;
$.ajax({
type: 'GET',
url: '/Session/GetSessionKey',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { key: "helpmode" },
sucess: function (data) {
alert(data);
//debugger;
//var ok = data.success;
//if (ok) {
// var algo = data.value;
// alert(algo);
// helpmode = !algo;
//}
},
error: function (xhr) {
//debugger;
alert(xhr);
alert('ERROR::SetSessionKey!' + xhr.responseText);
}
});
helpmode = false;
$.ajax({
type: 'GET',
url: '/Session/SetSessionKey',
data: { key: "helpmode", value: helpmode },
sucess: function (data) {
alert(data);
},
error: function (xhr) {
debugger;
alert('ERROR::SetSessionKey!' + xhr.responseText);
}
});
}
Controller
public ActionResult SetSessionKey(string key, string value)
{
Session[key] = value;
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
public ActionResult GetSessionKey(string key)
{
if(Session[key] != null)
{
var value = Session[key];
return Json(new { success = true, data = value }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
Javascript works
function FilterInfoByFlightsCallback(values) {
//debugger;
var data = JSON.stringify(values);
var url = '/Campaign/FilterInfoByFlights';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
$('#infoList').html(result);
},
error: function (result) {
// handle errors
location.href = "/MindMonitor/"
}
});
}
Responses from inspector
http://localhost:50518/Session/GetSessionKey?key=helpmode
{"success":true,"data":"false"}
http://localhost:50518/Session/SetSessionKey?key=helpmode&value=false
{"success":true}
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?
UzpcVlNTb3VyY2VcUHJvamVrdGVcTU1JXGJmdWVudGVzXE1NSVxNaW5kc2hhcmUuTU1JXE1NSVxTZXNzaW9uXEdldFNlc3Npb25LZXk=?=
Persistent-Auth: true
X-Powered-By: ASP.NET
WWW-Authenticate: Negotiate oRswGaADCgEAoxIEEAEAAABDh+CIwTbjqQAAAAA=
Date: Tue, 07 Jul 2015 12:45:03 GMT
Content-Length: 31
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?
UzpcVlNTb3VyY2VcUHJvamVrdGVcTU1JXGJmdWVudGVzXE1NSVxNaW5kc2hhcmUuTU1JXE1NSVxTZXNzaW9uXFNldFNlc3Npb25LZXk=?=
Persistent-Auth: true
X-Powered-By: ASP.NET
WWW-Authenticate: Negotiate oRswGaADCgEAoxIEEAEAAABDh+CIwTbjqQAAAAA=
Date: Tue, 07 Jul 2015 12:45:03 GMT
Content-Length: 16
Any idea?
There is no extra c in - sucess: function (data) { because of this even though the response from server would be 200 OK but it will not fire traditional success because it is not able to find one.
It should be - success: function (data) {
AJAX can be difficult to troubleshoot if you don't have a lot of experience with it. The Developer Tools (or FireBug) available for all modern browsers are your friend. They make it much easier to see/understand what the server is returning as a response.
Since the request is using Ajax, the browser won't render any error pages that are returned.
Using Chrome (the other tools are similar and usually opened with CTRL + SHIFT + I or F12):
Open the Developer Tools pane with (CTRL + SHIFT + I).
Click the Network tab.
Click your page element to fire the click handler and send the Ajax request.
Find and click the network request in the Network tab (bottom-left).
The pane next to the network request has Tabs for 'Headers', 'Preview' and 'Response'.
Headers will show you the contents of the request (what got sent to the server).
Response will show you the content of the servers response. This might be JSON for a successful request or it might be HTML source for an error page if an error occured.
The Preview tab will render the servers Response (if possible). This is especially helpful if you receive an error response/page from the server since you won't have to wade through the raw HTML to find the error details.
If your AJAX call is failing, and your server returns a 500 error, you can always check your server logs or look at the Network > Preview tab to see the error detail that is returned. You can troubleshoot the error just as you would any traditional server response.
I have a simple ajax post to the server..
$(".invite-team-members-submit-btn").click(function() {
$.post("invite_team_member", { token: $("#token").val(), email: $("#email").val(), team: $("#team").val() })
.done(function (responseText) {
responseText = jQuery.parseJSON(responseText);
alert(responseText.response);
})
.fail(function (data) { alert("ERROR: " + data); })
.then(function () { alert("Something should happen."); });
});
The JSON returned looks like this...
{"response":"Person has been invited."}
My response header in the console looks like this...
Response Headers
Cache-Control max-age=0, private, must-revalidate
Connection close
Content-Type application/json; charset=utf-8
Date Wed, 22 May 2013 21:45:07 GMT
Etag "e5b5e12acbcc78372b2a861027b66c05"
Status 200 OK
Transfer-Encoding chunked
X-Request-Id d835ce021eff7733d67ebfcdd468bdf2
X-Runtime 0.007909
x-ua-compatible IE=Edge
In my console I see that it the server and returned the appropriate text, but I don't receive an alert in my browser. I'm just out of idea's on what's wrong. Has jQuery updated something that I'm missing?
You are using $.post incorrectly. You mean to use $.ajax and specify the type: "post" property.
$.post's first argument is the URL. In your case it's an object. I think that perhaps jQuery ends up using the current page URL to make a request instead (which is why you see one), but I can't be sure. You could rewrite this as:
$.post("invite_team_member", {data: data})
.done(function (responseText) { alert(responseText); })
.fail(function (data) { alert("ERROR: " + data); });
use $.ajax() then set the type to "POST"
Try this code:
mydata = "name=Jon&location=USA";
$.ajax({
type : 'POST',
url : 'myphp.php',
data : mydata
}).done(function(msg){
alert("DONE");
});