jQuery response working in DreamWeaver but not in Browser - javascript

I have a problem when trying to get response from URL or PHP script. When I click on a button that runs this function clicked() it gives normal response in DreamWeaver but when clicked in browser it returns error. I've searched answers but nothing really helped.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Log In</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
// I've deleted buttons and other stuff from this example code so it can be easier to read
<script language="javascript">
function clicked(){
$.ajax("test.php", {
type: 'GET',
dataType: 'text',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
alert("returned_data ="+returned_data);
},
error: function( req, status, err ) {
alert( 'something went wrong', status, err );
}
});
</script>
</html>
PHP script is working fine, some other problem is here but I can't seem to see it.

You are missing a closing brace at the end of your script.
it should be:
<script language="javascript">
function clicked(){
$.ajax("test.php", {
type: 'GET',
dataType: 'text',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
alert("returned_data ="+returned_data);
},
error: function( req, status, err ) {
alert( 'something went wrong', status, err );
}
});
}
</script>

Your code works on Dreamweaver because it has a built in Apache server, although you are not using one in your production environment.

Related

How to receive judgement result from model of Custom Vision with JavaScript

I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.

How can I display the data from the JSON on my webpage?

I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.

AJAX Call Is Not Working With The Controller Action

Salaamun Alekum
My AJAX Call Is Not Calling The Controller Action In ASP.NET MVC Web Applicaiton Project
Bellow Is My AJAX Call In Javascript And Next Is Controller's Action
AJAX Call
var requestUrl = '/Home/GetCurrentUser';
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
The Controller Action
[SharePointContextFilter]
public JsonResult GetCurrentUser()
{
CurrentUserModel um = new CurrentUserModel();
try
{
Microsoft.SharePoint.Client.User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.Email, user => user.LoginName);
clientContext.ExecuteQuery();
um.Name = spUser.Title;
um.Email = spUser.Email;
um.LoginName = spUser.LoginName;
}
}
SharePointBoxOnline.Common.User u = UserManager.Instance.GetUserByEmail(um.Email);
if (u != null)
{
um.ClientId = u.FK_Client_ID;
um.UserId = u.User_ID;
}
}
catch (Exception e)
{
SharePointBoxOnlineAppWeb.Classes.LogsManager.LogException(e.Message, e.StackTrace, System.Web.HttpContext.Current.Request.Url.ToString(), "Added logging functionality to store the exception information in the Database", DateTime.Now);
}
return Json(um, JsonRequestBehavior.AllowGet);
}
Errors Results In AJAX Are
error.description
Invalid character
status
parsererror
xhr.responseText
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>An unexpected error has occurred.</h2>
<p>Please try again by launching the app installed on your site.</p>
</div>
</div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"673b269bf2c74e39a9496d69f3e0b62e"}
</script>
<script type="text/javascript" src="http://localhost:14069/4b2e31c8e2cf413facce9558ed0cb3ff/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Thank You Stackoverflow And Members Of Stackoverflow Please Let Me Know If You Require Further Details
Thank You
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
});

How to catch if ajax got wrong response type with jQuery

My ajax call looks like this:
$.ajax({
url: self.options.base_url + '/interface/jsonp/auth_user/',
dataType: 'jsonp',
success: function (data) {
self._after_user_auth(data);
},
error: function () {
self._service_unavailable()
}
});
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Unhandled Exception</title>
</head>
<body>
<h1>Unhandled Exception</h1>
<p>An unhandled exception was thrown by the application.</p>
</body>
</html>
And if there is some error on server-side I get the next response
which rises Uncaught SyntaxError: Unexpected token <
Is it possible to catch that on the client?
I'm not sure I understand you, but you can catch JavaScript error with
try{}catch(){}:
$.ajax({
url: self.options.base_url + '/interface/jsonp/auth_user/',
dataType: 'jsonp',
success: function (data) {
try{
self._after_user_auth(data);
}catch(err){
console.log(err); //catch is fired if inside try js find an error.
}
},
error: function () {
self._service_unavailable()
}
});
catch(err) - err is an object that contain all error information.
some documentation: Try catch

JQuery callback not executed?

I want to have a progressbar that take data from server, so I created 2 servlets the first one (process) starts the process and when it ends return the result; the second one (GetEvent) gets progress information from session every 500ms..
All of this works normally and the progress information is displayed correctly, but the
process Servlet's callback never executes.
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
process();
$("#progressbar").progressbar({ value: 0 });
$("#progressStatus").html("");
getEvent();
});
function process()
{
$.getJSON("process", function(result){
//never executed
alert( "Result: " );
});
}
function getEvent()
{
$.getJSON("GetProgressEvent", function(data) {
$.each(data.ProgressEvents, function(){
$("#progressbar").progressbar({ value: this.progress });
$("#progressStatus").html(this.status);
});
});
setTimeout(getEvent, 500);
}
</script>
</head>
<body style="font-size:62.5%;">
<div id="progressbar"></div>
<div id ="progressStatus"></div>
</body>
</html>
I just started with JQuery and I don't know what's wrong with this code.
you are calling $.getJSON with a url "process"
this function has no error handling if there is problem with the response or invalid JSON is returned then the callback will not be called.
http://api.jquery.com/jQuery.getJSON/
jQuery.getJSON( url, [data], [success(data, textStatus, jqXHR)] )
url A string containing the URL to which the request is sent.
data A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR)A callback function that is executed if the request succeeds.
Try adding a valid url in place of "process" and if that fails use the
$.ajax method as follows
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: $.param( $("Element or Expression") ),
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});

Categories

Resources