How to use JSON.parse or eval () to display an array? - ajax

I have this code to save values ​​in json string in a session variable, which I call from ajax
I have the following code:
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
})
.done(
//this is the callback function, which will run when your POST request returns
function(postData){
//Make sure to test validity of the postData here before issuing the GET request
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (getData) {
session = getData;
alert(session);
});
}
);
});
}}
})( jQuery );
I have the following code that works fine, I just printed the following alert:
["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"]
and I need to have something like this:
[
{
title:"Cro Magnon Man",
artist:"The Stark Palace",
mp3:"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"
},
{
title:"Hidden",
artist:"Miaow",
mp3:"http://www.jplayer.org/audio/mp3/Miaow-02-Hidden.mp3"
}
]
How I can work this data with jquery?
thank's

Assuming the data is stored in a variable called yourObject you can do:
var result = JSON.parse("["+yourObject[0]+"]");
Here is a working bin

This is what JSON.parse() was designed to do. Eval() is not the approach to use here. To clarify, JSON.parse() takes valid, appropriately escaped JSON strings and converts them into usable objects within Javascript. eval(), on the other hand, is designed to take strings and attempt to EXECUTE them as Javascript functions, objects, variables, etc.

Your sample input is actually an array of strings. You need to parse each element within the array as an object. Using jQuery:
var input = ["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"];
var resultArray = new Array();
for(var i = 0; i < input.length; i++){
var parsedElement = $.parseJSON(input[i]);
resultArray.push(parsedElement);
}

var display = JSON.stringify(jsonObject, undefined, 2); // indentation level = 2

Related

Datatable info is lost after i do a flitered search

I'm having a problem with a data table, whenever I use the search function in my table all the data is lost the moment I input anything on the search bar, I create this data table dynamically using AJAX, first I do a request to the server to get the data for my table.
function traerBecas() {
var ciclo = document.getElementById("ciclo").value;
$.ajax({
url: '/becas/listaBecas',
type: 'GET',
data: {
"ciclo": ciclo,
},
dataType: 'JSON',
success:function(response){
llenarTabla(response);
}
});
}
Once I get the response as a JSON I pass the info to another function to build each table row and insert it into the table.
function llenarTabla(jsonArray) {
var tabla = document.getElementById('becaBody');
tabla.innerHTML = "";
jsonArray.forEach(element => {
var trElement = document.createElement('tr');
var tdCLVBECA = document.createElement('td');
var tdINSTIT = document.createElement('td');
var tdCICLO= document.createElement('td');
var tdSECCION = document.createElement('td');
var tdFECINI = document.createElement('td');
var tdFECFIN = document.createElement('td');
var tdACCIONES = document.createElement('td');
var linkEditar = document.createElement('a');
var linkEliminar = document.createElement('a');
tdCLVBECA.innerText = element.CLV_BECA;
tdINSTIT.innerText = element.INSTIT.toUpperCase();
tdCICLO.innerText = element.CICLO;
tdSECCION.innerText = element.SECCION;
tdFECINI.innerText = element.FEC_INI;
tdFECFIN.innerText = element.FEC_FIN;
linkEditar.setAttribute("href","/becas/editar/"+element.CLV_BECA);
linkEditar.setAttribute("data-bs-toggle", "tooltip");
linkEditar.setAttribute("data-bs-placement", "top");
linkEditar.setAttribute("title", "Eliminar");
linkEditar.innerHTML = "<i class='fas fa-pen'></i>";
linkEliminar.setAttribute("onclick", "eliminacion("+element.CLV_BECA+")");
linkEliminar.setAttribute("data-bs-toggle", "tooltip");
linkEliminar.setAttribute("data-bs-placement", "top");
linkEliminar.setAttribute("title", "Editar");
linkEliminar.innerHTML = " <i class='fas fa-trash'></i>";
tdACCIONES.appendChild(linkEditar);
tdACCIONES.appendChild(linkEliminar);
trElement.appendChild(tdCLVBECA);
trElement.appendChild(tdINSTIT);
trElement.appendChild(tdCICLO);
trElement.appendChild(tdSECCION);
trElement.appendChild(tdFECINI);
trElement.appendChild(tdFECFIN);
trElement.appendChild(tdACCIONES);
tabla.appendChild(trElement);
});
}
Then I have the function to transform my table to a data table, and up to this moment, everything works alright. EDIT: Forgot to mention that this info is run first when the page is loaded, the table at the beginning is empty and then is filled with the info I requested.
$(document).ready(function() {
$('#myTable').DataTable({
responsive: true,
language: {
url: '//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json'
}
});
});
Then, once I have my table built, I try to use the search function that it generates, but then I run into the problem that the table doesn't find the info, loses the data, and doesn't return to the previous state once I delete the prompt on the search bar.
I'm at a loss of what to do, I have other data tables that don't have this problem, however, those tables aren't built using AJAX, they get their info directly from the controller with the compact() function in the PHP controller, and using Blade directives like #foreach loops.
You should open up your browser's dev tools and inspect the network request to your endpoint:
url: '/becas/listaBecas'
It could be a number of things, the network tab will show you if there is an error with the AJAX request. If the AJAX request has no error, you will want to look at your endpoint and debug the query that is being run to see why it's not returning any results.
Would also be a good idea to add a error catch for the AJAX call:
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request");
}

How can I get the results of two SQL-Queries in PHP in one JS function with AJAX?

I am a complete beginner and I hope that you can help me.
In my php file I make two different database queries and I need their results for calculations in a js function, which in turn should be displayed in the browser.
If I try to display the results from both queries, only "undefined" is returned. However, they are displayed to me in the console, where I also have the numbers output via consol.log (data). I am trying this with the help of ajax. If I remove the part from the second DB query in my function, it works. Unfortunately not all together. What am I doing wrong? Is what I plan to do even possible or do I have to take a detour? If yes, which one?
Here is my previous code:
Javascript:
function clickPHPtoJS(){
$.ajax({
url: "index.php",
type: "POST",
success: function(data) {
console.log(data);
clickPHPtoJSResponse(data);
},
error: function (data) {
console.log("Daten nicht erhalten");
}
});
}
function clickPHPtoJSResponse(data) {
// Antwort des Server ggf. verarbeiten
var response = JSON.parse(data);
var einer = response.einer;
var zwoelfer = response.zwoelfer;
var anzahl = response.nr;
document.getElementById("lab1er").innerHTML = einer + " " + zwoelfer + " " + anzahl;
}
PHP:
<?php
require 'inc/db.php';
$erg = $db->query("SELECT id, sender FROM packaging_log WHERE sender='test' AND packaging='1er'")
or die($db->error);
$gesteigereiner = $db->query("SELECT * FROM geliefert WHERE 1")
or die($db->error);
while ($zeile = $gesteigereiner->fetch_object()) {
$einer = $zeile->test1er;
$dreier = $zeile->test3er;
$sechser = $zeile->test6er;
$zwoelfer = $zeile->test12er;
}
$geliefert = array ( "nr" => $erg->num_rows,
"einer" => $einer,
"zwoelfer" => $zwoelfer);
print_r (json_encode($geliefert));
?>
Unfortunately, that's not how it works. But if I completely remove the result from the first DB query in the JS.
Many thanks in advance. I am grateful for any information, clarification and tips.
The problem was the following: "nr" => $erg->num_rows
To get what I wanted I had to save $erg->num_rows as a variable and to put the variable into the array.
So first step: $nr= $erg->num_rows;
Second step: "nr" => $nr

Filling a form in JSP with ajax

I know this kind of questions has already been asked, but I totally am a newbie with Ajax and JavaScript.
I have a field (codigo_caso) which I need to be the launcher for the form filling
<input id="codigo_caso" autofocus="autofocus" type="text" name="codigo_caso" value=""/>
I have to retrieve 4 variables after loosing focus on that field (or 1 variable if the other 4 are empty)
And the big problem after retrieving those 4 variables is how to work well with them.
JSP Web Page --> Script
This is the fragment i copied from the internet and modified to receive ONE field
$(document).ready(function() {
$("#codigo_caso").blur(function() {
var cod = $(this).val();
var dataString1 = {"codigo":cod};
$.ajax({
type: "GET",
url: "otros/codigoCasoDependienteNuevaTarea.jsp",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: dataString1,
cache: false,
success: function(response) {
$(".linea_equipo").response("linea_equipo");
$("#selectArea").filter(function() {
return $(this).response("id_area") === response("area");
}).prop('selected', true);
$(".listaCentros").response("nombre_centro");
$("#listaRolNuevaTarea").filter(function() {
return $(this).response("id_rol") === response("rol");
}).prop('selected', true);
}
});
});
});
This is my JSP file launching the SQL [where i need to recover several variables]. I need to know how to return these 3 fields to my previous JSP
JSP FILE --> otros/codigoCasoDependienteNuevaTarea.jsp
String linea = "", centro = "", error = "No existe el caso indicado";
int area, rol;
Connection conex = (Connection) session.getAttribute("conexion");
Statement st = conex.createStatement();
String sql = "";
String cod = request.getParameter("codigo").toString();
if (cod != null && !cod.isEmpty() && !cod.equals("0")) {
sql = "SELECT t1.linea_equipo,t1.id_rol, t2.id_area,t2.nombre_centro "
+ " FROM gen_casos_prisma t1 LEFT OUTER JOIN gen_centros t2 ON "
+ " t1.id_centro = t2.id_centro "
+ " WHERE "
+ " t1.CODIGO_CASO = " + cod;
ResultSet rs = st.executeQuery(sql);
rs.beforeFirst();
if (rs.next()) {
linea = rs.getString("linea_equipo");
area = rs.getInt("id_area");
centro = rs.getString("nombre_centro");
rol = rs.getInt("id_rol");
JSONObject j = new JSONObject();
j.put("linea_equipo", linea);
j.put("id_area", area+"");
j.put("nombre_centro", centro);
j.put("id_rol", rol+"");
} else {
/* return variable error */
}
response.setContentType("application/json");
}
The next step after knowing how to receive these fields is to know what to do with them. i know how can i place linea_equipo in a text-field [with the code I posted in the script above the JAVA code] but i also need to set as "selected" one option in each of these lists (two are dropdown lists and the other is a datalist) taking into account that they are already filled; just need to place selected attribute in the value that matches the field that the form must receive from this ajax-jsp thing.
(selectArea - id_area, listaCentrosDeArea - nombre_centro, listaRolNuevaTarea - id_rol)
<select id="selectArea" >
<%out.print(f.getSelectAreas(conex));%>
</select>
<datalist id="listaCentrosDeArea" id="datalist1">
<% //out.print(f.selectCentrosNOUser(conex, updateTarea));%>
</datalist>
<select id="listaRolNuevaTarea" name="rol">
<% out.print(f.selectRolesNoUser(conex));%>
</select>
Sorry if it seems a bit tricky or heavy, but I've been requested to do this and I have no idea.
when you are doing
success: function(html) {
("#linea_equipo").val(html);
}
you are returning the value to the JSP, so just make sure that all the elements that you want filled in have an id like linea_equipo
In the success part of your code you can write the logic to populate data to your form.
success: function(response)
{
$("#ID").val("value");//find these value from your response
// if your response is JSON you can replace value like response.key
}
see what json is
For selecting a drop down by jQuery use
$('#dropdownid').val('selectedvalue');
//========
code to return response as json in java servlet
response.setContentType("application/json");
response.getWriter().write(jsonobject.toString());

Ajax.request not working

I am sorting a list using scriptaculous, i can't get the ajax request part to work.
This is my code:
<script type="text/javascript">
Sortable.create("images_list", {
onUpdate: function() {
var list = Sortable.serialize("images_list");
alert(list);
new Ajax.Request('processor.php', {
method: 'post',
parameters: { data: list }
});
}
});
I Have alerted out the serialize string, this part is working fine:
images_list[]=18&images_list[]=19&images_list[]=21&images_list[]=22&images_list[]=20
So the sorting is working fine, however the data string doesn't seem to be available in the processor.php
<?php
//Connect to DB
require_once('connect.php');
parse_str($_POST['data']);
for ($i = 0; $i < count($images_list); $i++) {
$id = $images_list[$i];
mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'");
}
?>
Any ideas why the data is not getting posted? I have tested to see if the processor.php page is actualy being invoked, and it is.
Thank you
When method = 'post', you need to use "postBody" instead of "parameters" for having parameters posted to your server side script

jqGrid display default "loading" message when updating a table / on custom update

I have a case where I need to update a jqgrid based on some search criteria which the user selects. I can get the data to update , but I would want the loading message to show while the new data is being fetched. Can someone please let me know how to get that working ?
Current code follows
var ob_gridContents = $.ajax( {
url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data : "portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val(),
async : false
}).responseText;
var ob_Grid = jQuery('#OBGrid')[0];
var ob_GridJsonContents = eval('(' + ob_gridContents + ')');
$('#ob_Grid').trigger("reloadGrid");
ob_Grid.addJSONData(ob_GridJsonContents);
ob_Grid = null;
ob_GridJsonContents = null;
}
If I correct understand what you will, I can recommend you to use jQuery blockUI plugin (http://malsup.com/jquery/block/). Then you don’t need more to use "async : false" parameter of $.ajax function and do something like following:
var WaitMsg = function () {
jQuery('#main').block({ message: '<h1>Die Daten werden vom Server geladen...</h1>' });
};
var StopWaiting = function () {
jQuery('#main').unblock();
};
WaitMsg();
$.ajax({url : '/DisplayObAnalysisResults.action?getCustomAnalysisResults',
data: jQuery.param({portfolioCategory: $('#portfolioCategory').val(),
subPortfolioCategory: $('#subPortfolioCategory').val(),
subportfolio: $('#subportfolio').val()}),
complete: function (data, status) {
if (status === "success" || status === "notmodified") {
var ob_GridJsonContents = jQuery.parseJSON(data.responseText);
...
}
StopWaiting();
},
error: function (xhr, st, err) {
// display error information
StopWaiting();
}
});
I recommend you don’t build parameters with the way like
"portfolioCategory="+ $('#portfolioCategory').val()
+"&subPortfolioCategory="+ $('#subPortfolioCategory').val()
+ "&subportfolio=" + $('#subportfolio').val()
because you can receive encoding problems, if data returned by .val() have some special characters. You could use JavaScript function encodeURIComponent in such cases (like encodeURIComponent($('#portfolioCategory').val()))
or jQuery.param function if you construct a string like p1=val1&p2=val2&...pN=valN.
Best regards
Oleg

Resources