Load ajax success data on new page - javascript

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.

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.

How to solve error parsing in dataTables?

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';

add loading text to javascript before html()

i want to add loading text before .html() load complete in my page
here is my code
$.post("<?php echo get_template_directory_uri(); ?>/template-parts/live.php", { couplername:couplername, couplercount:couplercount, couplerlathing:couplerlathing, couplerwhois:couplerwhois, couplerdetailsname:couplerdetailsname, couplerdetailsid:couplerdetailsid, couplerdetailsnumber:couplerdetailsnumber },
function(data) {
$("#order_price").html(data);
});
In order to have better control over your ajax call use the following ajax style:
$.ajax({
url: 'http://example.com',
method: 'POST',
data : {
someKey : "SOME_VAL",
anotherKey : "ANOTHE_VAL"
},
beforeSend:function(){
//HERE YOU CAN SHOW LOADING ETC.
},
success: function (response) {
//HERE YOU CAN GET THE RESPONSE of AJAX
},
error: function (e) {
//HERE YOU CAN HANDLE SITUATIONS OF ERROR
},
complete : function(){
//HERE YOU CAN REMOVE THE LOADING
}
});

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

Populating a JSTree with JSON data obtained in AJAX

I'm trying to populate a JSTree with JSON data that I'm obtaining from a service (which is called using ajax). However, I am getting a "Neither data nor ajax settings supplied error" in the jquery.jstree.js file. Because of this the JSTree just displays a loading gif.
AJAX code (editted to try setting json to local variable test, then return test)
function getJSONData() {
var test;
$
.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
test = json;
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
test = "error";
}
});
return test;
}
JSTree code
var jsonData = getJSONData();
createJSTrees(jsonData);
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
After some debugging, I've found that jsonData is undefined when passed to the createJSTrees method. Am I retrieving that data correctly in the Ajax code?
Thanks in advance
jsonData is undefined because getJSONData() doesn't return a value. You can't rely on the return value from your $.ajax success handler unless you assign a variable local to getJSONData() that gets returned after the $.ajax call completes. But you want something like this, which also has the benefit of being asynchronous:
<script type="text/javascript">
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
}
</script>
I have not tested your approach before, where you supply the data parameter directly to the json_data plugin, so I won't be able to supply an answer to this scenario.
However, since you are using an AJAX call to get the data, can't you supply the AJAX call to JSTree and let it handle the call on its own? Here's how I've configured the AJAX call in my code:
(...)
'json_data': {
'ajax': {
'url': myURL,
'type': 'GET',
'data': function(node) {
return {
'nodeId': node.attr ? node.attr("id") : ''
};
}
},
'progressive_render': true,
'progressive_unload': false
},
(...)

Categories

Resources