Jquery ajax POST response is null - javascript

I want to get the url in this link:
CODE:
<div id="id01"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "http://www.panet.co.il/series/seriesLink/138099",
success: function(info){
document.getElementById("id01").innerHTML = info.data.url ;
}
});
});
</script>

The problem is in the response. When you use JSONP the response result must be wrapped inside a jsonCallback() function:
jsonCallback({"Name": "Foo", "Id": 1234, "Rank": 7});
Look for more information here.

Looks like the returned data can't be parsed correctly. Here's my error message in Google Chrome:
Uncaught SyntaxError: Unexpected token :
The data returned from http://www.panet.co.il/series/seriesLink/138099 has some UTF8 characters in it. Maybe that's the cause.

Related

Why am i getting an error when I am sending JSON data from Javascript to Flask?

This is my javascript code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$.ajax({
type: 'POST',
url: "/jstoflask",
data: {
1: "Welcome",
2: "to",
3: "Geeks",
4: "for",
5: "Geeks"
},
success: function(data) {
console.log('success', data);
}
});
});
</script>
This is my flask code
#app.route('/jstoflask',methods=["POST"])
def jstoflask():
data=request.form('data')
print(data)
return jsonify(data)
I'm getting an error : TypeError: 'ImmutableMultiDict' object is not callable.
What am I doing wrong? How do I solve this?
It's because request.form is not a method you can call. It's the payload as an ImmutableMultiDict. You can change the line to data = request.form and you'd be able to see the value.
Since the request object is a dictionary, you can access the data by passing a key like so: request.form['1'].
Official Docs

Ajax JavaScript variable to PHP

I'm trying to send a JavaScript dictionary variable to PHP using Ajax with JavaScript/jQuery $.get method, but it produces an error.
Here is the JavaScript code:
$.get( "contr.php", { max: "max", max2: "max2" } );
And PHP:
$max = $_GET['max'];
var_dump($max);
jQuery works
JavaScript $.get works
The PHP error is:
undefined index max
What am I doing wrong?
The error is helpful. It says your dictionary variable passed to $.get has omitted the keyvalue pair data -> max. Try this:
$.ajax({
url: "contr.php",
method:"GET",
data:{
max: "max"
max2: "max2"
}
}).done(function(response){
alert(response)
})
Try this:
$.ajax({
type: "GET",
url : "contr.php",
data: {
max : "max",
max2: "max2"
},
success : function(data){
// Do some stuff
console.log(data); // Use this to check the page response
}
})
Refer to this link on the jQuery site :)
Replace your Ajax code with this one:
$.get( "contr.php", { "max": "max", "max2": "max2" }, function(res){} );

Error when making Ajax REST API calls

I have this application that I am trying to create.
The application should login (using REST API), and respond with a session id.
I have created a button, which calls the JavaScript function that performs the ajax call, which in turn tries to login.
The results are appended to the div (appscan_results)
Here's is the code
<html>
<head>
<title> AppScan Issues Exporter </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function login(){
var request = $.ajax({
type:"POST",
url:"myurl",
dataType: "json",
contentType: "application/json",
data:{
"userId": "username",
"password": "password",
"featureKey": "AppScanEnterpriseUser",
"clientVersion": "",
"clientIp": "",
"clientHostName": ""
},
});
request.done(function (jqXHR){
alert('Success');
$("#appscan_results").html(jqXHR.responseText);
});
request.fail(function(jqXHR) {
alert('Failure');
$("#appscan_results").html(jqXHR.responseText);
});
}
</script>
<button onclick="login()">Get Issues</button>
<div id="appscan_login"></div>
<div id="appscan_results"></div>
</body>
</html>
After it runs, I get the following error:
Exception thrown by application class 'org.apache.wink.server.internal.RequestProcessor.handleRequest:195'
javax.servlet.ServletException: org.codehaus.jackson.JsonParseException: Unexpected character ('u' (code 117)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at [Source: com.ibm.ws.webcontainer.srt.SRTInputStream#d80cceaa; line: 1, column: 2]
at org.apache.wink.server.internal.RequestProcessor.handleRequest(RequestProcessor.java:195)
at com.ibm.websphere.jaxrs.server.IBMRestServlet.service(IBMRestServlet.java:106)
at [internal classes]
at com.ibm.appscan.server.filters.ClickjackFilter.doFilter(Unknown Source)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:192)
at [internal classes]
What am I missing in the code?
PS: I have tested the REST call using REST API client and I do get a response,
org.codehaus.jackson.JsonParseException
Your servlet/rest controller is not able to parse the Input JSON string and convert it to a Valid Java Object.
Change data to
data:JSON.stringify({
userId: "username",
password: "password",
featureKey: "AppScanEnterpriseUser",
clientVersion: "",
clientIp: "",
clientHostName: ""
},
})

Project Oxford - HTTP 404 when calling Computer Vision API through Javascript

I am trying to get JSON data from Microoft Project Oxford through a API call. I followed the API reference but when I make a call I get a 404 error.
<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
"visualFeatures": "All",
};
$.ajax({
url: "https://api.projectoxford.ai/vision/v1/analyses&" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","0000000000000000");
},
type: "POST",
// Request body
data: '{ "Url": "http://www.sweetheartmotors.ca/sites/default/files/audi_PNG1736.png" }',
})
.done(function(data) {
alert("success");
//display data
console(data);
})
.fail(function() {
alert("error");
});
});
</script>
What is stopping me from making the call?
You need to change the URL to end in a question mark, rather than an ampersand: https://api.projectoxford.ai/vision/v1/analyses?
Unfortunately most of the samples on the projectoxford.ai site contain this error.

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:
$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});
The script was stuck on this line:
prePopulate: populateValue
When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:
[{
"id": "11566",
"name": "Smith - White"
}]
There was a javascript error:
Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`
How can I fix this error?
You need to parse the string in your populateValue variable to an object:
prePopulate: $.parseJSON(populateValue)
Or alternatively, in plain JS:
prePopulate: JSON.parse(populateValue)
You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.
Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json
Here is my .CS page code:
WebMethod
public static string PopulateDetails(Guid id){
var prx = new ProductProxy();
var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
return JsonConvert.SerializeObject(result);
}
Then in my jQuery post method:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Productjq.aspx/PopulateDetails",
data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
success: function(result) {
var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"
$.each(rspns, function() {
$('#<%=txtProductName.ClientID %>').val(this.Name);
});
},
error: function(xhr, textStatus, error) {
alert('Error' + error);
}
});
I was getting this error as well.
C# Api returning Serialized Dictionary data.
return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);
Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize
return dic_data;
No more errors on the browser side. Not sure why.

Categories

Resources