How to solve error parsing in dataTables? - javascript

I have a function button that carry user info fullname, after clicking the button, it will send fullname and level to an API to be process and the result should be display in dataTable. Unfortunately, I got this error.
This is console.log for console.log(params). {"task_level":3,"fullname":"Administrator"}
Below is console.log for console.log(params).
Both console log is similar to API's result.
I don't know which is proper.
JS 1st Try (1st Ajax to send the parameter to API and after return success hopefully working but not.
"<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$.ajax({
url : url_api + '/api/user_task',
crossDomain: true,
type : 'POST',
dataType : 'json',
data: params,
success: function(response){
if (response.status == "Success"){
console.log(response)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}
},
error: function(e){}
});
}
JS 2nd Try
<button type='button' class='btn btn-dark btn-round' onclick='viewTablePerson(""+value.fullname+"")'>View Project</button>"+
function viewTablePerson(fullname){
var level = 3;
var fullname2 = fullname;
var obj = {
task_level : level,
fullname : fullname2
};
var params = JSON.stringify(obj);
console.log(params)
$('#viewProgress').DataTable({
ajax: {
url: url_api + '/api/user_task',
crossDomain : true,
type : "POST",
cache : false,
dataType : "json",
contentType: false,
processData: true,
data : params,
timeout: 10000,
},
destroy: true,
columns: [
{ data : "task_name"},
{ data : "task_owner"},
{ data : "task_status"}
],
});
}

Documentation says:
When using the ajax option to load data for DataTables, a general error can be triggered if the server responds with anything other than a valid HTTP 2xx response.
So, you have to check server-side response instead of search for problems on the front-end.
Also, in your case make sure
the plugin sends request to the same domain from which the current page is loaded;
browser security system doesn't prevent loading of external scripts - for example on http://localhost you cannot Ajax load a script from http://google.com without special measures;
you are specifying a relative path without a domain name (if you are using a single domain);
JSON data in response is a valid.
If you cannot alter the backend system to fix the error, but don't want your end users to see the alert message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it:
$.fn.dataTable.ext.errMode = 'throw';

Related

While Passing a MediaStream object through Ajax to PHP, Ajax call returns a blank object

I am trying to pass a MediaStream object through Ajax to PHP and simply just returning that object. But it returns a blank object. Please find the code as below.
jQuery Code:
globStream contains the media stream Object.
globStream = new Array(globStream);
formData.delete("stream");
formData.append("stream", JSON.stringify(globStream));
$.ajax({
url : "/editpeople",
dataType : "text",
type : "POST",
cache : false,
contentType : false,
processData : false,
data : formData,
success : function(result) {
result = JSON.parse(result.trim())[0];
},
error : function(jqXHR, exception) {
}
});
PHP Code:
$mediaSream = json_decode(stripslashes($_REQUEST["stream"]));
$returnCode = json_encode($mediaSream);
echo $returnCode;
The result I am receiving is as shown in the screen print attached.

Insert variable value into ajax post data

I have created a form with textboxes and a dropdown menu, inside my code I've created a script which will be called when clicking "Send Form"
Lets say my field are : firstName, lastName, country (dropdown)
Here is the script:
function f1() {
var settings = {
"async": true,
"url": "https://api.TheSite.com/v2/applications/123456789/newJson.json",
"method": "POST",
"headers": {
"x-api-key": "123456789123456",
"content-type": "application/json",
},
"processData": false,
"data": "{\r\n \"deployment\": {\r\n \"revision\": \"string\",\r\n \"changelog\": \"string\",\r\n \"description\": \"string\",\r\n \"user\": \"string\"\r\n }\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
alert("The Form Was Sent");
});
}
I would like to insert those 3 variables' values inside the "data" string like so:
"data": "{\r\n \"deployment\": {\r\n \"revision\": \`firstName
\",\r\n \"changelog\": \"`lastName
and so on...
In the dropdown menu, I assume it will be displayed as an array. How do I include my variable inside?
First create an empty object and insert the data into it.
Next use JSON.strigify() to convert that into a JSON blob before you send it over to the server.
var data = {};
data.deployment = {};
data.deployment.revision = firstName;
data.deployment.changelog = lastName;
var settings = {
....,
data: JSON.stringify(data)
};
Since you are already using jQuery to perform your AJAX request, you should be aware that you can actually pass a native JavaScript object into the data portion of the request. You don't need to have it converted to a JSON string. If you want to, you can just stringify it.
You can actually establish default request options and then merge them with the data you want to request.
var defaults = {
url: 'https://api.TheSite.com/v2/applications/123456789/newJson.json',
method: 'POST',
contentType: 'application/json',
headers: {
'x-api-key': '123456789123456',
},
processData: false,
async: true
};
function makeXhrRequest(config) {
var xhrRequest = $.extend(true, defaults, config);
// If you want to convert the request to a json String.
//xhrRequest.data = JSON.stringify(data);
$.ajax(xhrRequest).done(function(data, textStatus, jqXHR) {
console.log(data);
alert("The Form was sent...");
});
}
var $myForm = $('form[name="my-form"]');
makeXhrRequest({
data : {
deployment : {
revision : $myForm.find('input[name="firstname"]').val(),
changelog : $myForm.find('input[name="lastname"]').val(),
description : 'string',
user : 'string'
}
}
});
SOLVED
this is the syntax that worked for me +$("#firstName")[0].value+ and this is the code :
"data":"{\r\n\deployment\: {\r\n revision\:"+"\""+$("#firstName")[0].value+"\","+"\r\n"

Jquery filer.js Ajax request not sending updated variable value

so Ive got this jquery plugin which is sending an ajax request to a php file with a variable attached.
However the variable attached to data{type:filetype} is being changed on the page. When the user submits the request to be sent, the new value of the filetype is not being sent.
Any idea why ?
The filetype variable is a global variable :
<script type="text/javascript">
var filetype = "";
</script>
This is the plugin being initiated :
$('#filer_input1').filer({
uploadFile: {
url: "php/fileupload/upload.php",
data: {order:19,
type:filetype},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function(){
console.log(filetype);
},
success: function(data, el){
console.log(data);
console.log(el);
},
error: function(el){
},
statusCode: null,
onProgress: null,
onComplete: null
}
}
function which updates the variable :
function setFileType(x){
var text = $("#"+x).html() + ' <span class="caret"></span>';
$("#fileTypeSelect").html(text);
filetype = x;
}
Any help would be greatly appreciated

Load ajax success data on new page

My ajax call hits the controller and fetches a complete JSP page on success. I was trying to load that data independently on a new page rather than within some element of the existing page. I tried loading it for an html tag but that didn't work either. I tried skipping the success function but it remained on the same page without success data. My ajax call is made on clicking a normal button in the form and the code looks like as shown below.
$.ajax({
url : '/newpage',
type : 'POST',
data : requestString,
dataType : "text",
processData : false,
contentType : false,
success : function(completeHtmlPage) {
alert("Success");
$("#html").load(completeHtmlPage);
},
error : function() {
alert("error in loading");
}
});
This should do:
$.ajax({
url : '/newpage',
type : 'POST',
data : requestString,
dataType : "text",
processData : false,
contentType : false,
success : function(completeHtmlPage) {
alert("Success");
$("html").empty();
$("html").append(completeHtmlPage);
},
error : function() {
alert("error in loading");
}
});
You can try this,
my_window = window.open("");
my_window.document.write(completeHtmlPage);
into your success.

Cross domain jQuery ajax calls not working

I'm having trouble with this code and I can't seem to get it to work. The typical error that I get back for this call is a "Failed to load resource: the server responded with a status of 401 (Unauthorized) " .
$('#btnZendesk').click(function () {
$.ajax({
url: "https://flatlandsoftware.zendesk.com/api/v2/topics/22505987.json",
type: 'GET',
crossDomain: true,
xhrFields: {
withCredentials: true
},
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
timeout: 2000,
username: "test#test.com",
password: "test",
success: function (data, textStatus, response) {
alert("success");
},
error: function (data, textStatus, response) {
alert(data);
}
});
Problem is that the resource you are trying to access is protected with Basic Authentication.
You can use beforeSend in jQuery callback to add a HTTP header with the authentication details e.g.:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic XXXXXX");
}
Alternatively you can do it using jQuery ajaxSetup
$.ajaxSetup({
headers: { 'Authorization': "Basic XXXXX" }
});
EDIT
A few links to the mentioned functions
jQuery.ajaxSetup
jQuery.ajax
EDIT 2
The Authorization header is constructed as follows:
Username and password are joined into a string "username:password" and the result string is encoded using Base64
Example:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
I too got this problem and somehow all solutions from internet either failed or were not applicable due to client webservice restrictions (JSONP, XDR, CORS=true)
For this, I added an iframe in my page which resided in the client;s server. So when we post our data to the iframe and the iframe then posts it to the webservice. Hence the cross-domain referencing is eliminated.
We added a 2-way origin check to confirm only authorized page posts data to and from the iframe.
Hope it helps
<iframe style="display:none;" id='receiver' name="receiver" src="https://iframe-address-at-client-server">
</iframe>
//send data to iframe
var hiddenFrame = document.getElementById('receiver').contentWindow;
hiddenFrame.postMessage(JSON.stringify(message), 'https://client-server-url');
//The iframe receives the data using the code:
window.onload = function () {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
var origin = e.origin;
//if origin not in pre-defined list, break and return
var messageFromParent = JSON.parse(e.data);
var json = messageFromParent.data;
//send json to web service using AJAX
//return the response back to source
e.source.postMessage(JSON.stringify(aJAXResponse), e.origin);
}, false);
}

Categories

Resources