Ir para conteúdo
lui hurk

Como inserir dados em tabelas relacionadas no mysql via AJAX

Recommended Posts

Já pesquisei e foi muito, e esse assunto não tem em lugar nenhum. Bem eu desenvolvi um CRUD com LOGIN e SESSION, em php ficou perfeito cada usuário com sua sessão funcionando no XAMPP, só que estou tentando, desenvolver um app  pelo CORDOVA, via AJAX com estas mesmas características se tratando de cliente , servidor,  ok, fiz sessão de login, registro e o CRUD,  certo..tudo beleza,.. Até eu relacionar a tabela de login com a do crud aí lascou, o login eu consigo entrar e ser redirecionado para o CRUD e ao inserir sei lá "produtos" na tabela não róla, claro que a dor de cabeça é... as sessões LOCAL ou SESSION STORAGE se conversarem com a $_SESSAO php, eu fiz isso, tanto que o login que tem o START() lado servidor  e o registro como já disse funcionam normalmente, agora percebi que o problema esta no start do CRUD, devo estar pecando no AJAX erro de principiante, tenho dúvidas e a pergunta é esta do titulo.   

Aos mais experientes peço ajuda.

Editado por lui hurk
add

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 23/01/2019 at 21:16, lui hurk disse:

Já pesquisei e foi muito, e esse assunto não tem em lugar nenhum. Bem eu desenvolvi um CRUD com LOGIN e SESSION, em php ficou perfeito cada usuário com sua sessão funcionando no XAMPP, só que estou tentando, desenvolver um app  pelo CORDOVA, via AJAX com estas mesmas características se tratando de cliente , servidor,  ok, fiz sessão de login, registro e o CRUD,  certo..tudo beleza,.. Até eu relacionar a tabela de login com a do crud aí lascou, o login eu consigo entrar e ser redirecionado para o CRUD e ao inserir sei lá "produtos" na tabela não róla, claro que a dor de cabeça é... as sessões LOCAL ou SESSION STORAGE se conversarem com a $_SESSAO php, eu fiz isso, tanto que o login que tem o START() lado servidor  e o registro como já disse funcionam normalmente, agora percebi que o problema esta no start do CRUD, devo estar pecando no AJAX erro de principiante, tenho dúvidas e a pergunta é esta do titulo.   

Aos mais experientes peço ajuda.

Para todos efeitos continuo com esse problema a segunda tabela ou seja a do cliente não recebe os dados.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Opa Jack, brigado pela ajuda, deixa eu reformular meu help..., pela inserção ou conexão ta beleza, 

 

São duas tabelas relacionadas:

CREATE TABLE `users` (
  `id` int(9) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
  MODIFY `id` int(9) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;


CREATE TABLE `employees` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(100) NOT NULL,
  `duration` int(5) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `login_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  CONSTRAINT FK_employees_1
  FOREIGN KEY (login_id) REFERENCES users(id)
  ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB;

A questão das Sessions está superada, eu entro com usuário na table "users" e tranquilo e só , pois na table "employees"  não consigo cadastrar os dados, porém ao segregar as tables, a table "employees" ela cadastra normal, o problema, está aí quando há o relacionamento entre elas. Aí mais curioso no servidor php sem o Ajax róda perfeitamente.{ você entra na sessão com o seu usuário e cadastra seu os dados} mas em Ajax tá difícil.

Abaixo o link para acessar o exemplo, de como eu quero.

DesteJeito  

 

Tomara que tenha sido claro, abraços.

Compartilhar este post


Link para o post
Compartilhar em outros sites
16 minutos atrás, lui hurk disse:

Opa Jack, brigado pela ajuda, deixa eu reformular meu help..., pela inserção ou conexão ta beleza, 

 

São duas tabelas relacionadas:


CREATE TABLE `users` (
  `id` int(9) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
  MODIFY `id` int(9) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;


CREATE TABLE `employees` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(100) NOT NULL,
  `duration` int(5) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `login_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  CONSTRAINT FK_employees_1
  FOREIGN KEY (login_id) REFERENCES users(id)
  ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB;

A questão das Sessions está superada, eu entro com usuário na table "users" e tranquilo e só , pois na table "employees"  não consigo cadastrar os dados, porém ao segregar as tables, a table "employees" ela cadastra normal, o problema, está aí quando há o relacionamento entre elas. Aí mais curioso no servidor php sem o Ajax róda perfeitamente.{ você entra na sessão com o seu usuário e cadastra seu os dados} mas em Ajax tá difícil.

Abaixo o link para acessar o exemplo, de como eu quero.

DesteJeito  

 

Tomara que tenha sido claro, abraços.

 

O problema não esta na sua tabela e sim no seu código então

Se tu posta parte do código que esta dando o problema que tu disse ai

Será ate melhor para os membros do FÓRUM lhe ajudar tbm.....

Compartilhar este post


Link para o post
Compartilhar em outros sites

Ok, como eu faço exponho o código da table users e employees aqui?....

Certo...

Mas beleza aí no entendimento né, em Ajax não funfa employees, no servidor funfa tudo, como no " exemplo ".

 

Vou dar uma analisada para pontuar aí eu posto o código.

abraços.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bem la vai,

 

form.html

 

<div class="list">
        <input type="hidden" id="id" value="" />
        <div class="item">
            <label>  Name title</label>
            <input type="text" name="title"  id="title" value="" />
        </div>
        <div class="item">
            <label>Employee Position duration</label>
            <input type="text" name="duration"  id="duration" value="" />
        </div>
        <div class="item">
            <label>Employee Salary price</label>
            <input type="text" name="price" id="price" value="" />
        </div>
        <div class="item">
            <input type="button" id="insert" class="button button-block" value="Enviar" />
        </div>
    </div>

 

Ajax.js ( insert )

<script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $("#insert").click(function() {
            var title = $("#title").val();
            var duration = $("#duration").val();
            var price = $("#price").val();
            var dataString = "title=" + title + "&duration=" + duration + "&price=" + price + "&insert=";
            if ($.trim(title).length > 0 & $.trim(duration).length > 0 & $.trim(price).length > 0) {
                $.ajax({
                    type: "POST",
                    url: "https://caminho.com.br/insert.php",
                    data: dataString,
                    crossDomain: true,
                    cache: false,
                    beforeSend: function() {
                        $("#insert").val('Connecting...');
                    },
                    success: function(data) {
                        if (data == "success") {
                            alert("inserted");
                            $("#insert").val('submit');
                        } else if (data == "error") {
                            alert("error");
                        }
                    }
                });
            }
            return false;
        });
    });
    </script>

 

insert.php

 

<?php
ob_start();
session_start();
 
 include "db.php";
 if(isset($_POST['insert']))
 {
 $title=$_POST['title'];
 $duration=$_POST['duration'];
 $price=$_POST['price'];
 $loginId = $_SESSION['id'];

 $q=mysqli_query($con,"INSERT INTO employees (`title`,`duration`,`price`,`login_id`) VALUES ('$title','$duration','$price','$loginId')");
 if($q)
  echo "success";
 else
  echo "error";
 }
 ob_end_flush();
 ?>

users.php

 

     if(isset($_POST['login']))
   {
    $username = $_POST['username'];
    $password = $_POST['password'];

     $login =  mysqli_query($con, "SELECT *  FROM `users` WHERE `username`='$username' AND `password`='$password'")
                    or die("Could not execute the select query.");

      $row = mysqli_fetch_assoc($login);
        
        if(is_array($row) && !empty($row)) {
            $validuser = $row['username'];
            $_SESSION['valid'] = $validuser;
            $_SESSION['id']    = $row['id'];
          
                                              
          echo "success"; 
         }else{

          echo "error";    
           }
     }
    mysqli_close($con);

Acrescentando;

 

normal.JPG.813d5a8667e74c707a3def25df6e6370.JPG

 

Só lembrando que a requisição é realizado do lado cliente em html.

Ok, tentei sumarizar o máximo.

 

 

Abraços.

 

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 08/10/2019 at 22:10, Jack Oliveira disse:

 

O problema não esta na sua tabela e sim no seu código então

Se tu posta parte do código que esta dando o problema que tu disse ai

Será ate melhor para os membros do FÓRUM lhe ajudar tbm.....

 

Beleza a parte é essa.

 

 <?php session_start(); ?>
<?php
 session_id();
header("Access-Control-Allow-Origin: *");

 ini_set('display_errors',1);

ini_set('display_startup_erros',1);

error_reporting(E_ALL);

     include "db.php";


 if(isset($_POST['insert'])){

$title=$_POST['title'];
 $duration=$_POST['duration'];
 $price=$_POST['price'];
 $loginId = $_SESSION['id'] = 'login_id';


 
 
 $q=mysqli_query($con,"INSERT INTO employees  
 	(`title`,`duration`,`price`,`login_id`) 
 	VALUES   
 	('$title','$duration','$price','$loginId')");
if($q) { 

        	echo "success"; 

        }else{
              echo "error"; 
           
            }
        }
 ?>

Se puderem me ajudar fico muito grato.

 

Abraço a todos.

Compartilhar este post


Link para o post
Compartilhar em outros sites

@lui hurk

 

Não existe poblema em inserir informações em tabelas relacionadas  deste que exista registro na tabela MÃE para que possa ser inserido registro na tabela filha, este é o conceito.

 

Experimenta usar o comando de INSERT como abaixo:

 

$q=mysqli_query($con,"INSERT INTO employees
               (id, title, duration, price, login_id)
        VALUES (NULL, '".$title."', ".$duration.", ".$price.", ".$loginId.")");

Só uma dica do que estava errado no seu INSERT.

 

Variáveis do tipo ALHANUMERICA devem ser colocadas entre aspas na clausula SQL.

Variáveis do tipo NUMEICA devem ser colocadas SEM aspas na clausula SQL.

 

O banco de dados identifica um ALPHANUMERICO como STRING quando existem ASPAS no inicio e fim da palavra, como você declarou TITLE como VARCHAR elas devem ser colcadas entre aspas, mas isso estou falando dentro do VALUE então TITLE no VALUE fica 'Titulo aqui como Alphanumerico', para os outros campo como  DURATION PRICE e LOGINID você declarou como INT e DECIMAL, lembrando que INT só aceita numeros inteiros, então se tiver . (ponto) e/ou , (vigula) vai dar erro, lembrando também que para o Banco de Dados, não existe , como separados de casas decimais, então o ponto deve ser usado.

 

Exemplo, valor R$ 1.221.469,99 <-- esse valor para ser inserido no banco de dados deve ficar como 1221469.99.

 

A mesma regra do INT deve ser aplicado para o DECIMAL então no VALUR esses "valores" numéricos devem ser cadastrados sem as aspas.

 

VALUE (NULL, 'meu titilo aqui', 1, 15.99, 1) <-- exemplo de como deve ser formatado o VALUE.

 

Espero ter ajudado.

 

Att.

Felipe Coutinho

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por Ivansakua
      Olá a todos.
      Estou desenvolvendo um aplicativo android em cordova e utilizando o sqlite. Ao executar uma consulta sql (ex. SELECT * FROM db_teste) eu recebo os dados (codigo e nome), porém, ao realizar dentro deste "for" de recebimento de dados outra consulta usando os dados recebidos para consulta em outra tabela (Ex. Pego o codigo da tabela db_teste e executo a consulta SELECT * FROM db_teste_teste WHERE cod_teste='" + cod + "' ORDER BY codigo) eu recebo os dados da segunda consulta somente quando toda a primeira é feita. Abaixo segue o que está na minha função listaDadosTabelas. OBS.: Eu vou jogando os resultados dentro uma div com ID="app".
       
          var html = "";
          var sql = "SELECT * FROM db_teste ORDER BY codigo";
          
          await tx.executeSql(sql, [], function(tx, result) {
              
              if(result.rows != null && result.rows.length > 0) {
                  
                  for(var i = 0; i < result.rows.length; i++) {
                      
                      var row = result.rows.item(i);
                      
                      var cod = row.codigo;
                      var nome = row.nome;
                      
                      document.getElementById("app").innerHTML += "COD.: " + cod + " - NOME: " + nome + "<br>";
                      
                      var sql1 = "SELECT * FROM db_teste_teste WHERE cod_teste='" + cod + "' ORDER BY codigo";
                      
                      tx.executeSql(sql1, [], function(tx, result1) {
              
                          if(result1.rows != null && result1.rows.length > 0) {
                              for(var c = 0; c < result1.rows.length; c++) {
                                  var row1 = result1.rows.item(c);
                                  var cod1 = row1.codigo;
                                  var nome1 = row1.nome;
                                  document.getElementById("app").innerHTML += "COD.: " + cod1 + " - NOME: " + nome1 + "<br>";  
                              }
                              
                              document.getElementById("app").innerHTML += "<br>";
       
                          } else {
                              document.getElementById("app").innerHTML += "NENHUM DADOS ENCONTRADO TABELA TESTE TESTE...<br>";
                          }
                      }, function(error) {
                          document.getElementById("app").innerHTML += "ERRO AO BUSCAR DADOS TABELA TESTE TESTE...<br>";
                      });
                      
                  }
                  
              } else {
                  
                  document.getElementById("app").innerHTML += "NENHUM DADOS ENCONTRADO TABELA TESTE...<br>";
                  
              }       
              
          }, function(error) {
              
              document.getElementById("app").innerHTML += "ERRO AO BUSCAR DADOS TABELA TESTE...<br>";
              
          });
    • Por ckcesar
      Galera alguém pode me ajudar, eu gerei uma Build com AngularCli e tento rodar ela com o Cordova e ao inspecionar no Chrome me retorna o seguinte erro no console:
      main-es2015.7678d805abc29502169b.js:1 Service worker registration failed with: TypeError: Failed to register a ServiceWorker: The URL protocol of the current origin ('file://') is not supported. at g._next (main-es2015.7678d805abc29502169b.js:1) at g.__tryOrUnsub (main-es2015.7678d805abc29502169b.js:1) at g.next (main-es2015.7678d805abc29502169b.js:1) at f._next (main-es2015.7678d805abc29502169b.js:1) at f.next (main-es2015.7678d805abc29502169b.js:1) at Kl._next (main-es2015.7678d805abc29502169b.js:1) at Kl.next (main-es2015.7678d805abc29502169b.js:1) at Dl._next (main-es2015.7678d805abc29502169b.js:1) at Dl.next (main-es2015.7678d805abc29502169b.js:1) at G.notifyNext (main-es2015.7678d805abc29502169b.js:1)  
    • Por marcossantana10
      Opa, to precisando muito de uma ajuda: estou tentando fazer o upload de arquivos de um app hibrido (rodando android) para um servidor. O código abaixo é executado sem erro, mas o upload não acontece. Será que alguem tem ideia de onde pode estar o erro?
       
      var images = []; var $imagesDiv; document.addEventListener("deviceready", init, false); function init() { $("#addPicture").on("touchend", selPic); $imagesDiv = $("#images"); $("#uploadPictures").on("touchend", uploadPics); } function selPic() { navigator.camera.getPicture(function(f) { var newHtml = "<img src='"+f+"'>"; $imagesDiv.append(newHtml); images.push(f); if(images.length === 1) { $("#uploadPictures").removeAttr("disabled"); } }, function(e) { alert("Error, check console."); console.dir(e); }, { quality: 50, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, destinationType: Camera.DestinationType.FILE_URI }); } function uploadPics() { alert("Ok, going to upload "+images.length+" images."); var defs = []; var fd = new FormData(); images.forEach(function(i) { alert('processing '+i); var def = $.Deferred(); window.resolveLocalFileSystemURL(i, function(fileEntry) { alert('got a file entry'); fileEntry.file(function(file) { alert('now i have a file ob'); console.dir(file); var reader = new FileReader(); reader.onloadend = function(e) { var imgBlob = new Blob([this.result], { type:file.type}); fd.append('file'+(images.indexOf(i)+1), imgBlob); fd.append('fileName'+(images.indexOf(i)+1), file.name); def.resolve(); }; reader.readAsArrayBuffer(file); }, function(e) { alert('error getting file', e); }); }, function(e) { alert('Error resolving fs url', e); }); defs.push(def.promise()); }); $.when.apply($, defs).then(function() { alert("all things done"); var request = new XMLHttpRequest(); request.open('POST', 'url', true); request.send(fd); }); } Do lado do servidor, onde eu deveria receber a requisição e upar os arquivos, está conforme código abaixo:
      <?php header("Access-Control-Allow-Origin: *"); $imgFileName=date("Y").date("m").date("j")."_".$_POST['index']."_".rand(1000,9999).".jpg"; if(move_uploaded_file($_FILES['file']['tmp_name'], "anuncios/".$imgFileName)){ echo "upload ok"; //or anything you need } ?>  
    • Por Kellison Ruan
      Olá galera, Boa tarde!
      Estou com um probleminha em Ionic que está quebrando muito minha cabeça por dias.
      Método de pagamento do paypal aparece em meu site, mas não aparece no app ionic, o que será? Já tentei de tudo. Esse app faz comunicação via API do Woocommerce, e lá está habilitado a forma de pagamento com PayPal, porém só não aparece no app, já que na página de checkout no meu site, aparece.
       
      Segue o código da página de checkout do app:
       
      import { Component, Inject } from '@angular/core'; import { NavController, NavParams, AlertController, Loading, LoadingController, ToastController, App } from 'ionic-angular'; import { PlacedPage } from '../placed/placed'; import { PaymentGateway } from "../../models/payment-gateway.models"; import { Constants } from "../../models/constants.models"; import { WordpressClient } from '../../providers/wordpress-client.service'; import { Global } from '../../providers/global'; import { Subscription } from "rxjs/Subscription"; import { CartItem } from "../../models/cart-item.models"; import { OrderRequest } from "../../models/order-request.models"; import { Address } from "../../models/address.models"; import { ShippingLine } from "../../models/shipping-line.models"; import { UserResponse } from "../../models/user-response.models"; import { OrderResponse } from "../../models/order-response.models"; import { Currency } from "../../models/currency.models"; import { InAppBrowser, InAppBrowserOptions } from '@ionic-native/in-app-browser'; import { sha512 } from 'js-sha512'; import { APP_CONFIG, AppConfig } from '../../app/app.config'; import { OrderUpdateRequest } from '../../models/order-update-request.models'; import { Coupon } from '../../models/coupon.models'; import { HomePage } from '../home/home'; import { TranslateService } from '@ngx-translate/core'; import { Helper } from '../../models/helper.models'; import { ShippingMethod } from '../../models/shipping-method.models'; import { PayPal, PayPalPayment, PayPalConfiguration, PayPalPaymentDetails } from '@ionic-native/paypal'; @Component({ selector: 'page-payment', templateUrl: 'payment.html', providers: [WordpressClient] }) export class PaymentPage { private loading: Loading; private loadingShown: Boolean = false; private placedPagePushed: Boolean = false; private paymentDone: Boolean = false; private paymentFailAlerted: Boolean = false; private subscriptions: Array<Subscription> = []; private paymentGateways = new Array<PaymentGateway>(); private cartItems: Array<CartItem>; private selectedPaymentGateway; private selectedAddress: Address; private orderRequest: OrderRequest; private orderId = -1; private user: UserResponse; private totalItems = 0; private total = 0; private couponApplied = false; private pickupTime = 0; private deliveryTime = 0; private shippingChargeGlobal: number; constructor(@Inject(APP_CONFIG) private config: AppConfig, public translate: TranslateService, private iab: InAppBrowser, private toastCtrl: ToastController, public navCtrl: NavController, private navParams: NavParams, private service: WordpressClient, private loadingCtrl: LoadingController, private alertCtrl: AlertController, public appCtrl: App) { this.cartItems = this.navParams.get('cart'); this.totalItems = this.navParams.get('totalItems'); this.total = this.navParams.get('total'); this.shippingChargeGlobal = this.navParams.get('shippingChargeGlobal'); let paymentGateways = JSON.parse(window.localStorage.getItem(Constants.PAYMENT_GATEWAYS)); this.selectedAddress = JSON.parse(window.localStorage.getItem(Constants.SELECTED_ADDRESS)); if (paymentGateways != null) { for (let pg of paymentGateways) { if (pg.enabled && this.paymentImplemented(pg.id)) { this.paymentGateways.push(pg); } } } } ionViewWillLeave() { this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); }); this.dismissLoading(); } paymentImplemented(id) { return id === "pumcp" || id === "payuindia" || id === "cod"; } paymentMethod(paymentGateway) { this.selectedPaymentGateway = paymentGateway; } placedPage() { if (this.selectedPaymentGateway == null) { this.translate.get('field_error_payment_method').subscribe(value => { this.showToast(value); }); } else { this.orderRequest = new OrderRequest(); this.orderRequest.payment_method = this.selectedPaymentGateway.id ? this.selectedPaymentGateway.id : "cod"; this.orderRequest.payment_method_title = this.selectedPaymentGateway.title ? this.selectedPaymentGateway.title : "cod"; this.orderRequest.set_paid = false; this.orderRequest.billing = this.selectedAddress; this.orderRequest.shipping = this.selectedAddress; this.user = JSON.parse(window.localStorage.getItem(Constants.USER_KEY)); this.orderRequest.customer_id = String(this.user.id); let selectedShippingMethod: ShippingMethod = JSON.parse(window.localStorage.getItem(Constants.SELECTED_SHIPPING_METHOD)); if (selectedShippingMethod) { let shippingTotal = 0; for (let ci of this.cartItems) { if (!ci.product.shipping_cost_use_global && ci.product.shipping_cost != 1) shippingTotal = shippingTotal + ci.product.shipping_cost; } if (this.shippingChargeGlobal != -1) { shippingTotal = shippingTotal + this.shippingChargeGlobal; } this.orderRequest.shipping_lines = new Array<ShippingLine>(); this.orderRequest.shipping_lines.push(new ShippingLine(selectedShippingMethod.method_id, selectedShippingMethod.method_title, String(shippingTotal))); } this.orderRequest.line_items = this.cartItems; for (let item of this.orderRequest.line_items) { item.product = null; } this.translate.get('order_creating').subscribe(value => { this.presentLoading(value); }); let coupon: Coupon = JSON.parse(window.localStorage.getItem(Constants.SELECTED_COUPON)); let subscription: Subscription = this.service.createOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), this.orderRequest).subscribe(data => { this.orderId = data.id; if (coupon) { this.applyCoupon(coupon); } else { this.orderPlaced(); } }, err => { console.log(err); this.dismissLoading(); let orderId = Helper.extractOrderIdFromError(err); if (orderId != -1) { this.orderId = orderId; if (coupon) { this.applyCoupon(coupon); } else { this.orderPlaced(); } } else { this.translate.get('order_failed').subscribe(value => { this.showToast(value); }); this.appCtrl.getRootNav().setRoot(HomePage); } }); this.subscriptions.push(subscription); } } applyCoupon(coupon) { let couponSubs: Subscription = this.service.applyCouponCode(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), coupon.code).subscribe(data => { this.couponApplied = true; window.localStorage.removeItem(Constants.SELECTED_COUPON); this.translate.get('confirm_order_coupon_applied').subscribe(value => { this.showToast(value); }); this.orderPlaced(); }, err => { console.log(err); this.dismissLoading(); }); this.subscriptions.push(couponSubs); } orderPlaced() { this.dismissLoading(); if (this.selectedPaymentGateway.id && this.selectedPaymentGateway.id === "cod") { this.clearCart(); this.navCtrl.setRoot(PlacedPage); } else if (this.selectedPaymentGateway.id === "pumcp" || this.selectedPaymentGateway.id === "payuindia") { this.initPayUMoney(); } else { this.translate.get('order_placed_cod').subscribe(value => { this.showToast(value); }); this.clearCart(); this.navCtrl.setRoot(PlacedPage); } } initPayUMoney() { let name = this.user.first_name && this.user.first_name.length ? this.user.first_name : this.user.username; let mobile = this.user.username; let email = this.user.email; let bookingId = String(Math.floor(Math.random() * (99 - 10 + 1) + 10)) + this.orderId; let productinfo = this.orderId; let salt = this.config.payuSalt; let key = this.config.payuKey; let amt = this.couponApplied ? this.total : this.totalItems; let string = key + '|' + bookingId + '|' + amt + '|' + productinfo + '|' + name + '|' + email + '|||||||||||' + salt; let encrypttext = sha512(string); //let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&salt=" + salt + "&key=" + key; let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&hash=" + encrypttext + "&salt=" + salt + "&key=" + key; let options: InAppBrowserOptions = { location: 'yes', clearcache: 'yes', zoom: 'yes', toolbar: 'no', closebuttoncaption: 'back' }; const browser: any = this.iab.create(url, '_blank', options); browser.on('loadstop').subscribe(event => { browser.executeScript({ file: "payumoney/payumoneyPaymentGateway.js" }); if (event.url == "http://localhost/success.php") { this.paymentSuccess(); browser.close(); } if (event.url == "http://localhost/failure.php") { this.paymentFailure(); browser.close(); } }); browser.on('exit').subscribe(event => { if (!this.paymentDone && !this.paymentFailAlerted) { this.paymentFailure(); } }); browser.on('loaderror').subscribe(event => { this.showToast('something_went_wrong'); }); } paymentFailure() { this.paymentFailAlerted = true; let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), new OrderUpdateRequest('cancelled')).subscribe(data => { }, err => { console.log(err); }); this.subscriptions.push(subscription); this.translate.get(['payment_fail_title', 'payment_fail_message', 'ok']).subscribe(res => { let alert = this.alertCtrl.create({ title: res.payment_fail_title, message: res.payment_fail_message, buttons: [{ text: res.ok, role: 'cancel', handler: () => { this.done(); console.log('Okay clicked'); } }] }); alert.present(); }); } paymentSuccess() { this.paymentDone = true; this.clearCart(); this.translate.get('just_a_moment').subscribe(value => { this.presentLoading(value); }); let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), { set_paid: true }).subscribe(data => { this.done(); }, err => { this.done(); this.paymentSuccess(); console.log(err); }); this.subscriptions.push(subscription); } done() { if (!this.placedPagePushed) { this.placedPagePushed = true; this.dismissLoading(); this.appCtrl.getRootNav().setRoot(this.paymentFailAlerted ? HomePage : PlacedPage); } } private presentLoading(message: string) { this.loading = this.loadingCtrl.create({ content: message }); this.loading.onDidDismiss(() => { }); this.loading.present(); this.loadingShown = true; } private dismissLoading() { if (this.loadingShown) { this.loadingShown = false; this.loading.dismiss(); } } private presentErrorAlert(msg: string) { let alert = this.alertCtrl.create({ title: 'Error', subTitle: msg, buttons: ['OK'] }); alert.present(); } showToast(message: string) { let toast = this.toastCtrl.create({ message: message, duration: 3000, position: 'bottom' }); toast.onDidDismiss(() => { console.log('Dismissed toast'); }); toast.present(); } clearCart() { let cartItems = new Array<CartItem>(); window.localStorage.setItem('cartItems', JSON.stringify(cartItems)); } }  
    • Por tiagosp
      Olá, estou iniciando o aprendizado de programação para android e ios; realizando uma pesquisa no Google, me deparei com o PhoneGap, logo segui o passo a passo para a instalação, baixei o PhoneGap, instalei, baixei o visualizado no celular (android) e editei o arquivo index.html como informado!
      Porém em nenhum momento me foi solicitado para apontar o java, sdk, imagem do android, nada....
      Além disso, há muitas referências ao cordova, porém eu não entendo qual a funcionalidade dele.... estou perdido!
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.