Extract Data from JSON and display in SWAL alert - php

I am having problems while trying to show info from a Json to an alert, this is my code.
function check_values_chbx(){
var pre_insc = [];
}).done(function(response){
for(i=0; i<response.length; i++){
pre_insc[i] = response[0]['personas'][i]['name']+" "+response[0]['personas'][i]['ap_pat']+" "+response[0]['personas'][i]['ap_mat'];
}
alert(pre_insc[1]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n"+pre_insc.join('\n')+"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
}else {
location.reload();
}
});
});
}
And this is my JSON
[
{
"personas": [
{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [
{
"name": "Carrera larga"
}
],
"categoria": [
{
"name": "Juvenil"
}
]
}
]
I need to print each name like:
swal("name1\n"+name2\n"+etc").
Please if someone could help me it will be very helpful, have a nice day.

You can use the below script which recursively iterates a json object if it finds an array or Object until it finds the text for the given property and then print them all if the property name is name with \n separator, you can add the following inside your script file and pass it the response that you are receiving and use the returned names with your sweetAlert, just make sure you pass the response to the function like below
names = jsonParser.getNames(response[0]);
Add the below in you script
var jsonParser = {
isObject: function (property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function (property) {
return property && {}.toString.call(property) === '[object Array]';
},
getNames: function (errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.getNames(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
An example to read the names from your given response is given below.
var jsonParser = {
isObject: function(property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function(property) {
return property && {}.toString.call(property) === '[object Array]';
},
convertToString: function(errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.convertToString(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
var response = [{
"personas": [{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [{
"name": "Carrera larga"
}],
"categoria": [{
"name": "Juvenil"
}]
}];
var names = '';
names = jsonParser.convertToString(response[0]);
console.log(names);
Your final script should look like
function check_values_chbx(){
var pre_insc = [];
}).done(function (response) {
var names = jsonParser.getNames(response[0]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n" + names +
"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
} else {
location.reload();
}
});
});
Hope this helps you out

Related

Cant resolve this error: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

This is the Response
{
"message": null,
"data": {
"items": [
{
"dealerId": 634,
"dealerName": "Test12",
"dealerCode": "dandasn123"
},
{
"dealerId": 36,
"dealerName": "Saurabh",
"dealerCode": "ASDF"
},
{
"dealerId": 38,
"dealerName": "Muskan",
"dealerCode": "ASDF"
},
{
"dealerId": 16,
"dealerName": "Nsj94",
"dealerCode": "ASDF1234"
}
]
},
"type": null
}
This is the Model which I have created using jsonToDart Plugin available in Android Studio
import 'Data.dart';
class DealerDetailsModel {
DealerDetailsModel({
this.message,
this.data,
this.type,
});
DealerDetailsModel.fromJson(dynamic json) {
message = json['message'];
data = json['data'] != null ? Data.fromJson(json['data']) : null;
type = json['type'];
}
dynamic message;
Data? data;
dynamic type;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['message'] = message;
if (data != null) {
map['data'] = data?.toJson();
}
map['type'] = type;
return map;
}
}
import 'Items.dart';
class Data {
Data({
this.items,
});
Data.fromJson(dynamic json) {
if (json['items'] != null) {
items = [];
json['items'].forEach((v) {
items?.add(Items.fromJson(v));
});
}
}
List<Items>? items;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
if (items != null) {
map['items'] = items?.map((v) => v.toJson()).toList();
}
return map;
}
}
class Items {
Items({
this.dealerId,
this.dealerName,
this.dealerCode,
});
Items.fromJson(dynamic json) {
dealerId = json['dealerId'];
dealerName = json['dealerName'];
dealerCode = json['dealerCode'];
}
int? dealerId;
String? dealerName;
String? dealerCode;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['dealerId'] = dealerId;
map['dealerName'] = dealerName;
map['dealerCode'] = dealerCode;
return map;
}
}
and this is the method that I have created to fetch dealer details, and here only I am facing the error where I have written getData as List
Future<List<DealerDetailsModel>> getDealerDetails() async {
var params = {'': ''};
if (isNetworkAvail) {
await apiBaseHelper.getAPICall(getDealerDetailsData, params).then(
(getData) async => {
dealerData = (getData as List)
.map((data) => DealerDetailsModel.fromJson(data))
.toList(),
},
);
}
return dealerData;
}
Your issue is that you are expect a list from api response but it is a Map. So you need to parse it like this. Change your getDealerDetails to this:
Future<DealerDetailsModel?> getDealerDetails() async {
var params = {'': ''};
if (isNetworkAvail) {
var getData = await apiBaseHelper.getAPICall(getDealerDetailsData, params);
return DealerDetailsModel.fromJson(getData);
}
return null;
}
remember change your FutureBuilder's type to DealerDetailsModel? instead of List<DealerDetailsModel>.

I am using paypal api and it works in localhost but it doesn't in the server

I am using a mysql database with php and the query is not done in the database in clever cloud, I have this code for the html:
this script is in the html because it's the button to buy so it gets to the api, processes the process and gets the json object from the api that contains the users data
<script>
try {
document.addEventListener('DOMContentLoaded',
paypal.Buttons({
style:{
layout: 'horizontal',
color: 'silver',
shape: 'pill',
tagline: 'false',
label: 'paypal'
},
createOrder: function(data, actions)
{
return actions.order.create({
purchase_units: [{
amount: {
value: costo
}
}]
});
},
onApprove: function(data, actions)
{
let url = 'heres the link of the php file'
actions.order.capture().then(function(detalles)
{
const item = {
detalles: {
id: detalles.id,
purchase_units: detalles.purchase_units[0].amount.value,
status: detalles.status,
update_time: detalles.update_time,
payer: {
email_address: detalles.payer.email_address,
payer_id: detalles.payer.payer_id
}
}
};
console.log(JSON.stringify(item));
console.log(detalles);
alert("Pago realizado");
//window.location.href="";
return fetch(url,
{
method: 'post',
headers:
{
'content-type': 'application/json'
},
body: JSON.stringify(item)
}).catch( err => {
alert(err);
});;
});
},
onCancel: function(data)
{
alert("Pago cancelado");
console.log(data);
},
onError: function (err)
{
alert("Ha sucedido un error, intente de nuevo");
}
}).render('#paypal-button-container'), false);
} catch (error) {
console.log(error);
}
</script>
and this for the php, it gets the data from the json and put it on a query
<?php
session_start();
include "database.php";
$id_us = $_SESSION["id_us"];
$id_producto = $_SESSION['id_p'];
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$json = file_get_contents('php://input');
$datos = json_decode($json, true);
if($json != NULL)
{
$str = "{datos: 2}";
echo $str;
$id_transaccion = $datos['detalles']['id'];
echo $id_transaccion;
$precio = floatval($datos['detalles']['purchase_units']);
$estado = $datos['detalles']['status'];
$fecha = $datos['detalles']['update_time'];
$fecha_db = date('Y-m-d H:i:s', strtotime($fecha));
$_email = $datos['detalles']['payer']['email_address'];
$id_cliente = $datos['detalles']['payer']['payer_id'];
$ingreso = "INSERT INTO `comprado`(`id_usuario`, `id_producto`, `fecha_historial`, `id_transaccion`, `email`, `id_cliente`, `precio`) VALUES ('$id_us', '$id_producto','$fecha_db','$id_transaccion','$_email','$id_cliente','$precio')";
mysqli_query($conexion, $ingreso);
}else {
echo $json;
}
}
?>
it works in localhost but in heroku and clever cloud it doesn't because the query won't insert in the database

Laravel : Axios not saving the data in edit page

I create an edit page to edit the data. After the user edits the form. The form should be saved. But in my case I can't save the form it's showing error.
I facing this error.
ReminderComponent.vue
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
Vue.use(VueAxios, axios);
const md = new MarkdownIt({
linkify: true
})
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules','mailtemplates'],
components: {
},
data() {
return {
template:
{
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
if (this.mailtemplates) {
this.template=this.mailtemplates;
}
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value !== ''
},
fetch()
{
//request data
axios.get(this.email_index_route,this.template)
.then((res) => {
this.template = res.data.template;
})
**axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})**
},
save()
{
//save data to db
axios.post(this.email_index_route, this.template)
.then((res) => {
alert('Mail sent successfull!')
})
**axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})**
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
}
}
</script>
I think this area causing problem but i can't find the solution.
axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})
axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})
route file
Route::get('api/email/create', ['as' => 'email.create', 'uses' => 'Havence\AutoMailController#create']);
Route::get('automail/mail', 'Havence\AutoMailController#mail');
Route::get('automail/index',['as'=>'email.index','uses' => 'Havence\AutoMailController#index']);
Route::post('automail/edit/{id}',['as'=>'email.edit','uses' => 'Havence\AutoMailController#edit']);
Route::get('automail/delete',['as'=>'email.delete','uses' => 'Havence\AutoMailController#destroy']);
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
As per your error and your route file you are using POST method on your edit page but your edit method accepts only GET method that is why you are getting this error.
I'm getting this error

CodeIgniter - AJAX,STORED PROCEDURE

I don't know how to begin this but here's the statement before the problem.
THE URL -> my.com/kustomer/customerListOfApplication/24669
I got a modal that accepts more than 10 fields.
I got the PROCEDURE call in a model.
public function insertApplicationAjax(){
$inType = $this->input->post('lineType');
$inCustomer = $this->input->post('custId');
//echo $inType;die();
$inMeter = $this->input->post('meter');
$inIfBusiness = strtoupper($this->input->post('business'));
$inDeposit = $this->input->post('deposit');
$inApplicationFee = $this->input->post('applicationFee');
$inServiceFee = $this->input->post('serviceFee');
$inOtherFee = $this->input->post('otherFee');
$inInitialReading = $this->input->post('initialReading');
$inDateApplied = date('Y-m-d');
$inNote = strtoupper($this->input->post('note'));
$inLocation = strtoupper($this->input->post('add1'));
$inCluster = $this->input->post('cluster');
$inZone = $this->input->post('zone');
$inTypeOfService = 1; //application 2 Reconnection 3 Promisory
$inCustomerName = strtoupper($this->input->post('customerName'));
$indiscountBit = $this->input->post('discountBit');
// echo $indiscountBit;die();
$inBrgyCode = $this->input->post('brgy');
$inPipe = $this->input->post('pipe');
$sql = "CALL APPLICATION_ADD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$query = $this->db->query($sql,array($inType,$inCustomer,$inMeter,$inIfBusiness,$inDeposit,$inApplicationFee,$inServiceFee,$inOtherFee,$inInitialReading,$inDateApplied,$inNote,$inLocation,$inCluster,$inZone,$inTypeOfService,$inCustomerName,$indiscountBit,$inBrgyCode,$inPipe));
if (!$query) {
return $this->db->error();
}else {
return true;
mysqli_next_result( $this->db->conn_id );
}
}
Here's the AJAX
jQuery.validator.addMethod("notEqual", function(b, a, c) {
return this.optional(a) || b != c
}, "Please input a value other than this...");
var validator = $( "#newAccountForm" ).validate({
submitHandler: function(d) {
var url = "http://my.com/application/insertApplicationAjax";//$('#newAccountForm').attr('action');
var msg;
if (url == "http://my.com/application/insertApplicationAjax") {
$('#submitApplicationBtn').prop('disabled', true).text('Please wait...');
msg = "New Application Successfully Added...";
}else {
$('#submitApplicationBtn').prop('disabled', true).text('Updating...');
msg = "Application Edited Successfully... 😉";
}
var formData = $('#newAccountForm').serialize(); //alert(formData);
$.post(url, formData, function(data,s) {
if (s = "success") {
if (data.data == true) {
toastr.success(msg);
setTimeout(function(){
$("#customerForm")[0].reset();
$('#addCustomerModal').modal('hide');
$('#submitApplicationBtn').removeAttr('disabled').text('SUBMIT');
}, 800);
// $('#customerTable').DataTable().ajax.reload();// refreshTable();
customerTable.ajax.reload();
} else {
$('#submitApplicationBtn').removeAttr('disabled').text('TRY AGAIN..');
alert('You didn\'t changed something.');
}
}else {
$('#submitApplicationBtn').removeAttr('disabled').text('TRY AGAIN..');
alert('Something went wrong try again.');
}
}, "json");
},
invalidHandler: function() {
toastr.warning(validator.numberOfInvalids() +' field(s) are invalid');
},
rules: {
meter: {
required: true,
notEqual: 0,
normalizer: function( value ) {
return $.trim( value );
}
},
brgy:{
notEqual: 0,
},
initialReading: {
required: false,
},
zone: {
required: true,
// rangelength: [2, 30]
},
cluster: {
required: true,
// rangelength: [2, 30]
},
add1: {
required: true
},
},
messages: {
brgy: {
required: "***",
},
zone: {
required: "***",
},
cluster: {
required: "***",
},
add1: {
required: "***",
},
meter: {
required: "***",
},
}
});
Here's the Observation and PROBLEM
it seems that i cannot pass the serialized data from the form to the model, but i can see the data on chrome inspect element.
Thrown error:
I did try to to use the PROCEDURE on phpmyadmin and it was fine.

how to get and pass multiple checkboxes value to server side (php) through controller using angularjs

how to get and pass multiple checkboxes values to server side (php) through controller using angularjs.
but it didn't throw any console error or else.
i don't know what's wrong with my code.
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role" ng-change="checkFirst()"> {{role}}
</label>
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
console.log($scope.user.roles);
};
Since your new to Angular, let me post some example that might help you.
<div ng-app="checkbox" ng-controller="homeCtrl">
<div ng-repeat="item in list">
<input type="checkbox" checkbox-group />
<label>{{item.value}}</label>
</div>{{array}}
<br>{{update()}}
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function($scope) {
$scope.array = [1, 5];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
$scope.update = function() {
if ($scope.array.toString() !== $scope.array_.toString()) {
return "Changed";
} else {
return "Not Changed";
}
};
})
.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b
}));
});
}
}
});
Let me know if this help for you.

Categories