How to do ajax between javascript and javascript - javascript

I need to do ajax to javascript and get a result by calling js function.
but I cannot get data.
I'm making TIZEN web application.
and I have web service on my server(asp).
I did ajax to my web but I got error.
As you can see, I Tried to debugging through console.log but any reasonable values not printed.
app.js (90) :getAlarmData()
app.js (153) :
$.ajax({
type: "POST"
, url: "serverIP/WebProject/WebContents/view/filename/function name"
, data: null
, contentType: "application/json; charset=utf-8"
, dataType: "json"
, async: false
, success: function (jSonResult) {
},
error: function (xhr, status, error) {
console.log(error + "\n" + status + "\n" + xhr.responseText);
}
});
app.js (90) :getAlarmData()
app.js (153) :

You are trying to do a function call on a file which is present on your server, you can't do that directly. You have to open a road on your server which return the result of your function.
You have to take look about communicate a single page application (SPA - Front end app) and your API (server side app).
For example :
$.ajax({
type: "POST"
, url: "serverIP/my/awesome/road/which/calling/my/function"
, data: null
, contentType: "application/json; charset=utf-8"
, dataType: "json"
, async: false
, success: function (jSonResult) {
console.log( jSonResult );
},
error: function (xhr, status, error) {
console.log(error + "\n" + status + "\n" + xhr.responseText);
}
});
For resume, you have to :
Open a road on your server
Return the result of your function in the call (jSonResult)
Use it in the success callback

Related

Code behind function of an aspx is not getting called using $.ajax

I have a web form IndexPage.aspx. The script part of this front end code is calling a code-behind function using ajax call.Here's the code:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~//IndexPage.aspx//SaveXml")%>',
data: JSON.stringify(logic),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
The "Failed" alert box is shown with return value 'undefined' after I run the code.
The code behind function is:
public static string SaveXml(string logic)
{
return logic;
}
This code-behind function is not getting called. The breakpoint which I have set at the code-behind function is not getting hit. I have tried almost all solutions from stack overflow. Please see if anythig is wrong in this code.
Thanks friends,
The issue was resolved. Checking browser console and network helped me a lot to solve the error.
I did two changes
1) Added [System.Web.Services.WebMethod] to code-behind function
2) Changed my => data: JSON.stringify(logic) ..... to ....=> data: '{ logic:\''+ logic +'\'}'
I did the second change after referring to this link: "Invalid JSON primitive" in Ajax processing
While sending just a string you need to add escape sequence.
Resolved
Ajax call:
$.ajax({
type: "POST",
url: '<%=Page.ResolveUrl("~/WebForm1.aspx/SaveXml")%>',
data: JSON.stringify({ "logic": "logic value" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
//cache: false,
success: function (msg) {
alert("AJAX received : " + msg.d);
},
error: function (msg) {
alert("Failed : " + msg.d);
}
});
Web Method
[WebMethod]
public static void SaveXml(string logic) {
}
Web.config
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

CROS Origin API Call issue?

I host my MVC API in server 'A'.
I tried to call API using jquery ajax call from native server (server 'A'). it's working fine as expected.
But, when tried to call API from server 'B'. I got an error.
No 'Access-Control-Allow-Origin' header is present on the requested resource
My ajax call like below
$.ajax({
url: Url,
type: "GET",
data: Data,
contentType: "application/json charset=utf-8",
async: false,
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
console.log("Exception in ajaxRequest - " + xhr.status + ' - ' + thrownError);
},
success: function (data) {
ResultData = $.parseJSON(data);
}
});

Passing ajax callback on typeahead.js source

I'm using jQuery 2.1.4 and trying to modify Twitter typeahead.js 0.11.1 to accept an ajax request as a source.
When I run the page from the local file system file:///C:/..., it works as expected, the error function is returned and the suggestion noData appears, but when I try to run the page directly from the server or even jsfiddle, the ajax success or error function are returned but the suggestions don't appear. The callback doesn´t seem to be working.
Do you think it is something related to the callback or the ajax request is being used improperly?
Below is my code:
HTML
<input class="typeahead" type="text" placeholder="Names" id="tah1">
Javascript
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'userNames',
source:
function findMatches(q, callback) {
console.log('q: ' + q);
var soapEnv =
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> "
+ "<soap:Body>"
+ "<ResolvePrincipals xmlns='http://schemas.microsoft.com/sharepoint/soap/'>"
+ "<principalKeys>"
+ "<string>" + q + "</string>"
+ "</principalKeys>"
+ "<principalType>All</principalType>"
+ "<addToUserInfoList>true</addToUserInfoList>"
+ "</ResolvePrincipals>"
+ "</soap:Body>"
+ "</soap:Envelope>"
$.ajax({
url: "www./_vti_bin/People.asmx?op=ResolvePrincipals",
type: "POST",
dataType: soapEnv,
success: function(data){
console.log('ajax request successful');
callback(data);
},
error: function(data){
console.log('ajax request error');
var errorValues = ['noData'];
callback(errorValues);
},
contentType: "text/xml; charset=\"utf-8\"",
SOAPAction: "http://schemas.microsoft.com/sharepoint/soap/ResolvePrincipals"
});
}
});
I also created this jsfiddle.
Thanks in advance!
I think it's about cross domain request:
$.ajax({
crossDomain: true,
url: "www./_vti_bin/People.asmx?op=ResolvePrincipals",
type: "POST",
dataType: soapEnv,
success: function(data){
console.log('ajax request successful');
callback(data);
},
error: function(data){
console.log('ajax request error');
var errorValues = ['noData'];
callback(errorValues);
},
contentType: "text/xml; charset=\"utf-8\"",
SOAPAction: "http://schemas.microsoft.com/sharepoint/soap/ResolvePrincipals"
});
Use the options "crossDomain" and set it at true. Don't work on JSFiddle but your url is not reachable.

Jquery jsonp response error - Callback was not called

I'm trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I get an error in response. I don't need to execute it, I just need it in my script. In any format (the response is json but js doesn't understand it).
I can't affect on that domain so it's impossible to change something on that side.
Here's my code:
$.ajax({
url: url + '?callback=?',
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
window.jsonpCallback = function(response) {
console.log('callback success');
};
There are a few issues with your $.ajax call.
$.ajax({
url: url + '?callback=?',
// this is not needed for JSONP. What this does, is force a local
// AJAX call to accessed as if it were cross domain
crossDomain: true,
// JSONP can only be GET
type: "POST",
data: {key: key},
// contentType is for the request body, it is incorrect here
contentType: "application/json; charset=utf-8;",
// This does not work with JSONP, nor should you be using it anyway.
// It will lock up the browser
async: false,
dataType: 'jsonp',
// This changes the parameter that jQuery will add to the URL
jsonp: 'callback',
// This overrides the callback value that jQuery will add to the URL
// useful to help with caching
// or if the URL has a hard-coded callback (you need to set jsonp: false)
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You should be calling your url like this:
$.ajax({
url: url,
data: {key: key},
dataType: 'jsonp',
success: function(response) {
console.log('callback success');
},
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
JSONP is not JSON. JSONP is actually just adding a script tag to your <head>. The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.
JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.
Please read the docs: http://api.jquery.com/jquery.ajax/
var url = "https://status.github.com/api/status.json?callback=apiStatus";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'apiStatus',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Try this code.
Also try calling this url directly in ur browser and see what it exactly returns, by this way You can understand better what actually happens :).
The jsonpCallback parameter is used for specifying the name of the function in the JSONP response, not the name of the function in your code. You can likely remove this; jQuery will handle this automatically on your behalf.
Instead, you're looking for the success parameter (to retrieve the response data). For example:
$.ajax({
url: url,
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
success: function(data){
console.log('callback success');
console.log(data);
}
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You can also likely remove the other JSONP-releated parameters, which were set to jQuery defaults. See jQuery.ajax for more information.

Ajax request after success result of other reqjest (.NET + jQuery)

I need to get xml document from a server, then client signs it and sends back to server.
At server side I have web method which saves document:
[WebMethod]
public static void SaveSignedDocument(string SignedData)
{
SignedCms signedCms = new SignedCms();
....
}
Then, I get document from a server and after success receive it I make client to sign it and send back. Here is Javascript
// get xml to sign
$.ajax({
type: "POST",
url: "Default.aspx/GetXMLReceipt",
data: "{'ITN': " + ITN + " }",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (xml) {
// xml file was got
var xmlString = xmlToString(xmlData);
// Sign data
var SignedData = SignData(xmlString);
// Send it to server
$.ajax({
url: 'Default.aspx/SaveSignedDocument',
data: "{ 'SignedData': '" + SignedData + "' }",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){
alert('Document was successfully sent!');
}
error: function (data, status, jqXHR) {
alert('Send signed data failed - ' + jqXHR);
}
});
},
error: function (data, status, jqXHR) {
alert('Get data failed - ' + jqXHR);
}
});
The problem is that none of the alert at second requests ever fire. If I change request to synchronous everything is ok but why it does not work like written above? The server receives nothing and if we look to network traffic I see that request was interrupted. Why?
Encode your data properly, do not use any string concatenations. Here's the correct way:
data: JSON.stringify({ ITN: ITN }),
and on your second AJAX request:
data: JSON.stringify({ SignedData: SignedData })
The JSON.stringify method will ensure that you are sending valid JSON to your server by properly encoding the argument.

Categories

Resources