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 );
}
});
Related
I want to add a value in the input text valor and assign this value to the row where it is, for this I need pass to the update query ID and the valor.
What am I doing wrong?
Table
<?php
$IDTipoEquipamento = $_POST['Car'];
$result = mysqli_query($conn,"SELECT tipocaracteristicas.IDTipoCaracteristicas,tipoequipamento.TipoEquipamento, caracteristicas.Caracteristica, Valor FROM `tipocaracteristicas` LEFT JOIN tipoequipamento on tipoequipamento.IDTipoEquipamento= tipocaracteristicas.IDTipoEquipamento LEFT JOIN caracteristicas on caracteristicas.IDCaracteristicas=tipocaracteristicas.IDCaraterisiticas WHERE tipocaracteristicas.IDTipoEquipamento= '$IDTipoEquipamento';");
echo "<table width='100% class='sortable' id='datatables-example'>
<tr>
</tr>
<tr>
<td class='pure-table'></td>
<td class='pure-table'><b>Tipo de Equipamento</b></td>
<td class='pure-table'><b>Caracteristica</b></td>
<td class='pure-table'><b>Valor</b></td>
<td class='pure-table'><b>Atribuir</b></td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
echo "<td><a href='' onclick='UpdateTable()'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo"<br>";
echo "</table>";
mysqli_close($conn);
}
?>
Jquery + Ajax
<script type="text/javascript">
function UpdateTable() {
$("#valor").on('input', function() {
var valor = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor},
async: false,
dataType:'html',
success:function(data) {
$("#valor").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
$("#IDTipoCaracteristicas").on('input', function(){
var IDTipoCaracteristicas = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{IDTipoCaracteristicas:IDTipoCaracteristicas},
async: false,
dataType:'html',
success:function(data) {
$("#IDTipoCaracteristicas").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
}
</script>
PHP UPDATE QUERY PAGE
<?php
include ('conetar.php');
if(isset($_POST['valor'], $_POST['IDTipoCaracteristicas'])){
$valor = $_POST['valor'];
$IDTipoCaracteristicas= $_POST['IDTipoCaracteristicas'];
$sql = "UPDATE `tipocaracteristicas` SET `Valor`='$valor' WHERE `IDTipoCaracteristicas`= '$IDTipoCaracteristicas'";
if(mysqli_query($conn,$sql)){
} else{
echo "ERROR: Could not able to execute $sql. ";
}
mysqli_close($conn)
}
?>
See the below two statements here,
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
^^^^^^^^^^^^^^^^^^^^^^^^^
and
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
^^^^^^^^^ ^^^^^^^^
You're assigning the same id for all of your table rows, use class instead. Assign class to each of your IDTipoCaracteristicas, Valor input elements as well as to the update table hyperlinks. Furthermore, you didn't assign any value in Valor input element. Also, make the anchor tags non-linkable using javascript:void(0);, otherwise you'll get redirected every time you click on a link. So your while() loop should be like this:
while($row = mysqli_fetch_array($result)) {
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' class='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' class='valor' value='". $row['Valor'] ."'></td>";
echo "<td><a href='javascript:void(0);' class='updateTable'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
Subsequently, your jQuery/AJAX code should be like this:
<script>
$(document).ready(function(){
$(document).on('click', '.updateTable', function(){
var IDTipoCaracteristicas = $(this).parents('tr').find('.IDTipoCaracteristicas').val();
var valor = $(this).parents('tr').find('.valor').val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor, IDTipoCaracteristicas: IDTipoCaracteristicas},
async: false,
success:function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>
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 :)
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 />");
I have a PHP-file with multiple php functions in it.
I am sending a Javascript Variable with an AJAX-call, POST method to that PHP-file.`
Now the variable IS accessible in my PHP-file but not in that specific function where I want it...
$("#dropdown").change(function () {
var value = $("#dropdown").val();
console.log(value);
$.ajax({
type: "POST",
dataType: 'text',
url: "PhpFunctions.php",
data: {id:$("#dropdown").val()},
success: function (data) {
console.log(data);
$("div.geselecteerdVliegtuig").fadeIn("slow", function () {
console.log("Vliegtuigdetail faded in");
});
/*
$("div.vliegtuigenEnabled2").hide();
console.log("vliegtuigEnabled ID's hidden");
*/
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL`
//I CAN ACCESS DATABASE AND ID IS ACCESSIBLE HERE
//Connect to server
$connect = mysql_connect("localhost", "root", "root") or die(mysql_error());
//Connect to database
$select_db = mysql_select_db("Luchthaven") or die("Could not find database");
$id = $_POST['id'];
echo $id; //WORKS
//NEED TO ACCESS IS HERE
function GeselecteerdVliegtuig() {
makeConnection();
//Query the database
$id = $_POST['id'];
//$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';";
//echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';<br/>";
$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';";
echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';<br/>";
$fetch = mysql_query($query) or die("could not fetch data");
while ($row = mysql_fetch_assoc($fetch)) {
echo "<tr id=" . $row['vliegtuig_ID'] . ">";
echo "<td>" . $row['vliegtuig_ID'] . "</td>";
echo "<td>" . $row['maatschappij'] . "</td>";
echo "<td>" . $row['lengte'] . "</td>";
echo "<td>" . $row['breedte'] . "</td>";
echo "<td>" . $row['kilometerstand'] . "</td>";
echo "<td>" . $row['bouwjaar'] . "</td>";
echo "<td>" . $row['bereik'] . "</td>";
echo "<td>" . $row['aantalMotoren'] . "</td>";
echo "</tr>";
} // END WHILE
mysql_close(); //Make sure to close out the database connection
echo "<b>Connection closed<b><br/><br/>";
}
You can pass the $_POST['id'] variable to that function GeselecteerdVliegtuig($id) and call the function with GeselecteerdVliegtuig($_POST['id'])
Get rid of this line:
$id = $_POST['id'];
as you might want to use your functionality even if your value is not located in your $_POST["id"]. Modify your function header from
function GeselecteerdVliegtuig() {
to
function GeselecteerdVliegtuig($id) {
Call your function this way:
if (isset($_POST['id'])) {
GeselecteerdVliegtuig($_POST['id']);
}
and call your function from the page where you posted the value, make sure that the page where you posted exists, works and responds.
Finally, when everything is working change the way you are working with the database, because your current approach has a security leak due to SQL injection possibilities. What if I visit your page and execute the following in the console:
$("#dropdown").val("0'; delete from vliegtuig where '' = '");
and then trigger the post? It will remove every single record from your table unless you are making sure that these attempts fail.
I have a table that third column of it is checkboxe, and first two columns of it come from database
I want to send the wordID of words that checked:
$result = mysql_query("SELECT * FROM words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
and in my function I have this:
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign=1;
}
else{
assign=0;
}
$.ajax({
url: "assigner.php",
type: "POST",
data: { wordid: wordid, assign: assign}
}).done(function( e ) {
/*alert( "word was saved" + e );*/
});
}
}
I dont know how can I get WordId from the first part and use it in second part that I said
Just put another form element outside of the table, like:
<input type="hidden" value="[id]" name="wordid_name" id="worid_id" class="wordid_class">
You only have to replace [id] with the id of the row, then on Javascript you can call the attribute you prefer:
var wordid= document.getElementsByClassName('worid_class').value;
var wordid= document.getElementsById('worid_id').value;
var wordid= document.getElementsByName('worid_name').value;
Can make it outside for structure, just below var boxex.
I recommend you to create an Javascript object with the values of the checkboxes and then call just 1 time to Ajax.
Hope it helps you.