getJSON is not calling the controller action - javascript

I don't know why this is happening since there are other functions in this page that use also getJSON and they do work. I have the following JavaScript Code
function openSOPNotesDialog() {
var url = '<%: Url.Action("GetSOPNote", "SalesOrder") %>';
var id = <%: Model.SodID %>;
$.getJSON(url, { sodId : id }, function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
});
}
and then I have this method on the SalesOrderController class
public JsonResult GetSOPNote(int sodId)
{
var service = new SodSrv();
var note = service.GetSOPNotes(sodId);
return Json(note, JsonRequestBehavior.AllowGet);
}
However, the method is never called in the debugger and data is returned as null (which is what I'd expect). As I said before there are other calls in this page and they are also doing GET requests so I don't know what may be the cause.

Sounds like the browser is pulling the data from the cache since it is a get request. Make sure to set no cache headers on the server if it is not meant to be cached.

Try adding an error handler to try to track down what the issue is:
$.ajax({
dataType: 'json',
url: url,
data: { sodId : id },
success: function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("oops: " + textStatus + ": " + jqXHR.responseText);
}
});

I suspect that the reason is that getJSON uses get method and controllers normally allowed to accept only post methods. It's ease to check using any browser firebug for example.

Related

Knockout binding not updating in html

I have been working on a project that uses knockout for databinding from javascript to html. I am also reading data from a PLC using ajax, the data from the ajax request will put into the knockout viewmodel and shown on the webpage. I am having some trouble with the updating of the data binding.
I searched on the internet for help but didn't find anything so far that helped me so I hope you can help me further.
I have setup the viewmodel as following inside a javascript file:
function AppViewModel() {
var self = this;
self.hmitags = ko.observableArray(groupDataValues);
self.Capa100 = ko.observable("Cap100");
self.Testvar = ko.observable(50);
}
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
And have the data binding in the html file:
<span data-bind="text: Testvar></span>
when I now load the html file I see the value 50 as defiened in the viewmodel, so that is working. But now I want to read a variable from my PLC using ajax that is done through a function inside that same javascript file. This is how the function looks:
function ReadVariable()// function for reading out individual variables
{
// list can contain only one variable
var HMIReadList = "&paths=MainInstance.Testvar"
data.length = 0; // get rid of the data from the last query
// issue the data request
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + BearerToken);
}
});
$.ajax({
type: "GET",
url: baseurl + "_pxc_api/api/variables?pathPrefix=Arp.Plc.Eclr/" + HMIReadList,
})
.done(function (data, status, jqXHR) {
viewModel.Testvar = data.variables[0].value;
console.log(viewModel.Testvar);
})
.fail(function (jqXHR, status, errorThrown) {
console.log("CreateSession Error: " + errorThrown);
console.log("Status: " + status);
console.dir(jqXHR);
alert("CreateSession $.ajax failed. Status: " + status);
});;
}
I am using a button in the html page to call this function. In the console I can see that it is reading a value from the PLC and that it is different that the initial value 50. But on the html page it is not changing. I am not sure why it isn't working I have been looking around for some solutions but have not found anything that is working.
A knockout observable is a function. In order to update the value of the observable, you need to invoke the function with the new value as follows:
viewModel.Testvar(data.variables[0].value)

Issues with make jQuery ajax call to a rest api

I am trying to use jquery ajax to make a post request that returns some response but it does not seem to work properly. Sometimes it works after a long wait, other times it does not work at all.This is my code.
<script type="text/javascript">
const id = $('#auth').val();
$("#set").click(function(){
$('.spinner-grow').show();
$.post("https://ravesandboxapi.flutterwave.com/v2/gpx/transactions/escrow/settle",
{
id: id,
secret_key: "FLWSECK-25*******************0628-X"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$('.spinner-grow').hide();
});
});
</script>
what might be the issue here?
The following is a complete example of a AJAX post is handled via jQuery. Just sharing it for reference.
var url = "api/path/to/your/controller";
var data = {};
data.id = id;
data.secret = 'your-secret';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (resultObject) {
console.log(resultObject);
},
error: function (err) {
console.log('An error occured');
}
});
If you are getting a 404 error, better check the path to the API. You can use a tool like Postman to validate your requests and then try implementing the same in code.
Also make sure that there is no CORS issue as from your code we cannot understand if your post is triggered from the same domain.

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Ajax POST never gets triggered, neither success nor error

What I am trying to do by using AJAX is when I click "Select" Button, all the related information coming from SQL DB will be assigned to the related labels.
The problem is that the AJAX code below($.ajax) never gets triggered (neither success nor error). alert(res[0]) is showing the true result on screen (so the clientid parameter is true).
This is from a WebApplication Project in Asp.Net
function BindClientSummaryForm() {
var skillsSelect = document.getElementById('<%= ddlSFoundClients.ClientID %>');
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
var res = selectedText.split('-');
document.getElementById('<%= hiddenClientID.ClientID %>').value = res[0];
alert(res[0]);
$.ajax({
type: "POST",
url: "Default.aspx/GetClientSummaryData",
contentType: "application/json;charset=utf-8",
data: "{ 'clientid': " + res[0] + "}",
dataType: "json",
success: function (data) {
alert("deneme");
document.getElementById('<%= lblClientNameSurnameD.ClientID %>').innerHTML = data.d.Firstname + " " + data.d.Lastname;
document.getElementById('<%= lblDateOpenedD.ClientID %>').innerHTML = data.d.DateFileOpened;
document.getElementById('<%= lblCityD.ClientID %>').innerHTML = data.d.City;
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error occured while filling ClientSummary part.");
}
});
return false;
}
<asp:Button runat="server" CssClass="btnSelect fieldButton" ID="btnSSelect" Text="Select" OnClientClick="return BindClientSummaryForm()"></asp:Button>
CodeBehind
[WebMethod]
public static MyClient GetClientSummaryData(String clientid) //GetData function
{
...
return client;
}
the debugger never drops to the GetClientSummaryData(clientid) method in c# as well.
I appreciate for your helps.
Try to change the value of content-type to text/plain on both, the client and the server, and use eval ('('+data+')') in the success function.
I know that this is not correct because the server response is json, but happened to me the same thing and I discovered (i don't know the reason) when you return the content as content-type: application/json on the server, jQuery does not call the success function.
What for do you specify POST as a request type? It seems like it will be more natural if you use GET (even method name tells us about that).
Also I'm not sure about this syntax data: "{ 'clientid': " + res[0] + "}" because I prefer to write scripts in separate files. Anyway, you can try to write data: { clientid: res[0] } instead

Why isn't this jquery.get function working?

I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".

Categories

Resources