Get JSon data with Ajax - javascript

can you guys help me, I am not really a JS dev so i am polling my hair out with this one.
i'm working with Ajax to display data from a json file...but it doesn't work, i put console.log almost everywhere to see result but it won't work, here's my code:
encode data:
// Inclusion du ficher de fonction permettant de démarrage du contexte de l'applicaiton
Include $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR."Includes".DIRECTORY_SEPARATOR."Functions".DIRECTORY_SEPARATOR."functions.php";
// Initialisation des variables
$action = '';
$pValue = '';
$pType = '';
$pRegion = '';
$currenthyperviseur = new hyperviseur();
$currentregion = new region();
// Récupération de l'action passée au webservice
if(isset($_REQUEST['action']) && $_REQUEST['action']!= "") {$action = $_REQUEST['action']; }
if(isset($_REQUEST['pValue']) && $_REQUEST['pValue']!= "") {$pValue = base64_decode($_REQUEST['pValue']); }
if(isset($_REQUEST['pType']) && $_REQUEST['pType']!= "") {$pType = $_REQUEST['pType']; }
if(isset($_REQUEST['pRegion']) && $_REQUEST['pRegion']!= "") {$pRegion = $_REQUEST['pRegion']; }
// Gestion de l'ensemble des cases du web service
switch($action)
{
//
// Permet la récupération de données dans l'Hyperviseur (GET)
//
case 'H_getAlmBacPFull' : echo json_encode($currenthyperviseur->getListAlarmeBac(1)); break;
case 'H_getAlmBacTFull' : echo json_encode($currenthyperviseur->getListAlarmeBac(2)); break;
case 'H_getGrpBacTFull' : echo json_encode($currenthyperviseur->getListAlarmeQualifBac()); break;
case 'H_getAlmDetails' : echo json_encode($currenthyperviseur->getAlarmeDetails($pValue)); break;
case 'H_getGrpDetails' : echo json_encode($currenthyperviseur->getGroupeDetails($pValue)); break;
//
// Permet la MAJ de données dans l'Hyperviseur (SET)
//
case 'H_setCheckAlm' : echo $currenthyperviseur->setAlarmeCheckAction($pValue); break;
case 'H_setGroupAlm' : echo $currenthyperviseur->setGroupAlarme($pValue); break;
case 'H_setAlmIdGrp' : echo $currenthyperviseur->setAlarmeIdGrp($pValue); break;
//
// Permet la récupération de données pour le module 'HyperViseur MoreDetails' (GET)
//
case 'HVMD_getContentBloc' : echo json_encode($currenthyperviseur->getContentBloc($pType, $pValue)); break;
//
// Permet la récupération de données pour le module 'Region' (GET)
//
case 'R_getListContentBloc' : echo json_encode($currentregion->getListContentBloc($pType)); break;
case 'R_getContentBloc' : echo json_encode($currentregion->getContentBloc($pType, $pRegion)); break;
//
// Permet la récupération de données pour le module la map des régions
//
case 'dashMap_getSite' : echo json_encode($dashMap_getSite($pRegion); break;
}
function dashMap_getSite($pRegion) to get data:
$dataArray = array();
if($pRegion == 'all')
{
$dataLine = array();
$dataLine['codeSite'] = "01014";
$dataLine['latitude'] = '46.2625';
$dataLine['longitude'] = '5.6380';
$dataLine['nom'] = 'Oyonnax 2';
$dataLine['nbAlm'] = 10;
$dataLine['critilevel'] = 2;
array_push($dataArray, $dataLine);
$dataLine = array();
$dataLine['codeSite'] = "04025";
$dataLine['latitude'] = '44.4242';
$dataLine['longitude'] = '6.7533';
$dataLine['nom'] = 'Barcelonette 3 Est TDF';
$dataLine['nbAlm'] = 0;
$dataLine['critilevel'] = 1;
array_push($dataArray, $dataLine);
}
return $dataLine;
And this second function getArrayOfSiteAjax() to display it with ajax
console.log(gWsProviderUrl);
$.ajax({
url: gWsProviderUrl + '?action=dashMap_getSite&pRegion=all',
type: 'POST',
dataType: 'json',
success:function(data){
console.log('arrayOfSite');
arrayOfSite = data;
$.each(arrayOfSite, function(currentIdx, currentValue){
console.log('codeSite => ' + currentValue.codeSite );
console.log('latitude => ' + currentValue.latitude );
console.log('longitude => ' + currentValue.longitude );
console.log('nom => ' + currentValue.nom );
console.log('nbAlm => ' + currentValue.nbAlm );
console.log('critilevel => ' + currentValue.critilevel);
});
console.log('heyy');
}
});
Thank you !

case 'dashMap_getSite' : echo json_encode($dashMap_getSite($pRegion); break;
That's a syntax error and should probably be
case 'dashMap_getSite' : echo json_encode(dashMap_getSite($pRegion)); break;
Because there was an error, the success callback didn't get called, an you don't get a message.
To display the data, you could do something like this:
// ...
success: function (data) {
var container = $('#container'); // the element in which you want to display the data
// loop over each item in the array
$.each(data, function (index, element) {
var outer = $('<div />');
// element is an object, loop over its properties
$.each(element, function (key, value) {
var inner = $('<div />');
inner.text(key + ': ' + value);
outer.append(inner);
})
container.append(outer);
});
}
// ...

Related

How to pass data from PHP to JS and to PHP again using an onclick function and AJAX

Imagine I have a CRUD table with a button to delete a register.
What I'm trying to do?
Basically, I want that, the parameters that there are in the function Delete() (3 variables), they arrive to me to PHP again by means of POST method so that with these data I can make the query and to delete the registry in the Database.
The information I want to pass on is as follows:
$data->id // Value example: 1
$tableName // Value example: users_test
$field // Value example: id
My button:
<button onclick='Delete($data->id, $tableName, $field)'>Delete</button>
My Delete JS function (basically I create a POST request sending an action to my PHP.
function Delete(id, tableName, field){
$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
action: "deleteRegistro"
}, function (data, status) {
if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
if (status === 'error') {
console.log("Not deleted"); // For debugging purpose
} else if (status === 'success') {
console.log("Deleted successfully");
}
}
else {
return false;
}
});
}
My PHP:
switch($_POST['action']){
case 'deleteRegistro':
$id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
$tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
$field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
break;
}
This if my full code if you need it:
<?php
use GuzzleHttp\json_decode;
include_once(DIR_PLUGINS.'/alexcrudgenerator/main.php');
$test = new GenerateCrud($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
if ($_GET['action']){
print_a($_GET['action']);
}
switch($_POST['action']){
case 'datosTabla': // OK.
//print_r($_POST['action']);
$res = json_decode($_POST['datos']);
echo json_encode($res, JSON_UNESCAPED_UNICODE);
break;
case 'deleteRegistro':
$id = $_POST['id']; // Quiero obtener estas variables que he enviado desde la función Delete();
$tableName = $_POST['tableName']; // Quiero obtener estas variables que he enviado desde la función Delete();
$field = $_POST['field']; // Quiero obtener estas variables que he enviado desde la función Delete();
break;
case 'showtable': // OK.
$res = getEntireTable($_POST['tableName'], $_POST['id'], $_POST['tableFields']);
$tableName = $_POST['tableName'];
$field = json_decode($_POST['tableFields'],1)[0];
//print_r($tableName);
//print_r('<br>');
//print_r($campo);
foreach ($res as $data){
$data->acción = "<div class='text-center'><div class='btn-group'><button id='modificar_$data->id' class='btn btn-primary btn-sm btnEditar' value='edit'><i class='material-icons'>edit</i></button><button onclick='Delete($data->id, $campo)' class='btn btn-danger btn-sm btnBorrar'><i class='material-icons' value='delete'>delete</i></button></div></div>";
$resultados['data'][] = $data;
}
$resultados = json_encode($resultados); // 7 PROPIEDADES
foreach(json_decode($_POST['tableFields']) as $columnsDB){
$fields[] = array('data'=>$columnsDB);
}
$fields[]['data'] = 'acción';
$fields = json_encode($fields);
?>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<div class="container caja">
<div class="row">
<div class="col-lg-12 col-sm-12">
<div>
<table id="tablaUsuarios" class="table table-striped table-bordered table-condensed hover" style="width:100%" >
<thead class="text-center">
<tr>
<?php
foreach (json_decode($_POST['tableFields']) as $columnsTH){
echo '<th>' . strtoupper($columnsTH) . '</th>';
}
echo '<th>ACCIÓN</th>';
?>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
function Delete(id,tableName, campo){
//$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/res/?action=deleteRegistro&tabla=" + tabla + "&nombre_campo=" + campo + "&id=" + id, function(data){
$.post("<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/", {
action: "deleteRegistro"
}, function (data, status) {
if (confirm("¿Estás seguro que deseas borrar el registro?") == true) {
if (status === 'error') {
console.log("Not deleted"); // For debugging purpose
} else if (status === 'success') {
console.log("Deleted successfully");
}
}
else {
return false;
}
});
}
$(document).ready(function() {
var datos= <?=$resultados?>;
var dynamicColumns = <?=$fields?>;
datos = JSON.stringify(datos);
$('#tablaUsuarios').DataTable({
"language": {"url": "https://cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json"},
"paging": true,
"lengthChange": true,
"searching": true,
"info": true,
"autoWidth": true,
"scrollX": true,
"ajax":{
"url": '<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/',
"method": 'POST',
"data":{action: "datosTabla", datos: datos}
},
"columns": dynamicColumns
});
})
</script>
<?php
break;
}
?>
May be you should try something, like this:
function Delete(id, tableName, field){
$.post(
"<?=SITE_URL_ADMIN?>/alexcrudgenerator/crud/res/",
{
action: "deleteRegistro"
id: id,
tableName: tableName,
field: field
},
function (success) {....}
)};
Have you forgotten id, tableName and field?
There is also the newer fetch.then
function ajaxpost (divid,var1,var2,var3) {
var pcache = (Math.floor(Math.random() * 100000000) + 1); // this is important to avoid browser cache
var postix = [];
postix["divid"] = encodeURIComponent(divid);
postix["var1"] = encodeURIComponent(var1);
postix["var2"] = encodeURIComponent(var2);
postix["var3"] = encodeURIComponent(var3);
postix["cookies"] = decodeURIComponent(document.cookie); // if you need to send cookies
postix["windowwidth"] = encodeURIComponent($(window).width()); // optional but cool if you need to retrive more that just text....
postix["windowheight"] = encodeURIComponent($(window).height());
// this code will retrieve ALL localStorage and sessionStorage to send to php if you need
for (var i = 0; i < localStorage.length; i++){ postix[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); }
for (var i = 0; i < sessionStorage.length; i++){ postix[sessionStorage.key(i)] = sessionStorage.getItem(sessionStorage.key(i)); }
fetch("/path_to_php.php?pcache="+pcache, {
method: "POST",
body: JSON.stringify(Object.assign({}, postix)),
headers: {"Content-type": "application/json; charset=UTF-8"}
}).then(function (response) { return response.text(); })
.then(function (html) { $("#"+divid).html(html); })
.catch( err => console.log() );
}

XHR Unable to Load with Django Project

I'm in traineeship in a company and I need to used the program of another trainee who programmed it in 2012. So I have done some update but I have a some problems :
When I press a button, I have a JS that make a xhr.get to recover a JSON. But I have this message on my firefox console :
Object { message: "Unable to load /query/?typeForm=com…", stack:".cache["dojo/errors/create"]/</</g#…", response: Object, status: 0,responseText: "", xhr: XMLHttpRequest }
My JS :
function queryDataGrid(map, stringForm) {
var test = "pouet";
require(["dojox/grid/DataGrid",
"dojo/store/Memory",
"dojo/data/ObjectStore",
"dojo/_base/xhr",
"dojo/domReady!",
"dojo/dom",
"dojo/_base/array"],
function(DataGrid, Memory, ObjectStore, xhr, arrayUtil, dom) {
var nodeDomGrid = dom.byId("datagrid");
window.alert("hey");
xhr.get({
url: "/query/",
form: dom.byId(stringForm),
handleAs: "json",
load: function(data) {
var nodeDomGrid = dom.byId("datagrid");
var nodeGrid = dijit.byId("datagrid");
var gridLayout = [];
var dataStore = new ObjectStore({ objectStore:new Memory({ data: data.fields }) });
console.log("store");
console.log(data.fields[0][1]);
globalData = data;
for(i in data.columns) {
gridLayout.push({
name: data.columns[i],
field: data.columns[i],
width: "auto"
})
}
nodeGrid.setStructure(gridLayout);
nodeGrid.setStore(dataStore);
var nodeMap = dom.byId("map");
columns = data.columns;
columnsToDisplay = []
numberColumn = 0;
for (i in columns) {
if (columns[i] == "Distance Fin") {
numberColumn = i
}
if (parseInt(i) > parseInt(numberColumn) && numberColumn != 0) {
columnsToDisplay.push({ value: columns[i], label: columns[i]});
}
}
dijit.byId("dataToColor").addOption(columnsToDisplay);
var vectorLayer = map.getLayersByName("KML")[0];
vectorLayer.removeAllFeatures();
var kmlFile = createKMLFile(data.kmldata, dom.byId("hiddenColor").value, dom.byId("sizeLine").value, dom.byId("colourPR").style.backgroundColor, dom.byId("sizePR").value);
var features = KMLToFeatures(kmlFile);
var bounds;
for(var i=0; i<features.length; ++i) {
if (!bounds) {
bounds = features[i].geometry.getBounds();
} else {
bounds.extend(features[i].geometry.getBounds());
}
}
vectorLayer.addFeatures(features);
console.log(vectorLayer);
map.zoomToExtent(bounds);
refreshLayer(vectorLayer);
if (stringForm == "commonQueriesForm" && dijit.byId("table").get("value") == "location") {
dom.byId("colourPalette").style.display = "block";
dom.byId("styleKML").style.display = "none";
}
else {
dom.byId("colourPalette").style.display = "none";
dom.byId("styleKML").style.display = "block";
}
},
// Message d'erreur à modifier
error: function() {
nodeDomGrid.innerHTML = "La requête a engendré une erreur.";
}
})
});
console.log(stringForm);
};
My Form :
<form id="commonQueriesForm" data-dojo-type="dijit.form.Form" onload="alert('test')">
<p>
<div id="commonDataTitlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title: 'Requêtes'">
<input type="text" name="typeForm" id="typeForm" value="common" style="display:none" />
<select name="table" id="table" class="cSelect" data-dojo-type="dijit/form/Select"
data-dojo-props="onChange:function(){ if (dijit.byId('table').get('value') == 'location') {dijit.byId('age').set('disabled', true); } else {dijit.byId('age').set('disabled', false); }}">
{% for key, value in dictTablesDatabase.items %}
<option value="{{ key }}">{{ key }}</option>
{% endfor %}
<option value="location">Repérages</option>
</select><br />
<select name="road" id="road" class="cSelect" data-dojo-type="dijit.form.Select" data-dojo-props="">
<option value="all">Toutes les routes</option>
{% for road in listRoad %}
<option value="{{ road|first|cut:' ' }}">{{ road|first|cut:' ' }}</option>
{% endfor %}
</select><br />
<select name="age" id="age" class="cSelect" data-dojo-type="dijit.form.Select" data-dojo-props="">
{% for age in arrayNumber %}
<option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>
</div>
<button type="executeButton" data-dojo-type="dijit.form.Button" onClick="queryDataGrid(map, 'commonQueriesForm');">Lancer la requête</button>
</p>
</form>
urls.py :
from django.conf.urls import include, url
from GSRBaseWeb.Home import views as myapp_views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'GSRBaseWeb.views.home', name='home'),
# url(r'^GSRBaseWeb/', include('GSRBaseWeb.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^home/$',myapp_views.home, name='home'),
url(r'^home/query', myapp_views.queryDataGrid, name='queryDataGrid'),
]
views.py :
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from GSRBaseWeb.Utils.utils import Utils
from GSRBaseWeb.DataAccess.databaseAccess import DatabaseAccess
from GSRBaseWeb.DataAccess.GSRBaseDLLAccess import GSRBaseDLLAccess
from ctypes import *
# Envoie les données nécessaires aux différents formulaires
def home(request):
dictToSend = {}
data = DatabaseAccess()
dictTablesDatabase = data.dataToDisplay()
dictToSend["dictTablesDatabase"] = dictTablesDatabase
# Sélection de l'ensemble des routes
queryRoads = "SELECT id_route, nom FROM routes"
listRoad = data.executeQuery(queryRoads)
dictToSend["listRoad"] = listRoad
# Liste pour les âges
arrayNumber = []
i = 0
while i < 20:
arrayNumber.append(i)
i += 1
arrayNumber.append("Tous")
dictToSend["arrayNumber"] = arrayNumber
# Liste pour les emplacements
arrayLocation = ["Tous", " ", "D", "C", "G"]
dictToSend["arrayLocation"] = arrayLocation
return render(request, 'Home/home.html', context=dictToSend)
# Récupère le contenu d'un formulaire et le traite en fonction du type de formulaire (commun, simple ou complexe)
def queryDataGrid(request):
# request.GET renvoie un QueryDict (objet Django)
print("YOLO")
parametersContent = request.GET
whatForm = parametersContent.getlist("typeForm")[0]
print(type(whatForm))
try:
accessDLL = GSRBaseDLLAccess()
except:
print(Exception.message())
if whatForm == "common":
table = parametersContent.getlist("table")[0]
road = parametersContent.getlist("road")[0]
if table != "location":
if parametersContent.getlist("age")[0] == "Tous":
age = 20
print("True")
else:
print("False")
age = int(unicode(parametersContent.getlist("age")[0]))
if road == "all":
road = ""
# on fait une requête sur les repérages
if table == "location":
result, number = accessDLL.requete_reperage(road)
else:
result, number = accessDLL.requete_table(table, road, age)
elif whatForm == "simple":
"""
On fait le traitement du formulaire de requêtes simples
Prendre en compte des ajouts des formulaires
On va prendre en compte les différentes lignes du formulaire et leur nombre """
listConditions = []
# Lignes des données
listQueries = dataProcessingForm("Simple", parametersContent)
# Checkout et les routes
conditionCheckout = parametersContent.getlist("conditionCheckout")[0]
conditionRoad = parametersContent.getlist("conditionRoad")[0]
conditionRoad = 'ROUTE()="' + conditionRoad + '"'
listConditions.append(conditionRoad)
# Lignes des conditions
j = 1
while j < 6:
if parametersContent.__contains__("conditionData" + str(j)) == True:
data = parametersContent.getlist("conditionData" + str(j))[0]
# On récupère la table de la condition
table = data.split(":")[0]
location = parametersContent.getlist("conditionLocation" + str(j))[0]
age = parametersContent.getlist("conditionAge" + str(j))[0]
condition = parametersContent.getlist("condition" + str(j))[0]
value = parametersContent.getlist("valueCondition" + str(j))[0]
conditionLine = "(" + data + condition
if (str(value).isdigit()):
conditionLine += str(value)
else:
conditionLine += '"' + str(value) + '"'
conditionLine += ' ET ' + table + ':generation=' + str(age) + ' ET ' + table + ':emplacement="' + location + '")'
if conditionCheckout == "anything":
conditionLine += "NON" + conditionLine
listConditions.append(conditionLine)
else:
break;
j += 1
##todo modifier la condition pour la Route(), ajouter un ET tout le temps
if conditionCheckout == "atLeast":
conditionQuery = ' OR '.join(listConditions)
elif conditionCheckout == "all":
conditionQuery = ' ET '.join(listConditions)
result, number = accessDLL.requete_avancee(listQueries, conditionQuery)
elif whatForm == "complex":
# On fait le traitement du formulaire de requêtes complexes
listQueries = dataProcessingForm("Complex", parametersContent)
conditionQuery = parametersContent.getlist("textareaConditions")[0]
result, number = accessDLL.requete_avancee(listQueries, conditionQuery)
json = ""
if number[0] > 0:
# json à renvoyer en fonction des données des formulaires
listResult = []
i = 0
while i <= number[0]:
listResult.append(result[i])
i += 1
json = Utils.jsonSerializeQueryResult(listResult)
print(json)
return HttpResponse(content=json,
status=200,
mimetype="text/plain")
def dataProcessingForm(form, parametersContent):
""" Mise en forme des données des formulaires pour les requêtes
La mise en forme est faite pour la DLL utilisée qui effectue le plus gros des requêtes
"""
listQueries = []
i = 1
while i < 6:
if parametersContent.__contains__("data" + form + str(i)) == True:
data = parametersContent.getlist("data" + form + str(i))[0]
location = parametersContent.getlist("location" + form + str(i))[0]
if parametersContent.getlist("age" + form + str(i))[0] == "Tous":
age = 20
else:
age = int(unicode(parametersContent.getlist("age" + form + str(i))[0]))
contentToAdd = data + "," + location + "," + str(age)
print(contentToAdd)
listQueries.append(contentToAdd)
else:
break;
i += 1
return ";".join(listQueries)
The JS code is trying to load the absolute path /query/, but your Django patterns are setup to respond to ^home/query. Try using /home/query as your xhr URL.

Return to Ajax - Error - Symfony2

For over a week I can not solve a problem with ajax . I have a form where the customer chooses the product to buy , the amount you are going to buy , and to what extent ( 1kg, 5kg, etc ) . Everything works properly, when you choose the product, the other two fields with the corresponding quantities and units will auto . When sending the form, tells me the following error:
The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?
I'll put all code , but actually the problem should be in the driver. To that reading is not so difficult to do , I will be commenting on each step.
1°: First, sending the form to the view. (obviously , first passes through the routing, but do not go if)
TablasController.php
public function pedidoAction()
{
$em = $this->getDoctrine()->getManager();
$prodped= new ProdPedido();//creo la entidad de los productos
$form = $this->createForm(new ProdPedidoType(), $prodped);
$nombres = $em->getRepository('ProyectoAdminBundle:Catalogo')->findByArticulo();
return $this->render('AtajoBundle:General:pedido.html.twig', array('form' => $form->createView(), 'nombres' => $nombres));
}
2°: I reduced a little code so that not so long . Here , I present the form, and make the corresponding javascript that handles dynamically add fields , and that I mentioned above, the auto-complete fields. Although this does not go much to the case , since the problem would be in the controller.
pedido.html.twig
{% block content %}
<section class="pedido">
<form id="formulario" action="{{ path('crear_pedido', { 'id': app.user.id } ) }}" method="post" {{ form_enctype(form) }}>
{{ form_start (form) }}
{{ form_errors(form) }}
<div id="agrega">
<ul>
<li>{{ form_label(form.producto, 'Nombre del producto: ') }}</li>
<li>{{ form_label(form.cantidad, 'Cantidad que va a llevar: ') }}</li>
<li>{{ form_label(form.valor, 'Valor en numero (KGS/LTS): ') }}</li>
</ul>
<ul class="ul_0">
<li>{{ form_widget(form.producto, { 'attr': {'class': 'producto_0'} }) }}</li>
<li>{{ form_widget(form.cantidad, { 'attr': {'class': 'cantidad_0'} }) }}</li>
<li>{{ form_widget(form.valor, { 'attr': {'class': 'medida_0'} }) }}</li>
</ul>
</div>
<div ><input id="agregarCampo" type="button" value="Agregar Producto"/></div>
<div ><input id="quitarCampo" type="button" value="Quitar Producto"/></div>
<div ><input id="enviar" type="submit" id="submit"/></div>
{{ form_end (form) }}
</section>
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script type="text/javascript" src=" {{ asset('bundles/MICARPETA/js/jquery-2.1.4.min.js') }} "></script>
<script type="text/javascript">
$(document).ready(function() {
var loqueagrego;
var busqueda = $('#busqueda');
var contenedor = $("#agrega"); //ID del contenedor
var AddButton = $("#agregarCampo"); //ID del Botón Agregar
var QuitButton = $("#quitarCampo");
var productos = '{% for nombre in nombres %}<option value="{{ nombre.articulo }}"> {{ nombre.articulo }} </option>{% endfor %}';
var x = 1;
//agregar boton
$(AddButton).click(function (e) {
//el html que voy a agregar
loqueagrego = '<ul>';
loqueagrego = loqueagrego + '<li><label>Nombre del producto: </label></li>';
loqueagrego = loqueagrego + '<li><label>Cantidad que va a llevar: </label></li>';
loqueagrego = loqueagrego + '<li><label>Valor en numero (KGS/LTS): </label></li>';
loqueagrego = loqueagrego + '</ul>';
loqueagrego = loqueagrego + '<ul class="ul_'+x+'">';
loqueagrego = loqueagrego + '<li><select class="producto_0" name="producto[]">'+ productos +'</select></li>';
loqueagrego = loqueagrego + '<li><select class="cantidad_0" name="cantidad[]"></select></li>';
loqueagrego = loqueagrego + '<li><select class="medida_0" name="medida[]"></select></li>';
loqueagrego = loqueagrego + '</ul>';
//lo agrego
$(contenedor).append(loqueagrego);
x++; //sumo la cantidad de campos que hay
return false;
});
//quitar boton
$(QuitButton).click(function (e){
if (x !== 1){ // si es distinto a 1, remuevo los input que no deseo
$("#agrega ul:last-child").remove();
$("#agrega ul:last-child").remove();
x--;
}
return false;
});
//le digo que todos los que se agreguen dinamicamente tambien van a ser afectados
$('#agrega').on("change",".producto_0", function(e){
var elegido = $(this).val();
var medidahermano = $(this).parent().parent().attr("class");
var cantidadhermano = medidahermano;
medidahermano = $('.'+ medidahermano +' li:last-child');//recupero el ultimo hijo
medidahermano = medidahermano.children(1); //recupero el primer hijo
cantidadhermano = $('.'+ cantidadhermano +' li:nth-child(2)');
cantidadhermano = cantidadhermano.children(1);
var solido;
var liquido;
solido = '<option value="1">1</option>';
solido = solido + '<option value="5">5</option>';
solido = solido + '<option value="10">10</option>';
solido = solido + '<option value="15">15</option>';
solido = solido + '<option value="20">20</option>';
solido = solido + '<option value="30">30</option>';
solido = solido + '<option value="50">50</option>';
solido = solido + '<option value="100">100</option>';
liquido = '<option value="6">6</option>'
liquido = liquido + '<option value="12">12</option>';
liquido = liquido + '<option value="24">24</option>';
liquido = liquido + '<option value="48">48</option>';
liquido = liquido + '<option value="12">96</option>';
$.ajax({
type: "POST",
url: "{{ path('que_unidad') }}",
data: { 'id' : ' ' + elegido + ' ' },
error: function(){
alert("Error petición Ajax");
},
success: function(data){
alert(data);
if(data == 'KG' | data == 'unidad'){
$(cantidadhermano).html(solido);
}
else if(data == 'LTS'){
$(cantidadhermano).html(liquido);
}
$.ajax({
type: "POST",
url: "{{ path('medidas_y_unidades') }}",
data: { 'id' : ' ' + elegido + ' ' },
error: function(){
alert("Error petición ajax");
},
success: function(data){
$(medidahermano).html(data);
}
});
}
});
});
});
</script>
{% endblock %}
3°: This is where it is assumed that this error. For me it is the way to return the information to the ajax , but not really , because it seems like it's okay . Return information through a view, everything works fine , the fields will auto . But sending the form , I get this error.
TablasController.php
public function recuperarMedidasyUnidadesAction(){
$id = $_POST['id'];
$em = $this->getDoctrine()->getManager();
// busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
$medidas = $em->getRepository('ProyectoAdminBundle:Unidades')->findByUnidadesJoinCatalogo($id);
return $this->render('AtajoBundle:Ajax:medidasYUnidades.html.twig', array('medidas' => $medidas));
}
public function recuperarUnidadAction(){
$id = $_POST['id'];
$em = $this->getDoctrine()->getManager();
// busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
$unidad = $em->getRepository('ProyectoAdminBundle:Categoria')->findByUnidad($id);
return $this->render('AtajoBundle:Ajax:unidad.html.twig', array('unidad' => $unidad));
}
4°:views
medidasYUnidades.html.twig
{% for medida in medidas %}
<option value="{{ medida.medida }}">{{ medida.medida }}</option>
{% endfor %}
unidad.html.twig
{{ unidad.unidad }}
a response object requires data in an associative array. Your code gives an entity object. You have to convert that entity to an array.
If you would like to convert all the entity data into an array then you could use JMSSerializer. See also this other stackoverflow topic
Try modifying the code as given below. It includes changes to your controller actions as well as the ajax call in the
template.
public function recuperarMedidasyUnidadesAction(){
$id = $_POST['id'];
$em = $this->getDoctrine()->getManager();
// busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
$medidas = $em->getRepository('ProyectoAdminBundle:Unidades')->findByUnidadesJoinCatalogo($id);
//modified code
$status = 'error';
$html = '';
if($medidas){
$data =$this->render('AtajoBundle:Ajax:medidasYUnidades.html.twig', array('medidas' => $medidas));
$status = 'success';
$html = $data->getContent();
}
$jsonArray = array(
'status' => $status,
'data' => $html,
);
$response = new Response(json_encode($jsonArray));
$response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $response;
}
public function recuperarUnidadAction(){
$id = $_POST['id'];
$em = $this->getDoctrine()->getManager();
// busco las diferentes unidades que existen (1kg, 5kg, 10kg, etc)
$unidad = $em->getRepository('ProyectoAdminBundle:Categoria')->findByUnidad($id);
//modified code
$status = 'error';
$html = '';
if($unidad){
$data = $this->render('AtajoBundle:Ajax:unidad.html.twig', array('unidad' => $unidad));
$status = 'success';
$html = $data->getContent();
}
$jsonArray = array(
'status' => $status,
'data' => $html,
);
$response = new Response(json_encode($jsonArray));
$response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $response;
}
JavaScript in template:
$.ajax({
type: "POST",
url: "{{ path('medidas_y_unidades') }}",
data: { 'id' : ' ' + elegido + ' ' },
error: function(){
alert("Error petición ajax");
},
success: function(result, request) {
var parsedData =JSON.parse(result);
if(parsedData.status ==='success'){
userListDiv.html(parsedData.data);
$(medidahermano).html(parsedData.data);
}else{
//handle no result case
}
}
});

JSON.parse( xhr.responseText ) unexpected string error

I get an "Uncaught SyntaxError: Unexpected string " when I try to parse my xhr.responseText, I've looked for answers but cannot find any that can relate to my problem directly. I seem to understand that my xhr.responseText may be JSONP because it is manipulated byt the callback but that doesn't help me, how can I just have a JSON? I want to be able to use my JSON in my Javascript with the Google Maps API. I'm really confused and just trying to make this work, thanks for reading and possibly helping.
Here's my PHP script.
<?php
header("Content-type: application/json; charset=utf-8");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
require("include/param_bd.inc");
try {
$connBD = new PDO("mysql:host=$dbHote; dbname=$dbNom", $dbUtilisateur, $dbMotPasse, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$connBD->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit("Erreur lors de la connexion à la BD :<br />\n" . $e->getMessage());
}
try {
$reqZaps = "SELECT * FROM leszaps";
$prepReqZaps = $connBD->prepare($reqZaps);
$prepReqZaps->execute();
$prepReqZaps->setFetchMode(PDO::FETCH_OBJ);
} catch (PDOException $e) {
exit("Erreur lors de l'exécution de la requête SQL :<br />\n" . $e->getMessage() . "<br />\nREQUÊTE = " . $reqZaps);
}
if (!( $infoZaps = $prepReqZaps->fetch() ))
$msgErreur = "Aucun Zap trouvé";
else {
do
{
$id = $infoZaps->id;
$coordinates = $infoZaps->coordinates;
$arrondissement = $infoZaps->arrondissement;
$numerocivil = $infoZaps->numerocivil;
$rue = $infoZaps->rue;
$nombatiment = $infoZaps->nombatiment;
echo "{\n";
echo "\t\"id\": \"$id\",\n";
echo "\t\"coordinates\": \"$coordinates\",\n";
echo "\t\"arrondissement\": \"$arrondissement\",\n";
echo "\t\"numerocivil\": \"$numerocivil\",\n";
echo "\t\"rue\": \"$rue\"\n";
echo "\t\"nombatiment\": \"$nombatiment\"\n";
echo "}\n";
}
while ($infoZaps = $prepReqZaps->fetch());
}
$prepReqZaps->closeCursor();
$connBD = null;
if ($msgErreur != "undefined" && $msgErreur != null) {
echo "{\n";
echo "\t\"erreur\":\n";
echo "\t{\n";
echo "\t\t\"message\": \"" . str_replace("\"", "\\\"", $msgErreur) . "\"\n";
echo "\t}\n";
echo "}\n";
}
?>
And here's my Javascript script
var xhr;
var donneesChargees = false;
var objReperes;
var reperes;
chargerKml();
function chargerKml() {
var lienDocChargement = './script_load_kml_get.php';
var erreur = false;
chargerScriptAsync('./script_load_kml_bd.php', function(){
console.log("Les ZAP ont été chargées dans la base de données");
});
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpRequest = new
ActiveXObject("Microsoft.XMLHTTP"); }
try {
xhr = new XMLHttpRequest();
} catch (e) {
alert('Erreur: Impossible de créer l\'objet XMLHttpRequest');
erreur = true;
}
if (!erreur)
{
xhr.onreadystatechange = xhrCallback;
xhr.open('GET', lienDocChargement, true);
xhr.send(null);
}
}
function xhrCallback()
{
if (xhr.readyState == 4)
{
if (xhr.status != 200)
alert('Erreur: La requête HTTP a échoué (code=' + xhr.status + ')');
else
{
objReperes = JSON.parse( xhr.responseText );
creerReperes();
}
}
}
function creerReperes()
{
try {
var strReperes;
//$arrondissement = objReperes.$arrondissement;
strReperes = '[' + xhr.responseText + ']';
strReperes = strReperes.replace(/[\n\r\t]/g, '');
strReperes = strReperes.replace(/}{/g, '}~{');
strReperes = strReperes.split('~');
var coordonnees;
var id;
reperes = '[';
for (var i = 0; i < strReperes.length; i++){
var numberPattern = /\d+/g;
id = strReperes[i].split(',')[0];
id = id.match( numberPattern );
coordonnees = strReperes[i].split(',')[1] + ',' + strReperes[i].split(',')[2];
coordonnees = coordonnees.replace(/"/g, '');
coordonnees = coordonnees.replace('coordinates: ', '');
coordonnees = coordonnees.split(',');
reperes += '{"long": ' + coordonnees[0] + ', "lat": ' + coordonnees[1] + ', "id": ' + id + '}';
if (i != strReperes.length - 1) {
reperes += ', ';
}
}
reperes += ']';
reperes = JSON.parse(reperes);
} catch (e) {
alert('ERREUR: La réponse AJAX n\'est pas une expression JSON valide.');
return;
}
}
As you can see in creeReperes() i need to do some unorthodox manipulation with the xrhresponsetext instead of using a JSON.
Oh and sorry if some of the code is in french.
if (!( $infoZaps = $prepReqZaps->fetch() ))
$msgErreur = "Aucun Zap trouvé";
else {
$rows = array();
while ($infoZaps = $prepReqZaps->fetch()) {
$rows[] = $infoZaps;
}
echo json_encode($rows);
}
$prepReqZaps->closeCursor();
$connBD = null;

IE Parsing XML JQuery and AJAX

$.ajax({
url : SrvHandlerCalendar,
type : 'post',
data : {"persona": str, "day2" : dia + '.' + mes + '.' + anio},
timeout : 2000,
tryCount : 0,
retryLimit : 3,
cache: false,
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
$(xml).find('evento').each(function(){
ai++;
var id = $(this).attr('id');
var rdia = $(this).find('dia').text();
var rmes = $(this).find('mes').text();
var ranio = $(this).find('anio').text();
var hora = $(this).find('hora').text();
var horario = $(this).find('horario').text();
var desc = $(this).find('d').text();
var estado = $(this).find('estado').text();
var localidad = $(this).find('localidad').text();
var colonia = $(this).find('colonia').text();
var calle = $(this).find('calle').text();
var numero = $(this).find('ncasa').text();
var telefono = $(this).find('telefono').text();
var celular = $(this).find('celular').text();
var persona = $(this).find('persona').text();
var creador = $(this).find('creador').text();
var observaciones = $(this).find('observaciones').text();
if(persona != $("#personas_select option:selected").text()) return 1;
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br><br><br>";
html += "<table class=\"datatable\" cellpadding=10>"
html += "<tr><td><strong>Hora de la Cita</strong></td><td>" + hora + horario+"</td></tr>";
html += "<tr><td><strong>Domicilio</strong></td><td>" + calle + " #"+numero+"</td></tr>";
html += "<tr><td><strong>Colonia</strong></td><td>" +colonia+"</td></tr>";
//html += "<tr colspan=\"2\" style=\"text-align: center;\"><td>Datos de contacto</td></tr>";
html += "<tr><td><strong>Telefono</strong></td><td>" + telefono +"</td></tr>";
html += "<tr><td><strong>Celular</strong></td><td>" + celular +"</td></tr>";
html += "<tr><td><strong>Encuestador</strong></td><td>" + creador +"</td></tr>"
html += "<tr><td><strong>Observaciones</strong></td><td>" + observaciones +"</td></tr></table>";
$('#datos').html(html);
/*
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br>";
html += "<table>"
html += " <tr> <td>Hora de la Cita</td><td>horario y fecha</td></tr>";
html += "<tr> <td>Domicilio</td><td>vdomicilio</td></tr>";
html += "<tr><td>Colonia</td><td>vcolonia</td></tr>";
html += "<tr><td>Datos de contacto</td><td>(no hay otra columna)</td></tr>";
html += "<tr><td>telefono</td><td></td></tr>";
html += "<tr><td>celular</td><td></td></tr>";
html += "<tr><td>encuestador</td><td></td></tr></table>";
*/
});
if($("#datos").html() == loading){
$('#datos').html("Uups! No hay datos de evento para esta persona. <strong>Notificar de inmediato al administrador del sistema</strong> <a href=\"#\" onclick='alert(\"No se encontro el primer atributo XML\" + \" "+" \" )'> Ficha Técnica</a>");
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
$('#datos').html(loading);
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
$('#datos').html("Uups! Hubo un error procesando su solicitud <a href=\"#\" onclick='alert(\"Respuesta HTTP: \" + \" "+ xhr.status+" \" + \"\\nManejador del servidor: \" + \" " + SrvHandlerCalendar + " \" + \"\\nDescripcion de error: \" + \" " + textStatus + " \" + \"\\nIntentos: \" + \" " + this.retryLimit + " \" )'> Ficha Técnica</a>");
return;
}
if (xhr.status == 500) {
$('#datos').html('Uups! Hubo un error con el servidor. Intente nuevamente mas tarde y pongase en contacto con el administrador de sistemas.');
} else {
$('#datos').html("Uups! Hubo un error procesando su solicitud <a href=\"#\" onclick='alert(\"Respuesta HTTP: \" + \" "+ xhr.status+" \" + \"\\nManejador del servidor: \" + \" " + SrvHandlerCalendar + " \" + \"\\nDescripcion de error: \" + \" " + textStatus + " \" )'> Ficha Técnica</a>");
}
}
});`
And basically this:
var xml;
if (typeof data == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
$(xml).find('evento').each(function(){
ai++;
var id = $(this).attr('id');
var rdia = $(this).find('dia').text();
var rmes = $(this).find('mes').text();
var ranio = $(this).find('anio').text();
var hora = $(this).find('hora').text();
var horario = $(this).find('horario').text();
var desc = $(this).find('d').text();
var estado = $(this).find('estado').text();
var localidad = $(this).find('localidad').text();
var colonia = $(this).find('colonia').text();
var calle = $(this).find('calle').text();
var numero = $(this).find('ncasa').text();
var telefono = $(this).find('telefono').text();
var celular = $(this).find('celular').text();
var persona = $(this).find('persona').text();
var creador = $(this).find('creador').text();
var observaciones = $(this).find('observaciones').text();
if(persona != $("#personas_select option:selected").text()) return 1;
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br><br><br>";
html += "<table class=\"datatable\" cellpadding=10>"
html += "<tr><td><strong>Hora de la Cita</strong></td><td>" + hora + horario+"</td></tr>";
html += "<tr><td><strong>Domicilio</strong></td><td>" + calle + " #"+numero+"</td></tr>";
html += "<tr><td><strong>Colonia</strong></td><td>" +colonia+"</td></tr>";
//html += "<tr colspan=\"2\" style=\"text-align: center;\"><td>Datos de contacto</td></tr>";
html += "<tr><td><strong>Telefono</strong></td><td>" + telefono +"</td></tr>";
html += "<tr><td><strong>Celular</strong></td><td>" + celular +"</td></tr>";
html += "<tr><td><strong>Encuestador</strong></td><td>" + creador +"</td></tr>"
html += "<tr><td><strong>Observaciones</strong></td><td>" + observaciones +"</td></tr></table>";
$('#datos').html(html);
/*
var html = "<font size=5>Informacion del evento con <u>" + persona + "</u></font><br>";
html += "<font size=2>"+desc+"</font><br>";
html += "<table>"
html += " <tr> <td>Hora de la Cita</td><td>horario y fecha</td></tr>";
html += "<tr> <td>Domicilio</td><td>vdomicilio</td></tr>";
html += "<tr><td>Colonia</td><td>vcolonia</td></tr>";
html += "<tr><td>Datos de contacto</td><td>(no hay otra columna)</td></tr>";
html += "<tr><td>telefono</td><td></td></tr>";
html += "<tr><td>celular</td><td></td></tr>";
html += "<tr><td>encuestador</td><td></td></tr></table>";
*/
});
if($("#datos").html() == loading){
$('#datos').html("Uups! No hay datos de evento para esta persona. <strong>Notificar de inmediato al administrador del sistema</strong> <a href=\"#\" onclick='alert(\"No se encontro el primer atributo XML\" + \" "+" \" )'> Ficha Técnica</a>");
}
Only works on Chrome/Firefox and Not on IE.
I don't know why, I googled about JQuery and IE errors, tried the 'fixes' and they still do not work.
Thank you in advance.
UPDATE
It now works.
The problem with IE is that the XML It was receiving was bad because IE doesn't allow áéíóú letters (commonly used in spanish) instead displaying a square character therfor it could't process the XML.

Categories

Resources