jquery/ajax json data function not working - json

I have the following function it suppose to talk to another server retrieve the json data and display it the problem is the function is not even initiating a query I'm I doing something wronge? the code is uploaded into the apache tomcat server and I used wireshark for traces and there are none on the http port here is the code
$(document).ready( function() {
var home_add='http://wcf.net:3300/gateway';
$('#handshake').click(function(){
alert(" sending json data");
function handshake(){ /*testing the function */
var data_send = {
"supportedConnectionTypes": "long-polling",
"channel": "/meta/handshake",
"version": "1:0"
};
$.ajax({ /* start ajax function to send data */
url:home_add,
type:'POST',
datatype:'json',
contanttype:'text/json',
async: false,
error:function(){ alert("handshake didn't go through")}, /* call disconnect function */
data:JSON.stringify(data_send),
success:function(data){
$("p").append(data+"<br/>");
alert("successful handshake")
}
})
}
})})
Thank you in advance for the feedback
Lava

u dont call handshake function...
$(document).ready(function () {
var home_add = 'http://wcf.net:3300/gateway';
$('#handshake').click(function () {
alert(" sending json data");
$.ajax({ /* start ajax function to send data */
url: home_add,
type: 'POST',
datatype: 'json',
contanttype: 'text/json',
async: false,
error: function () { alert("handshake didn't go through") }, /* call disconnect function */
data: {
"supportedConnectionTypes": "long-polling",
"channel": "/meta/handshake",
"version": "1:0"
},
success: function (data) {
$("p").append(data + "<br/>");
alert("successful handshake")
}
});
});
});

If you are using Internet Explorer you have add following code in to your jsp page in head section
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" />
Try this one and check, may be it will work.

Related

ASP.NET jQuery reload element on submit (Ajax POST/GET)

Using ASP.NET I'm trying to reload only a part of my webpage using jQuery instead of using "location.reload();". It's a single page application. As the user submits a form the user credits change and the new value should be updated without a full page reload. The value for credits is retrieved through an Ajax Get Call and should be updated after an Ajax Post Call. I tried using "$("#userCredits").load(?);" within the Ajax Post but can't get it right. Do I need to make a partial view to achieve this? Thanks for helping.
HTML _Layout.cshtml
<ul class="nav masthead-nav">
<li id="userCredits">
//Paragraph retrived from Ajax Get Call: "#reloadUserCredits".
</li>
<li>
<p class="user">#User.Identity.GetUserName()</p>
</li>
</ul>
JS
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
location.reload();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.append('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
As I understand... You already are getting the user credits via Ajax on page load. So you only need to do it again after he bought some more.
Have the Ajax request to /api/user in a named function. Below, I called it get_credits(). Run it on page load AND on success of the Ajax request to /api/buypack.
//Ajax POST user pack (buy pack)
$("#postform").submit(function (e) {
e.preventDefault();
var data = {
applicationUserId: $("#userId").val().trim(),
packId: $("input.activeImg").val().trim(),
}
$.ajax({
url: '/api/buypack',
type: 'POST',
dataType: 'json',
data: data,
success: function () {
document.getElementById("postform").reset();
//location.reload();
// Refresh the credits displayed on the page
get_credits();
},
error: function () {
}
});
});
// Ajax GET user credits (navbar userCredits)
var $credits = $('#userCredits')
function get_credits(){
$.ajax({
type: 'GET',
url: '/api/user',
success: function (credits) {
$.each(credits, function (i, user) {
$credits.html('<p id="reloadUserCredits" class="credits">Credits: ' + user.credits + '</p>');
});
}
});
}
// Run on page load
get_credits();

Append additional HTML result in calling MVC action by Ajax in DNN8

I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)

Using HTTP GET with JQuery

I'm trying to use a GET HTTP cal, I got the request to work with the Advanced REST client (Chrome plugin) but cannot get it to work in JQuery.
Following the advice from this thread, I've set up the following:
$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
This is the output I'm trying to get (successfully with REST client)
{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}
I just want to be able to access the name variable from that JSON and pass it through my function. I wanted to at least get the above code to work before I try to figure out how to create an object so I can successfully call the name, something like .append(object.name)
I just started learning JQuery and this is my first post so sorry if I didn't include enough details.
You can't apply ajax calls to other domains. You can make workaround using server-to-server calls via curl() or file_get_content(url), and then make a js call to your script.
First make php file, which will call the server note that if you want to use file_get_contents you should allow_url_fopen in your php.ini:
myProxy.php
<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>
your js should make call to your PHP, so you have workaround Same Domain Policy:
$.ajax({
url: 'myProxy.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
I am not sure if your api info is correct, but I think the main thing you need to do is change to jsonp instead of json due to the same origin policy that musa mentions.
The following JS fiddle "works" but the request is not authorized at the server: http://jsfiddle.net/cf8S9/.
$(document).ready(function() {
$('#button').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'jsonp',
success: function() { alert('hello!'); },
error: function() { console.log(arguments);alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

Crossdomain request

I try to load static html pages from another server.I make crossdomain request.
$(document).ready(function (){
$("div[src]").each(function(){
var staticFileURL = $(this).attr('src');
$.ajax({
url: staticFileURL,
dataType: 'jsonp',
data: {},
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
});
});
But I got in chrome error "SyntaxError:Unexpected token <".
In FF "SyntaxError:Invalid xml attribute value".
What's wrong.Could somebody help me?
JSONP is to get json data from the server, it looks like you are trying to received HTML data.
Try to put your HTML data inside JSON object on the server and then read that HTML on the success callback:
for example, your json data from the server:
{ html: "<html><head>...</head></html>" }
also, your success callback should look like:
success: function(**data**){
}