Convert \n line breaks to HTML <BR> line breaks - javascript

I have this simple idea to convert my \n line breaks from my ajax JSON call to <br> so that it would properly display my data.
I tried many different ways to perform the conversion but I keep getting an error saying:
Uncaught TypeError: data.replace is not a function
The issue seems to be the way I'm making this call:
var incident = incident.replace(/\n/g, "<br />");
From what I see on the forums here this is how we're suppose to use .replace but I'm not understading why it doesn't like it.
I tried doing this as well:
"<td colspan='3'>"+incident.Impact.replace(/\n/g, "<br />")+"</td>"+
This works but if the field is empty it returns with an error stating that it cannot read .replace of undefined. Would anyone have any ideas?
Full code:
$.ajax({
url: this.basePath() + '/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc',
dataType: 'json',
cache: false,
success: function (data) {
$.each(data.d.results, function (index, incident) {
var incident = incident.replace(/\n/g, "<br />");
$('body').append(
"<table border='1' width='800' >"+
"<tr bgcolor='#9aff99' align='center'>"+
"<td width='800px' colspan='4'><strong>Transfert de connaissances</strong></td>"+
"</tr>" +
"<tr bgcolor='#fff'>"+
"<td width='165'>Billet:</td>"+
"<td>"+incident.Incident+"</td>"+
"<td width='165'>Priorité:</td>"+
"<td>"+incident.PrioritéValue+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Description:</td>"+
"<td colspan='3'>"+incident.Description+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td colspan='4' width='800px' bgcolor='#9aff99' align='center'>Détails</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Impact:</td>"+
"<td colspan='3'>"+incident.Impact+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Dépannage</td>"+
"<td colspan='3'>"+incident.Dépanage+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td colspan='4' width='800px' bgcolor='#9aff99' align='center'>Suivi</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Prochain Suivi:</td>"+
"<td colspan='3'>"+incident.Suivi+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Ressource:</td>"+
"<td colspan='3'>"+incident.Ressources+"</td>"+
"</tr>"+
"<tr bgcolor='#fff'>"+
"<td width='165'>Prime:</td>"+
"<td colspan='3'>"+incident.ResponsableValue+"</td>"+
"</tr>"+
"</table>"+
"<br><br>");
})
}
});

You are trying to use a string method on an object, not on property values within that object.
There is no Object.replace() so that will throw error
Similarly undefined.replace() will also cause error
Presumably you only have to fix a few property values but first it is necessary to make sure those values are defined and are strings before using replace()
Try
function convertBreak(str){
if(!str){
return ''; // don't want `undefined` printing into page
}
// if it's something other than string, return it as is
if( typeof str !=== 'string'){
return str;
}else{
return str.replace(/\n/g, "<br />")
}
}
incident.Description = convertBreak(incident.Description);

The problem with your code is here:
var incident = incident.replace(/\n/g, "<br />");
You are redeclaring the variable incident. Try to remove the redeclaration:
incident = incident.replace(/\n/g, "<br />");

Related

Reloading modal table appends to existing table and doubles the table

I have a modal that displays informations about items (dates, etc) in a table. When I click on an item it opens a smaller modal where I can update the items date, which is then updated throught a webservice to the database. then I want to reload the data to show the updated ETA. The way I found to do that is to recall the open function of my modal. But then when I do that the modal reloads and the table is now doubled. So it probably appends to the existing table without clearing the data. How can I clear the content and reload it fresh with the updated data ? Preferably without closing and reopening the modal. Heres my code.
First is the function that saves the change and closes the small modal
$('#btnSaveETAChange').click(function () {
var dt_eta = document.getElementById('<%=EtaDate.ClientID%>').value;
var no_item = document.getElementById('<%=ItemNo.ClientID%>').value;
var no_document = document.getElementById('<%=NoPo.ClientID%>').value;
var no_line = document.getElementById('<%=LineNo.ClientID%>').value;
var no_project = document.getElementById('<%=ProjectNo.ClientID%>').value;
UpdateEta(no_item, dt_eta, no_document, no_line)
$('#modalUpdateETA').modal('hide');
$('#modalUpdateETA').on('hidden.bs.modal', function () {
$('body').removeClass('modal-open');
OpenModaleShortage(no_project);
});
});
This the function that loads the main modal.
function OpenModaleShortage(ProjectNumber) {
$("#Shortage_body tr").remove();
$.ajax(
{
type: "POST",
url: '<%=ResolveUrl("~/MTL/SEPTOR/wsMTL.asmx/GetProjectOutstandingItems") %>',
contentType: "application/json; charset=utf-8",
data: "{ 'ProjectNumber': '" + ProjectNumber + "'}",
dataType: "xml",
success: function (data) {
var rowMaterial = "<tr>"
+ "<th style='text-align:center; font-size:16px'>Item No</th>"
+ "<th style='text-align:left; font-size:16px'>Description</th>"
+ "<th style='text-align:center; font-size:16px'>Shortage</th>"
+ "<th style='text-align:center; font-size:16px'></th>"
+ "<th style='text-align:center; font-size:16px'>ETA</th>"
+ "</tr>";
$("#Shortage tbody").append(rowMaterial);
$(data).find('SHORTAGE').each(function (i, productionRow) {
try {
rowMaterial = "<tr>"
+ "<td id='no_po' style='display: none; '>" + $(productionRow).find('PO').text() + "</td> "
+ "<td id='no_line' style='display: none; '>" + $(productionRow).find('LineNO').text() + "</td> "
+ "<td id='no_item' style='text-align:center; font-size:14px'>" + $(productionRow).find('ItemNo').text() + "</td> "
+ "<td id='no_project' style='text-align:center; font-size:14px'>" + $(productionRow).find('ProjectNo').text()+ "</td> "
+ "<td style='text-align:left; font-size:14px'>" + $(productionRow).find('Description').text() + "</td> "
+ "<td style='text-align:center; font-size:14px'>" + parseInt($(productionRow).find("ProjectShortage").text()) + "</td> "
+ "<td style='text-align:center; font-size:14px' data-toggle='modal'><div><i style='vertical-align: center;' class='fa fa-calendar'></i></div></td> "
+ "<td id='dt_eta' style='text-align:center; font-size:14px'>" + $(productionRow).find('ETA1').text().slice(0, 10).trim().replace('-', '.').replace('-', '.') + "</td>"
+ "</tr>";
$("#Shortage tbody").append(rowMaterial);
}
catch (err) {
alert(err.message);
}
});
$('#addShortage').modal('show');
},
failure: function (errMsg) {
alert(errMsg);
}
}
);
};
Pretty easily, it turns out. You'll want to use the jQuery empty() method
Before you stick any data into id Shortage tbody, just empty that div out. Then, when you append new data in, it should take its place.
Admittedly, I'm uncertain how this will go down with a tbody, so you may wind up needing to delete the whole table and then re-draw the whole table, but that's not a certain thing.
Turns out the best practical answer I've come up with is to rework my page using knockout.js.
(http://learn.knockoutjs.com/#/?tutorial=intro).
By binding my view to observables. I will save the trouble of ever having to deal with those situations again.

Can't display the json data which I got from my woocommerce store to another website

I want to post the detail of woocommerce orders like id, address, name etc of my woocomerce website to a page of another website of mine. I am getting responses in http://www.baruipurjn.in/wp-json/wc/v2/orders. I want to post the order details. I have successfully included the jQuery file in my functions.php file. My jQuery code is here. I am completely new in json and jquery. Please help.
jQuery(function($){
$.getJSON( "http://www.baruipurjn.in/wp-json/wc/v2/orders", function(data) {
var ordersData='';
$.each(data, function(key,value){
ordersData += "<tr>";
ordersData += "<td>" + value.id + "</td>";
ordersData += "<td>" + value.number + "</td>";
ordersData += "<td>" + value.total + "</td>";
ordersData += "</tr>";
});
$("orders").append(ordersData);
});
});
The id of the table where I want to put the data is "orders"

Jquery AJAX success doesn't work in Firefox (only in this script other works well)

I've 4 script with ajax but one of them doesn't works in Firefox.
It put an alert in success & it dosen't work too.
I've no error message but nothing happen.
It works very well in IE & Chrome.
Here my code :
/* Latest compiled and minified JavaScript included as External Resource */
$.ajax(
{
type: "GET",
url: "../processeur.php",
dataType: "json",
data: dataString,
cache:false,
success: function(response)
{
alert("success");
var options ="";
if(response != null)
{
for(var i=0; i<response.data.length; i++)
{
options +="<option value = '"+response.data[i]+"'>"+response.data[i];"</option>";
}
}
$("#Liberation tbody").append
(
"<tr>"+
"<td align='center'><input class='liberationL' name='liberationL' type='text'/></td>"+
"<td align='center'><input class='serviceL' name='serviceL' type='text'/></td>"+
//liste déroulante des codes projets destinataires
"<td align='center'>"+"<select class='codest' name ='codest' id=listecodes >"+"<option>Aucun</option>"+options+"</select>"+"</td>"+
//"<td align='center'><input class='dateL' name='dateL' type='text'/><span><br>jj-mm-AAAA</span></td>"+
"<td align='center'><input type='text' class='dateL' id='DateF' name='dateL' onclick='javascript:onCalendar_click();'/></td>"+
"<td align='center'><input class='montantL' name='montantL' type='text'/></td>"+
//liste déroulante des types de mouvements
"<td align='center'>"+"<select class='mouvementL' name='mouvementL'>"+"<option value='lc'>LC(-)</option>"+"<option value='vc'>VC(+)</option>"+"<option value='ci'>CI</option>"+"</select>"+"</td>"+
"<td align='center'>"+
"<img src='../images/enregistrer.png' class='btnEnregistrerLiberation'"+"style='cursor: pointer;'/>"+' '+"<img src='../images/supprimer.png' class='btnSuppLiberation'"+"style='cursor: pointer;'/>"+"</td>"+
"</tr>"
);
$(".btnEnregistrerLiberation").bind("click", EnregistrerLiberation);
$(".btnSuppLiberation").bind("click", SupprimerLib);
},
failure: function()
{
alert("error");
}
});
Here my php code, where data is encoded with json_encode :
include './BD/T_mouvements.php';
include '../sql.php';
require './jsonwrapper/jsonwrapper.php';
$idProg = $_GET['idProg'];
$exercice = $_GET['exercice'];
$array = array();
$liste = selectionnerListePro($exercice, $idProg);
echo json_encode(array('data'=>$liste));
exit();
Ok, I found my problem.
In fact, my code was good but the bug was in my sql.php
The guy who coding before me, forget a ";"...
Thanks everybody :)

Parse Error JSON.Parse when using getJSON

It's my 1st time coding with JS & JSON & I've a error message when I used getJSON :
parsererror
SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
return window.JSON.parse( data );
Here my code :
$.getJSON("../processeur.php",{
idProg: idp,
exercice: exo,
ajax: "true"})
.done(
function(response)
{
// alert( "success" );
var options ="";
if(response != null)
{
var length = response.data.length;
for(var i=0; i<length; i++)
{
options +="<option value = '"+response.data[i]+"'>"+response.data[i];"</option>";
}
}
$("#Liberation tbody").append
(
"<tr>"+
"<td align='center'><input class='liberationL' name='liberationL' type='text'/></td>"+
"<td align='center'><input class='serviceL' name='serviceL' type='text'/></td>"+
//liste déroulante des codes projets destinataires
"<td align='center'>"+"<select class='codest' name ='codest' id=listecodes >"+"<option>Aucun</option>"+options+"</select>"+"</td>"+
// "<td align='center'><input class='dateL' name='dateL' type='text'/><span><br>jj-mm-AAAA</span></td>"+
"<td align='center'><input type='text' class='dateL' id='DateF' name='dateL' onclick='javascript:onCalendar_click();'/></td>"+
"<td align='center'><input class='montantL' name='montantL' type='text'/></td>"+
//liste déroulante des types de mouvements
"<td align='center'>"+"<select class='mouvementL' name='mouvementL'>"+"<option value='lc'>LC(-)</option>"+"<option value='vc'>VC(+)</option>"+"<option value='ci'>CI</option>"+"</select>"+"</td>"+
"<td align='center'>"+
"<img src='../images/enregistrer.png' class='btnEnregistrerLiberation'"+"style='cursor: pointer;'/>"+' '+"<img src='../images/supprimer.png' class='btnSuppLiberation'"+"style='cursor: pointer;'/>"+"</td>"+
"</tr>");
$(".btnEnregistrerLiberation").bind("click",EnregistrerLiberation);
$(".btnSuppLiberation").bind("click",SupprimerLib);
})
.fail(function(jqxhr, textStatus, err){
alert( "error : " + textStatus );
console.log( textStatus, err );
});
Here my php code :
include './BD/T_mouvements.php';
include '../sql.php';
require './jsonwrapper/jsonwrapper.php';
$idProg = $_GET['idProg'];
$exercice = $_GET['exercice'];
$array = array();
$liste = selectionnerListePro($exercice, $idProg);
//$liste = selectionnerListePro(2011, 4);
foreach ($liste as $item)
{
$array[] = array($item);
}
echo "{\"data\":". json_encode($array) . "}";
exit();
And here the result of my php code when parameters are choose manually for function which runs query (for exemple 2011 & 4) :
{"data":[["DEV-SID"],["ENTREPOTDUI"],["HYDROGEOL"],["MES-TEMPS"],["MET-ENTREPO"],["MIG-BO\/XI"],["SID-AMODG"],["SID-ARCHID"],["SID-DSI"],["SID-FNGE"],["SID-OT-POL"],["SID-PILOTAG"],["SID-USAGRH"],["SIG-3D"],["SIG-ALTERNA"],["SIG-BDTOPO"],["SIG-CAO-DAO"],["SIG-DON-PDI"],["SIG-DONNEES"],["SIG-ORTHO"],["SIG-PLATGEO"],["SIG-STRUCTU"],["SIG-TOURNEE"],["SIG-WEB-PDI"],["STAT-CREDOC"]]}
I don't understand where is my bug..
The json_encode() function will do everything for you. Just create the data structure you want as an array or an object and the leave json_encode() to do all the hard work.
So change echo "{\"data\":". json_encode($array) . "}"; to
echo json_encode( array('data'=>$array) );
I am also fairly sure you can remove some unnecessary code from your script. You seem to be getting an array of arrays back from selectionnerListePro() and then processing that array of arrays into another array of arrays, but making no modifications in the process.
So this
$liste = selectionnerListePro($exercice, $idProg);
//$liste = selectionnerListePro(2011, 4);
foreach ($liste as $item)
{
$array[] = array($item);
}
echo json_encode( array('data'=>$array) );
Could be reduced to
$liste = selectionnerListePro($exercice, $idProg);
echo json_encode( array('data'=>$liste) );
I tried to do this with AJAX, & it finally works !! Here my code :
$.ajax(
{
type: "GET",
url: "../processeur.php",
dataType: "json",
data: dataString,
success: function(response)
{
//alert("success");
var options ="";
if(response != null)
{
for(var i=0; i<response.data.length; i++)
{
options +="<option value = '"+response.data[i]+"'>"+response.data[i];"</option>";
}
}
$("#Liberation tbody").append
(
"<tr>"+
"<td align='center'><input class='liberationL' name='liberationL' type='text'/></td>"+
"<td align='center'><input class='serviceL' name='serviceL' type='text'/></td>"+
//liste déroulante des codes projets destinataires
"<td align='center'>"+"<select class='codest' name ='codest' id=listecodes >"+"<option>Aucun</option>"+options+"</select>"+"</td>"+
// "<td align='center'><input class='dateL' name='dateL' type='text'/><span><br>jj-mm-AAAA</span></td>"+
"<td align='center'><input type='text' class='dateL' id='DateF' name='dateL' onclick='javascript:onCalendar_click();'/></td>"+
"<td align='center'><input class='montantL' name='montantL' type='text'/></td>"+
//liste déroulante des types de mouvements
"<td align='center'>"+"<select class='mouvementL' name='mouvementL'>"+"<option value='lc'>LC(-)</option>"+"<option value='vc'>VC(+)</option>"+"<option value='ci'>CI</option>"+"</select>"+"</td>"+
"<td align='center'>"+
"<img src='../images/enregistrer.png' class='btnEnregistrerLiberation'"+"style='cursor: pointer;'/>"+' '+"<img src='../images/supprimer.png' class='btnSuppLiberation'"+"style='cursor: pointer;'/>"+"</td>"+
"</tr>");
$(".btnEnregistrerLiberation").bind("click",EnregistrerLiberation);
$(".btnSuppLiberation").bind("click",SupprimerLib);
},
error: function(jqxhr, textStatus, err){
alert( "error : " + textStatus );
console.log( textStatus, err );
}
});

Event doesn't work when element isn't loaded directly

I have a table with many checkboxes which is generated with Ajax :
$.ajax({
type: "GET",
url: "jsonDevisUtilisateur.php?ra=" + $('#ra').val(),
success: function(data) {
var table = "<table class='dvs'><tr><td>Numéro</td><td>Client</td><td>Site</td><td>Libellé</td><td>Statut</td><td></td></tr>"
for (var i = 0; i < data.length; i++) {
table += "<tr><td>" + data[i].numDevis + "</td>";
table += "<td>" + data[i].client + "</td>";
table += "<td>" + data[i].site + "</td>";
table += "<td>" + data[i].libelle + "</td>";
table += "<td>" + data[i].statut + "</td>";
table += "<td><input type='checkbox' class='box' value='" + data[i].id + "' name='box[]'></td></tr>"
}
table += "</table>";
document.getElementById('devis').innerHTML = table + "<br/><br/>";
}
});
This part is working well !
The problem is when I'm trying to integrate a "select all" button.
My Javascript for it :
$(document).ready(function() {
$("#selectall").on("change", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
});
When my select all checkbox : <input type='checkbox' id='selectall' name='selectall'> is created on the same time than my HTML, it works.
But if I create my <input type='checkbox' id='selectall' name='selectall'> in my TABLE with my ajax function, it doesn't work, and nothing happens.
I'm pretty sure it is because the event is set to "selectall" at the load of the page but it doesn't exist yet and it doesn't look for it later.
What would be the solution ? Thanks for help
You can use event delegation as follow:
$('#devis').on("change", "#selectall", function(e) {
$("input[type=checkbox]").prop("checked", $(this).prop("checked"));
});
You are right in your thinking :
If your selectall checkbox is created after the document ready code execution, jquery can't find it (as it's not created yet).
I won't recommand using the live function as it is deprecated and can be removed in futur version of jquery.
You can still use the on function but with a little modification :
$("#devis").on("change", "#selectall",function(e) {
Note that #mycontainer MUST exist on document load.
If you can't place a container, this will always work :
$("body").on("change", "#selectall",function(e) {

Categories

Resources