Ajax responseText.replace() isn't working - javascript

The line which says it removes the markup doesn't completely and occasionally the text which gets displayed on the web page displays a 'rn' instead. I decided to skip removing the markup, but any attempt to remove or simplify the responseText.replace() function either gives me an error for the data.replaceAll() functions, or seems to do nothing. So how can I get the data to return with the markup and allow me to parse what I need?
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields}",
dataType: "json",
async: false
}).responseText.replace(/<\/?[^>]+>/gi, ''); //Remove markup
data = data.replaceAll("\\", "");
data = data.replaceAll("}}", "}");
data = data.replaceAll("{\"data\":", "");
data = data.replaceAll("{\"d\":", "");
data = data.replaceAll("]}", "]");
data = data.replaceAll("}}]\"}", "}]");
data = data.replaceAll("}]\"}", "}]");
I updated the code to the below and I am getting an error, "Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 34" which is where dataset is defined. I played around with various combos of the replaces and it appears to be .replace("\", ""); is the one causing the issue, but I don't know why.
var data = $.ajax({
type: "POST",
contentType: "application/json; charset=unicode",
url: '<%= ("Default.aspx/GetData") %>',
data: "{'fields': '" + fields + "'}",
dataType: "json",
async: false
});
var json = JSON.stringify(data)
.replace("}}", "}")
.replace("{\"data\":", "")
.replace("{\"d\":", "")
.replace("]}", "]")
.replace("}}]\"}", "}]")
.replace("}]\"}", "}]")
.replace("\\", "");
var table = $('#dtable').DataTable();
table.clear().draw();
var i = 0;
var j = [];
var dataSet = JSON.parse(json);
$.each(dataSet, function (key, value1) {
$.each(value1, function (key, value) {
j[i] = value;
i++;
});
table.row.add([j[1], j[2], j[3], j[4], j[5], j[6], j[7], j[8], j[9], j[10], j[11], j[12]]).draw();
i = 0;
j = [];
});

Related

How to serialize array in javaScript and append in formdata

I want to serialize array in a javascript and append the serialized value in form data, I have tried but serialize array showing empty, Kindly give a suggestion.
var IsolationFO = {};
IsolationFO['tagNumber'] = $('#tagNumberId').val();
IsolationFO['keyNumber'] = $('#lockProvidedId').val();
var formData = new FormData();
$.ajax({
url: baseURL + 'url',
type: "POST",
contentType: false,
processData: false,
data: function() {
//here the inputs showing empty
var inputs = $('#IsolationFO').serializeArray();
$.each(inputs, function(i, input) {
formData.append(input.name, input.value);
console.log("\nSending Data----------------" + input.name + "-----" + input.value);
});
return formData;
}(),

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

Why doesnt this javascript code work?

I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....

Json output returned 'undefined' on rendering

I have below output in json coming from a web method.
{"d":"[{\"id\":1,\"username\":\"deepak_nhm\",\"companyid\":4,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Deepak\",\"lastname\":\"Kerai\",\"avatarsmall\":\"/images_webdev/profile/634596544067649211654527189.jpeg\",\"company\":\"Orange\",\"CompanyRank\":1,\"OverAllRank\":3},{\"id\":2,\"username\":\"Mona_Co\",\"companyid\":1,\"MaxEQuizScoreAvailable\":600,\"EQuizzesUserScoreTaken\":100,\"EQuizzesUserTaken\":1,\"firstname\":\"Mona\",\"lastname\":\"Sadhu\",\"avatarsmall\":\"/images_webdev/profile/AspNetForumAvatarguy35.jpg\",\"company\":\"3 Retail\",\"CompanyRank\":1,\"OverAllRank\":3}]"}
How do I render the above output, as the below attempt only returns 'undefined')?
<script type="text/javascript">
$(document).ready(function () {
GetProducts();
});
function GetProducts() {
$.ajax({
type: "POST",
url: "Default.aspx/GetContestants",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the ul's content with the page method's return.
var invoices = msg.hasOwnProperty("d") ? msg.d : msg;
var invoicesInList = [];
for (var i = 0; i < invoices.length; i++) {
invoicesInList.push("<li>" + invoices[i]["username"] + "</li>");
//console.log(msg.length);
}
$(invoicesInList.join("")).hide().appendTo("#ProductsList").fadeIn("slow");
}
});
}
</script>
Thanks in advance.
msg.d is actually json, so you have to decode it to use it as an object, something like
var invoices = msg.hasOwnProperty("d") ? JSON.parse(msg.d) : msg;

Post with ajax-jquery send blank space when the sentence have +

I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...

Categories