jQuery ajax call to mvc Action doesn't fire success/error - javascript

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.

Related

Etag header not working, returns status 200 each time

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?

filepond receive undefined value in hidden input

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

Error sending AJAX POST request from local .html file to localhost:8080. CORS: "It does not have HTTP ok status."

I am getting an error when attempting to send a POST via AJAX from my own .html and .js files to localhost:8080. Upon submitting the request, the full error reads: "Access to XMLHttpRequest at 'http://localhost:8080/contact/new-message' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
CORS is already enabled on my browser, so access is automatically "Access-Control-Allow-Origin : *", so this is a different from that error.
Is there a way to include an "ok" status in the header? Or is the problem arising from elsewhere? Any help is greatly appreciated. Here are some code snippets:
My JavaScript, which runs as part of a form-submission:
function submitMessageAJAXCall(inputName, inputEmail, inputMessage, inputRegion) {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/contact/new-message',
data: JSON.stringify({
rbName: inputName,
rbEmail: inputEmail,
rbMessageText: inputMessage,
rbRegionId: inputRegion
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function() {
alert('Success!');
displayThankYouMessage();
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unfortunately that message did not go through.');
}
});
}
The Java code which recieves it:
#PostMapping("/new-message")
private ResponseEntity<HttpStatus> addNewMessage(#RequestBody RBNewMessage rbNewMessage) {
//validate message in service layer
boolean isRequestValid = contactService.validateNewMessageRB(rbNewMessage);
//is message is good, save it; else, return an error
if (isRequestValid == true) {
//create a new message
ContactMessage message = new ContactMessage();
//set message fields
message.setMyName(rbNewMessage.getRbName());
message.setMyEmail(rbNewMessage.getRbEmail());
message.setMessageText(rbNewMessage.getRbMessageText());
LocalDateTime timeOfMessage = LocalDateTime.now();
LocalDateTime timeWithoutNano = timeOfMessage.withNano(0);
message.setTimeStamp(timeWithoutNano);
int regionId = rbNewMessage.getRbRegionId();
Region region = regionService.getRegionById(regionId);
message.setRegion(region);
ContactStatus cs = contactStatService.getStatusById(1);
message.setContactStatus(cs);
//save message
contactService.save(message);
//return success
return new ResponseEntity<>(HttpStatus.OK);
} else {
//return error
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
And this is an example of a Postman request that is successful:
{
"rbName": "John Johnson",
"rbEmail" : "JohnJohnson#Email.com",
"rbMessageText" : "Hello there, this is my message.",
"rbRegionId" : 5
}
Add #CrossOrigin annotation (import org.springframework.web.bind.annotation.CrossOrigin) to the top of the controller class that is handling the request.

jQuery ajax always throws error

I build a page for mobiles, but i have problem when i send a POST with jQuery.ajax on my phone. It's works on my PC but not on my phone.
I have this code when i make the post request:
window.jQuery.ajax({
type: "POST",
url: "/Action/PageHandler.ashx?do=" + method,
cache: false,
data : postFormData,
dataType: "json",
success: function (data) {
DataHandler.GetResult(data, callBack);
},
error: function (oXhr, status, msg) {
callBack(false, msg);
}
});
The response when i use my phone is this:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Wed, 25 Dec 2013 17:20:00 GMT
p3p: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close
Content-Length: 69
{"ErrorMessage":"Wrong pasword or username!"}
When i run this code on my phone, the error function is called, status = error and msg is empty. I use jQuery mobile.
What's wrong with my code?

Ajax Success Fails to Initiate

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");
});

Categories