How to append table correctly in jquery? - javascript

I am coming to an issue where I am appending to my table using jQuery and also to <div class="jobEntity" id="bestTable">. For some reason I don't want to append my table like that. Is there a way to work around with my jQuery code to append the table properly? Thanks for the help.
{request.contextPath} - is just localhost:8080/
var cache = {};
$("#searchTextField").autocomplete({
minLength: 2,
focus: function(event, ui) {
event.preventDefault();
},
source: function(request, response) {
var term = request.term;
if (request.term in cache) {
response(cache[request.term]);
return;
}
$.ajax({
url: "#{request.contextPath}/JobSearchItem.xhtml",
type: "GET",
data: {
term: request.term
},
dataType: "json",
success: function(data) {
response(data);
}
});
},
select: function select(event, ui) {
event.preventDefault();
var url = '#{request.contextPath}/index.xhtml';
var searchValue = ui.item.value;
var data = new FormData();
data.append('searchValue', searchValue);
$.ajax({
url: url,
data: data,
method: "POST",
processData: false,
contentType: false,
cache: false
}).done(function(text) {
$('#results').append($(text).find('#bestTable'));
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$("#clearone").show();
});
},
response: function response(event, ui, data) {
if (!ui.content.length) {
var message = {
value: "",
label: "NOTHING HAS BEEN FOUND"
};
ui.content.push(message);
}
}
});

Well you could do something like this:
$.ajax({
url: url,
data: data,
method: "POST",
processData: false,
contentType: false,
cache: false
}).done(function(text) {
let append = $(text).find('#bestTable').text() + $(text).find('#textTable').text() + $(text).find('table').text();
$('#results').append(append);
$("#clearone").show();
});
As an idea, first prepare the append content and then append at once.

Related

Regex values in JSON response

I want to regex JSON response value in AJAX without losing the structure of JSON.
Here is the ajax
$.ajax({
url: "date.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
var formDatax = new FormData();
var date = data.results;
var res = date.map(function(item) {
return {
"images": item.images
};
});
$.ajax({
url: "json.php",
type: "POST",
data: JSON.stringify(res),
processData: false,
contentType: false,
dataType: "json",
headers: {
"X-Requested-With": "XMLHttpRequest",
},
success: function(data) {
},
error: function() {}
});
},
error: function() {}
});
Here is an example of JSON Response
{
"part_number_key":"DDASDAS",
"name":"ASD",
"description":"asd",
"price":12,
"general_stock":12,
"brand":"ASD",
"category_id":2776,
"images":[
{
"url":"https://asd.com/asd/asd/1241.jpg",
"display_type":1
},
{
"url":"https://asd.com/asd/asd/73223.jpg",
"display_type":0
},
{
"url":"https://asd.com/asd/asd/214121.jpg",
"display_type":0
}
],
"warranty":24
},
I want to get the link of the image where the display_type is having value 1, so I thought it's ok if I regex the first url before "display_type":1 but I'm not able because this is not string to regex.
/(https?\:\/\/[^\" ][^]).*("display_type":1)/i
The regex, it's not complete because I saw the problem about the string I didn't tried to complete the regex...
You could parse the JSON and use filter and map to get the images URL
success: function(data) {
var response = JSON.parse(data)
var imagesURL = response.images.filter(image => image.display_type).map(image => image.url)
}
The response type is always parsed JSON. You can just access the images which have display_type: 1 like so:
let fileterImages = data.data.images.map((image) => {
if(image.display_type === 1) return image.url;
}

$.ajax autocomplete not working in ie 11 in jquery?

I am coming to a problem where my autocomplete code below works on chrome and firefox, but not internet explorer 11. Can anyone help me solve my code. I think its $.ajax problem that ie not supporting, but can anyone help me with my code below. thanks.
$("#searchTextField").autocomplete({
minLength: 2,
focus: function(event, ui) {
event.preventDefault();
},
source: myData,
select: function select(event, ui) {
event.preventDefault();
var url = '#{request.contextPath}/index.xhtml';
var searchValue = ui.item.value;
var data = new FormData();
data.append('searchValue', searchValue);
$.ajax({
url: url,
data: data,
method: "POST",
processData: false,
contentType: false,
cache: false,
}).done(text => {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
},
response: function response(event, ui,) {
if (!ui.content.length) {
var message = {
value: "",
label: "NOTHING FOUND"
};
ui.content.push(message);
}
}
});
There's a couple of reasons this won't work in IE. Firstly you have a trailing comma in the response handler function which needs to be removed:
response: function response(event, ui,) {
Secondly you're using an arrow function in done(); these are completely unsupported in any version of IE.
$.ajax({ /* ... */ }).done(text => {
Use a traditional anonymous function instead. Here's a full example with these fixes:
$("#searchTextField").autocomplete({
minLength: 2,
focus: function(event, ui) {
event.preventDefault();
},
source: myData,
select: function select(event, ui) {
event.preventDefault();
var url = '#{request.contextPath}/index.xhtml';
var searchValue = ui.item.value;
var data = new FormData();
data.append('searchValue', searchValue);
$.ajax({
url: url,
data: data,
method: "POST",
processData: false,
contentType: false,
cache: false,
}).done(function(text) {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
},
response: function response(event, ui) {
if (!ui.content.length) {
var message = {
value: "",
label: "NOTHING FOUND"
};
ui.content.push(message);
}
}
});
Finally, note that you can debug JS issues like this by using the developer tools (press F12 to open them in most browsers) and viewing the errors in the console.

post html as string through ajax

I have a tinymce wysiwyg and i want to post the html from it to my action method:
$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var id = $("#destinationId").val();
var PostContent = JSON.stringify({ 'content': ed.getContent(), 'destinationId' : id });
console.log(PostContent);
$.ajax({
url: '#Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: PostContent,
success: function (data) {
},
error: function (xhr, error) {
},
});
I always get null in my action method that looks like this:
[HttpPost]
public ActionResult SaveDestinationContent(string content, string destinationId)
{
return Json("TRUE");
}
i have tried to do this in a couple of different ways:
$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var PostContent = ed.getContent();
console.log(ed.getContent());
var id = $("#destinationId").val();
$.ajax({
url: '#Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: {
content: PostContent.toString(), destinationId: id
},
success: function (data) {
},
error: function (xhr, error) {
},
});
but none of them work!
<---- EDIT ------>
I know it has to do with the serialization of the html because when i just add some random string and post that it works as expected!

Clearing uikit html editor

i am trying to clear the content of my uikit html editor after saving data of when closing/cancelling my modal.
i tried clearing it with these codes:
$("#description").val('');
$('#description').attr('data-uk-htmleditor');
$.UIkit.htmleditor('#description', { /* options */ });
but it's still not working. does anyone here can help me?
EDIT:
here's my other codes for pulling the data from the database:
function editTask(id){
key = id;
s_type = 'u';
console.log(s_type);
enableForm('#task');
$('#btn-save-task').hide();
$('#btn-save-edited-task,#btn-cancel-task').show();
$.ajax({
type: "GET",
url: baseUrl+"/opportunities/getInfo/task/"+id,
async : true,
data : {
getType : "getTask"
},
dataType: 'json',
error : function(req,error){
notify(req.statusText,'warning');
},
success: function(data){
$("#taskDescription").val(data.description);
$('#taskDescription').attr('data-uk-htmleditor');
$.UIkit.htmleditor('#taskDescription', { /* options */ });
}
});
}
Try this:
var task = '';
function editTask(id) {
key = id;
s_type = 'u';
console.log(s_type);
enableForm('#task');
$('#btn-save-task').hide();
$('#btn-save-edited-task,#btn-cancel-task').show();
$.ajax({
type: "GET",
url: baseUrl + "/opportunities/getInfo/task/" + id,
async: true,
data: {
getType: "getTask"
},
dataType: 'json',
error: function(req, error) {
notify(req.statusText, 'warning');
},
success: function(data) {
task = data.description;
}
});
}
$.UIkit.htmleditor('#taskDescription', { /* options */ });
//Get a reference to the CodeMirror editor
var editor = $('.CodeMirror')[0].CodeMirror;
//You can then use it as you wish
editor.setValue(task);

How can I make sure that other functions is run after this get function is fully completed and rendered?

I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.

Categories

Resources