I am trying to communicate with an onvif camera on the browser but have not success so far. Below is the code that i am using to communicate with the onvif camera.
let soapMessage = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
'<GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>'+
'</s:Body>'+
'</s:Envelope>';
let ipAdd = '192.168.1.100';
let port = 80;
let path = '/onvif/device_service';
let url = `http://${ipAdd}:${port}${path}`;
$.ajax(
{
type : 'POST',
url,
contentType : 'text/xml; charset="utf-8"',
dataType: "xml",
processData: false,
data : soapMessage,
success : processSuccess,
error : processError
});
function processSuccess(data, status, req)
{
console.log( 'SUCCESS' );
}
function processError(data, status, req)
{
console.log( 'ERROR' );
}
i am getting a net::ERR_EMPTY_RESPONSE
what i am doing wrong. Help needed
My working example basing on your question:
var soapMessage = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">'+
'<GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>'+
'</s:Body>'+
'</s:Envelope>';
var ipAdd = '192.168.2.110';
var port = 80;
var path = '/onvif/device_service';
var wsurl = `http://${ipAdd}:${port}${path}`;
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: wsurl,
crossDomain: true,
processData: false,
data: soapMessage,
success: processSuccess,
error: processError
});
}
Related
So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.
My code:
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "xxx";
var params = {
"long_url" : encodeURIComponent(url)
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/bitlinks",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: params
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.error(data);
});
});
});
Results: a 422 http error;
"{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"
But running it with CURL does work though: How to shorten URL using PHP Bitly v4?
What am I doing wrong? Is it not possible with jQuery only?
TIA.
I had made this edit from your code above and its working well.
1) JSON.stringify before sending request (convert your request to JSON format).
2) No need for encodeURIComponent().
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "token";
var params = {
"long_url" : url
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/shorten",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: JSON.stringify(params)
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
});
});
i am getting XMLHttpRequest cannot load.so how to remove this error ,please any suggetion for that.
function soapRCA(){
var productServiceUrl = "https://www.ilportaledellautomobilista.it/eai/AreaVeicolo- ws/services/secure/coperturaRC";
var tipoDiVettura = $('#tipoVeicolo').val();
var targaperRCA = $('#targaRCA').val();
var SoaMessage = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
'<soapenv:Header>'+
'<wsse:Security soapenv:mustUnderstand="0" soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">'+
'<wsse:UsernameToken wsu:Id="XWSSGID-1253605895203984534550" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">'+
'<wsse:Username>paolo.pelliccione</wsse:Username>'+
'<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">tdlemon900mj</wsse:Password>'+
'</wsse:UsernameToken>'+
'</wsse:Security>'+
'</soapenv:Header>'+
'<soapenv:Body>'+
'<CoperturaRCVeicoloSecureRequest xmlns="http://www.dtt.it/xsd/Veicolo">'+
'<tipoVeicolo>'+tipoDiVettura+'</tipoVeicolo>'+
'<targa>'+targaperRCA+'</targa>'+
'</CoperturaRCVeicoloSecureRequest>'+
'</soapenv:Body>'+
'</soapenv:Envelope>';
$.ajax({
url: productServiceUrl,
type: "GET",
dataType: "xml",
data: SoaMessage,
complete: showResult2,
contentType: "text/xml; charset=\"utf-8\"",
crossDomain: true,
cache: false
});
return false;
}
function showResult2(xmlHttpRequest, status) {
//alert('edew00');
var data = $(xmlHttpRequest.responseXML).find('#listMovimenti tbody');
console.log(data);
//alert('ecco data: '+JSON.stringify(data));
/*var data = (''+response).substring((''+response).indexOf('<form id="ListaCoperturaRCVeicolo"'),(''+response).length);
data = data.substring(0,data.indexOf('</form>'));
$('#targapage #fintoiframe').html(data);
var ris = $('#targapage #fintoiframe').find('#ListaCoperturaRCVeicolo').html();
$('#targapage #risultatorcaEsterna').html(ris); */
}
</script>
I'm able to post a message but when I add either the attachment or pending_attachment, I get an error saying:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://api.yammer.com/api/v1/messages.json" //note: the endpoint is api.yammer...
, method: "POST"
, data: {
"body" : document.getElementById("post_body").value,
"group_id" : document.getElementById("group_id").value
,"attachment1" : document.getElementById("attachment")
}
, success: function (msg) {
alert("Post was Successful!: " + msg.messages[0].id); //id of new message
}
, error: function (msg) { alert("Post was Unsuccessful..." + msg); }
}
);
} else {
yam.login( function (response) {
//nothing
});
}
});
}
yammer's javascript SDK doesn't work with attachment. (at least no working example has been seen on the internet) To upload an attachment, you can either upload the file to your server and then use og_url to post a link to that file on your server, or cook up your own ajax form upload. here is an example:
var data = new FormData();
data.append('body', document.getElementById("post_body").value);
data.append('group_id', document.getElementById("group_id").value);
data.append('attachment1', document.getElementById("attachment"), 'filename_of_your_choice');
$.ajax({
url: "https://api.yammer.com/api/v1/messages.json",
data: data,
beforeSend: function (xhr) {
// set authorization header
xhr.setRequestHeader("Authorization", "Bearer YOUR_AUTHORIZATION_TOKEN");
},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
console.log("ajax post success.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request.");
}
});
Notice that the authorization token is obtained in the response to a successful login. It is not your app ID. Also, I doubt document.getElementById("attachment") will work. You need to convert that object into an byte array blob.
It works for me:
function postAttach() {
var msg = $('#attach_body').val();
var m_data = new FormData();
m_data.append('body', msg);
m_data.append('group_id', 6194208);
m_data.append('attachment1', $('input[name=attachment1]')[0].files[0]);
yam.platform.request({
url: "messages.json",
contentType: "multipart/form-data",
data: m_data,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (user) {
alert("The request was successful.");
},
error: function (user) {console.log(user);
alert("There was an error with the request.");
}
});
}
<div name="postYammer">
<input type="text" name="body" value="" id="attach_body" />
<input type="file" name="attachment1" id="attach_img"/>
<button onclick="postAttach()" type="button">Post</button>
</div>
//Example Nodejs in async function
// nota : you can get token from https://developer.yammer.com/docs/app-registration
const qs = require("qs");
const got = require("got");
const formData = require("form-data");
const fs = require("fs");
var json = {
is_rich_text: true,
topic1: 'tag1',
topic2: 'tag2',
body: 'body body',
group_id: 'group_id',
}
let querystring = qs.stringify(json);
var formData = new formData();
var aHeader = formData.getHeaders();
aHeader['Authorization'] = "Bearer token";
formData.append('attachment1', fs.createReadStream(path));
const response = await got.post('https://www.yammer.com/api/v1/messages.json?' + qs, {
headers: aHeader,
body: formData
});
I'm trying to post JSON data along with 2 ids through a Jquery AJAX post. But I am not able to do it.
Following is my code:
try {
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = { "str": StringJson};
var url = APP_URL+"EditSurvey?";
var param = "SurveyId="+surveyID+"&JSONData="+JSON.stringify(dataValue)+"&UserId="+providerKey;
$.ajax({
type: "POST",
contentType: "application/json",
url: url,
data: param,
async:true,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.error);
},
});
} catch (error) {
alert(error);
}
I get the following error when I debug this in Safari:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and in simulator I get the following error:
Where am I getting wrong? How do I solve this? I have to 3 parameters for post
surveyID
JSON data
userID
Edited:
The webservice is now changed and all 3 params- i.e. 2 ids and one whole json data is passed to the webservice. Still jquery ajax post is not working. See my code below:
var surveyID= localStorage.getItem("surveyId");
var userDetails = jQuery.parseJSON(localStorage.getItem("userdetails"));
var providerKey = userDetails["ProviderUserKey"];
var dataValue = {"surveyID":surveyID, "userID":providerKey, "str": StringJson};
alert(dataValue);
var url = APP_URL+"EditSurvey";
var param = dataValue;
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: dataValue,
success: function (data) {
alert('sucess');
//}
},
error: function (err) {
alert("Err : " + err.text);
},
});
edited to include stringJson:
var StringJson = JSON.stringify(MainJSON);
alert(StringJson);
Check if the final json which is being passed is in the exact format as expected by the server.
Try giving:
contentType: 'application/json',
Accept: 'application/json'
See if it helps.
try this one
formData = {
// all your parameters here
param1: param1,
JSONData: formToJSON(),
UserId: providerKey
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: url,
dataType: "json",
data: formData,
success: function(data) {
//success handling
},
error: function(data) {
alert("Err : " + err.error);
}
});
function formToJSON() {
return JSON.stringify({
dataValue: dataValue
});
}
I have written the following javascript to create a tasklist in google:
postData = {'title':'Netsuite List'};
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
The response says:
{ "error":
{ "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." }
}
What could be the possible error ?
not working
contentType: 'application/json; charset=UTF-8',
try with this
var headers = { };
headers["Content-Type"] ="application/json ; charset=UTF-8";
//remove to parsing form-encoded input error
data:JSON.stringify( model),
//this use for remove to parse error
Example:
$.ajax({
type: 'Post',
url: postUrl,
headers: headers,
dataType: 'json',//not required in some case
data:JSON.stringify( model),
success: function (data, sts) {
alert('success');
},
error: function (err, sts) {
var msg;
}
});
You sent data like:
title=Netsuite%20List
But Google API waits for JSON:
{ "title": "Netsuite List" }
Try to provide JSON.stringify() output to the requestURL method:
postData = JSON.stringify({'title':'Netsuite List'}); // <-- Added JSON.stringify
access_token = 'xxxx';
url = 'https://www.googleapis.com/tasks/v1/users/#me/lists';
headers['Content-type'] = 'application/json';
headers['Authorization'] = 'Bearer ' + access_token;
headers['Content-length'] = 25;
response = $$.requestURL(url, postData, headers, 'POST');
Also, it's better to get around documentation or source of $$ object you use and check how it can support sending JSON data.
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
beforeSend: (xhr) => {
xhr.setRequestHeader("Content-Type", "application/json");
},
//...
or :
jQuery.ajax({
url: "https://www.googleapis.com/tasks/v1/users/#me/lists",
method: "POST",
data: JSON.stringify({ /* your object */ }),
dataType: "json",
contentType: "application/json",
//...