Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Pedro bezerra

Manter dados carrinho Woocomerce

Recommended Posts

Seguinte, meu site e http://elojobmundo.com/?post_type=product tem um simulador de elos la, quando tento comprar ele redereciona para o carrinho mais o problema e que o produto não vai junto, ele alega que não tem nenhum produto. o que eu preciso fazer? pois tenho o codigo php e quero que va para o carrinho do woocommerce.

codigo do simulador:

<center>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function EloEvolution(attrs) {
  var image_path = 'http://elojob.com.br/calculadora/tier/';
  this._products = {
    b5: {
      id: 2854,
      price: 0,
      image: image_path + 'bronze_5.png'
    },
    b4: {
      id: 2854,
      price: 25,
      image: image_path + 'bronze_4.png'
    },
    b3: {
      id: 2854,
      price: 25,
      image: image_path + 'bronze_3.png'
    },
    b2: {
      id: 2854,
      price: 25,
      image: image_path + 'bronze_2.png'
    },
    b1: {
      id: 2854,
      price: 25,
      image: image_path + 'bronze_1.png'
    },
    s5: {
      id: 2855,
      price: 30,
      image: image_path + 'silver_5.png'
    },
    s4: {
      id: 2855,
      price: 30,
      image: image_path + 'silver_4.png'
    },
    s3: {
      id: 2855,
      price: 30,
      image: image_path + 'silver_3.png'
    },
    s2: {
      id: 2855,
      price: 30,
      image: image_path + 'silver_2.png'
    },
    s1: {
      id: 2855,
      price: 30,
      image: image_path + 'silver_1.png'
    },
    g5: {
      id: 2856,
      price: 35,
      image: image_path + 'gold_5.png'
    },
    g4: {
      id: 2856,
      price: 35,
      image: image_path + 'gold_4.png'
    },
    g3: {
      id: 2856,
      price: 35,
      image: image_path + 'gold_3.png'
    },
    g2: {
      id: 2856,
      price: 35,
      image: image_path + 'gold_2.png'
    },
    g1: {
      id: 2856,
      price: 35,
      image: image_path + 'gold_1.png'
    },
    p5: {
      id: 2857,
      price: 50,
      image: image_path + 'platinum_5.png'
    },
    p4: {
      id: 2857,
      price: 50,
      image: image_path + 'platinum_4.png'
    },
    p3: {
      id: 2857,
      price: 50,
      image: image_path + 'platinum_3.png'
    },
    p2: {
      id: 2857,
      price: 50,
      image: image_path + 'platinum_2.png'
    },
    p1: {
      id: 2857,
      price: 50,
      image: image_path + 'platinum_1.png'
    },
    d5: {
      id: 2858,
      price: 100,
      image: image_path + 'diamond_5.png'
    },
    d4: {
      id: 2858,
      price: 120,
      image: image_path + 'diamond_4.png'
    },
    d3: {
      id: 2858,
      price: 100,
      image: image_path + 'diamond_3.png'
    },
    d2: {
      id: 2858,
      price: 100,
      image: image_path + 'diamond_2.png'
    },
    d1: {
      id: 2858,
      price: 100,
      image: image_path + 'diamond_1.png'
    },
    c5: {
      id: 2896,
      price: 200,
      image: image_path + 'challenger_1-2.png'
    },
    c4: {
      id: 0,
      price: 0,
      image: image_path + 'challenger_1-2.png'
    },
    c3: {
      id: 0,
      price: 0,
      image: image_path + 'challenger_1-2.png'
    },
    c2: {
      id: 0,
      price: 0,
      image: image_path + 'challenger_1-2.png'
    },
    c1: {
      id: 0,
      price: 0,
      image: image_path + 'challenger_1-2.png'
    }
  };
 
  this.currencyFormat = 'R$';
  this.currencyDecimalSeparator = ',';
 
  this._errorMessages = {
    dest_lt_cur: "Nível Desejado é menor que o Atual"
  }
  this._sequence = [
    'b5','b4', 'b3', 'b2', 'b1',
    's5','s4', 's3', 's2', 's1',
    'g5','g4', 'g3', 'g2', 'g1',
    'p5','p4', 'p3', 'p2', 'p1',
    'd5','d4', 'd3', 'd2', 'd1',
    'c5','c4', 'c3', 'c2', 'c1'
  ];
  this.errors = [];
 
 
// ============== PUBLIC METHODS ================
 
  // Need to set these settings
  // this.selectCurrentTier = attrs['selectCurrentTier'];
  // this.selectCurrentDivision = attrs['selectCurrentDivision'];
  // this.currentWrapImage = attrs['currentWrapImage'];
  // this.selectDestinationTier = attrs['selectDestinationTier'];
  // this.selectDestinationDivision = attrs['selectDestinationDivision'];
  // this.destinationWrapImage = attrs['destinationWrapImage'];
  // this.priceContainer = attrs['priceContainer'];
  // this.addToCartButton = attrs['addToCartButton'];
  // this.addToCartUrl = attrs['addToCartUrl'];
  
  this.settings = function(attrs) {
    for (var key in attrs) {
      this[key] = attrs[key];
    }
    this._attachAddToCart();
 
    return this;
  }
 
  this.change = function() {
    this.ck = $(this.selectCurrentTier).val() + $(this.selectCurrentDivision).val();
    this.dk = $(this.selectDestinationTier).val() + $(this.selectDestinationDivision).val();
    this.current = this._products[this.ck];
    this.destination = this._products[this.dk];
 
    this.updateImage();
    var price = this.sumValue();
    $(this.priceContainer).text(this._formatCurrency(price));
    return this;
  }
 
  this.updateImage = function() {
    $(this.currentWrapImage).css('background-image', 'url(' + this.current.image + ')');
    $(this.destinationWrapImage).css('background-image', 'url(' + this.destination.image + ')');
 
    if($(this.selectDestinationTier).val() == 'c') {
     $(this.selectDestinationDivision).attr('disabled', 'disabled');
    }
    else {
     $(this.selectDestinationDivision).removeAttr('disabled');
}
  }
 
  this.sumValue = function() {
    this._getSequence();
    if(this.i_dest < this.i_cur) {
      this._addError('dest_gt_cur');
      return false;
    }
 
    var sum = 0;
    this._execInSequence(function(p, k){
      sum += p.price;
    });
    return sum;
  }
 
  this.addToCart = function() {
    var evo = this;
    if(evo.beforeAddToCart) evo.beforeAddToCart();
    evo._getSequence();
 
    var products = [];
    evo._execInSequence(function(p){
      products.push(p);
    });
 
    function ajaxOrRedirectToCart(_products) {
      var p = products.shift();
      if(!p){
        window.parent.location = evo.cartUrl;
      }
      var url = evo.addToCartUrl.replace('%product_id', p.id);
      jQuery.get(url).success(function(){
        ajaxOrRedirectToCart(_products);
      });
    }
 
    ajaxOrRedirectToCart(products);
  }
 
  this.errorMessages = function () {
    var trErrors = [];
    for(var i = 0; i < this.errors.length; i++) {
      var k = this.errors[i];
      if(this._errorMessages[k]) {
        trErrors.push(this._errorMessages[k]);
      } else {
        trErrors.push(k);
      }
      return trErrors;
    }
  }
 
// ============== PRIVATE METHODS ================
  this._getSequence = function() {
    for(var i = 0; i < this._sequence.length; i++) {
      if(this.ck === this._sequence[i]) {
        this.i_cur = i;
      }
      if(this.dk === this._sequence[i]) {
        this.i_dest = i;
      }
    }
  }
 
  this._execInSequence = function(func) {
    for(var i = this.i_cur + 1; i <= this.i_dest; i++) {
      var p_key = this._sequence[i];
      var product = this._products[p_key];
      func(product, p_key);
    }
  }
 
  this._formatCurrency = function(val) {
    var o = [];
    var decPart = new String(parseInt((val - parseInt(val)) * Math.pow(10, this._currencyDecimalQty)) || 0);
    var intPart = new String(parseInt(val) || 0);
    if (decPart < 10) {
      decPart = "0" + decPart;
    }
 
    o.push(this.currencyFormat);
    o.push(' ')
    o.push(intPart);
 
    o.push(this.currencyDecimalSeparator);
    o.push(decPart);
 
    return o.join('');
  }
 
  this._attachAddToCart = function() {
    var evo = this;
    jQuery(evo.addToCartButton).click(function(){
      evo.addToCart();
    });
  }
 
  this._addError = function(err) {
    this.errors.push(err);
  }
 
  this.init = function(attrs) {
    if(attrs) {
      this.settings(attrs);
    }
  }
  this.init(attrs);
}
 
$(function(){
  var evo = new EloEvolution({
    selectCurrentTier: '#ct',
    selectCurrentDivision: '#cd',
    selectDestinationTier: '#dt',
    selectDestinationDivision: '#dd',
    currentWrapImage: '#cti',
    destinationWrapImage: '#dti',
    priceContainer: '#price',
    addToCartButton: '#cart',
    addToCartUrl: '/?post_type=product&add-to-cart=%product_id',
    cartUrl: '/carrinho',
    beforeAddToCart: function() {
      jQuery('#loader').show();
    }
  }).change();
  $('#ct,#cd,#dt,#dd').change(function(){
    // we need to call inside an anonymous function
    // because we use `this`, inside evo.change function,
    // referring to evo instance, instead the dom object
    // that was changed.
    evo.change();
  });
});
</script>
 
<style>
 
* {
  -webkit-transition: all 0.4s ease-in-out;
  -moz-transition: all 0.4s ease-in-out;
  -o-transition: all 0.4s ease-in-out;
  transition: all 0.4s ease-in-out;
}
 
#content2 {
  width:725px;
  background:url('http://elojob.com.br/calculadora/bg_calc.png') no-repeat center top;
  height:410px;
  background-size: 100%;
}
 
.current_tier_img,
.desired_tier_img {
  width: 192px;
  height: 192px;
  background-image: url(http://elojob.com.br/calculadora/tier/bronze_5.png);
  text-align: center;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-repeat: no-repeat;
  font-size: 18px;
  position: absolute;
  left: 50%;
  top: 70px;
  ;
}
 
#wrapper {position: relative;}
 
.desired_tier_img {
  ;
}
 
.desired_division {
  background:#FFF;
}
 
.current_tier_img span,
.desired_tier_img span,
#loader, h2 {display: none;}
 
br {clear:both;}
 
/*
#loader {
  width: 100%;
  height: 100%;
  display: none;
  background-color: #fff;
  opacity: 0.9;
  position: absolute;
  text-align: center;
  vertical-align: middle;
  padding-top: 300px;
}*/
 
.current_tier_division,
.desired_tier_division {
  width:49%;
  float:left;
  margin-bottom:20px;
  position: relative;
}
 
#price {
  position: absolute;
  width: 100px;
  left:50%;
  text-align: center;
  font-family: 'Trebuchet Ms';
  color:#FFF;
  ;
  top: 170px;
  font-size: 18px;
 
}
 
#cart {
  width: 150px;
  height:72px;
  position: absolute;
  border: 0px;
  background:url(http://elojob.com.br/calculadora/bt_comprar.png) no-repeat center top;
  left: 50%;
  ;
  top: 220px;
  
}
 
#cart:hover {
  cursor: pointer;
  background:url(http://elojob.com.br/calculadora/bt_comprar2.png) no-repeat center top;
}
 
.current_tier,
.desired_tier {
  background:#FFF;
  position: absolute;
  top: 250px;
  left: 50%;
  ;
  width: 150px;
  height: 28px;
  ;
  width: 130px;
}
 
.current_tier select,
.desired_tier select {
  border:0px;
  background: none;
  height: 28px;
}
 
.current_tier select:first-child
.desired_tier select:first-child {
  width:100px;
}
 
.current_tier select:last-child,
.desired_tier select:last-child {
  float:right;
}
 
/*#price {
float: right;
padding: 5px 10px;
width: 83px;
text-align: right;
border: 1px dotted #d1d1d1;
background: #f1f1f1;
margin-right: 159px;}*/
 
</style>
<link type="text/css" rel="stylesheet" href="chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/style.css"><script type="text/javascript" charset="utf-8" src="chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/js/page_context.js"></script></head>
<body screen_capture_injected="true" cz-shortcut-listen="true">
<div id="loader">Adicionando produto no carrinho...<br>Obs: O tempo de espera depende da quantidade que for adicionado ao carrinho.<br /><img src="http://elojob.com.br/calculadora/ajax-loading.gif" /></div>
<div id="content2">
  <div id="main_content">
    
    <div id="wrapper">
      <div class="current_tier_division">
        <div id="cti" class="current_tier_img"><span>Posição Atual</span></div>
        <div class="current_tier">
          <select id="ct">
            <option value="b">Bronze</option>
            <option value="s" selected>Prata</option>
            <option value="g">Ouro</option>
            <option value="p">Platina</option>
            <option value="d">Diamante</option>
          </select>
          <select id="cd">
            <option>5</option>
            <option>4</option>
            <option>3</option>
            <option>2</option>
            <option selected>1</option>
          </select>
        </div>
      </div>
      <div class="desired_tier_division">
        <div id="dti" class="desired_tier_img"><span>Posição Desejada</span></div>
        <div class="desired_tier">
          <select id="dt">
            <option value="b">Bronze</option>
            <option value="s">Prata</option>
            <option value="g" selected>Ouro</option>
            <option value="p">Platina</option>
            <option value="d">Diamante</option>
     <option value="c">Mestre</option>
          </select>
          <select id="dd">
            <option selected="selected">5</option>
            <option>4</option>
            <option>3</option>
            <option>2</option>
            <option>1</option>
          </select>
        </div>
      </div>
      <div id="sv" class="server" style="display:none;">
        <select>
          <option>Brazil</option>
        </select> 
      </div> 
      <div class="vpn" style="display:none;">
        <input name="VPN Protection" type="checkbox" value="VPN Protection" id="vpn_id"></input>
      </div>
      <br>
      <h2> VALOR </h2>
      <div id="price">Valor</div>
      <div>
        <button id="cart"></button>
      </div>
    </div>
  </div>
</div>
</body>
</html>
</center>

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por Rafael_Ferreira
      Não consigo carregar a imagem do captcha do meu formulário. Foi testado com o xampp e easyphp. Também não carregou a imagem de outros captcha. 
       
       
    • Por luiz monteiro
      Olá, tudo bem?
       
      Estou melhorando meu conhecimento em php e mysql e, me deparei com o seguinte. A tabela da base de dados tem um campo do tipo varchar(8) o qual armazena números. Eu não posso alterar o tipo desse campo. O que preciso é fazer um select para retornar o números que contenham zeros a direita ou a esquerda.
      O que tentei até agora
       
      Ex1
      $busca = $conexao->prepare("select campo form tabela where (campo = :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form']);
       
      Se a direita da string $_REQUEST['campo_form'] termina ou inicia com zero ou zeros, a busca retorna vazio.
      Inseri dados numéricos, da seguinte maneira para testar: 01234567;  12345670: 12345678: 12340000... entre outros nessa coluna. Todos os valores que não terminam ou não iniciam com zero ou zeros, o select funciona.
       
       
      Ex2
      $busca = $conexao->prepare("select campo form tabela where (campo = 0340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex3
      $busca = $conexao->prepare("select campo form tabela where (campo = '02340001' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex4
      $busca = $conexao->prepare("select campo form tabela where (campo like 2340000) ");
      Esse número está cadastrado, mas não retorna.
       
      Ex5
      $busca = $conexao->prepare("select campo form tabela where (campo like '12340000') ");
      Esse número está cadastrado, mas não retorna.
       
      Ex6
      $busca = $conexao->prepare("select campo form tabela where (campo like '"12340000"' ) ");
      Esse número está cadastrado, mas não retorna.
       
       
      Ex7
      $busca = $conexao->prepare("select campo form tabela where (campo like :campo) ");
      $busca->bindParam('campo', $_REQUEST['campo_form'])
      Não retorna dados.
       
      O  $_REQUEST['campo_form'] é envio via AJAX de um formulário. 
      Usei o gettype para verificar o post, e ele retorna string.
      Fiz uma busca com número 12345678 para verificar o que o select retorna, e também retrona como string.
       
      Esse tipo de varchar foi usado porque os números que serão gravados nesse campo,  terão zeros a direita ou na esquerda. Os tipos number do mysql não gravam zeros, então estou usando esse. O problema é a busca.
      Agradeço desde já.
       
       
    • Por daemon
      Boa tarde,
       
      Eu tenho uma rotina que faz uma leitura do arquivo .xml de vários sites.

      Eu consigo pegar o tópico e a descrição, e mostrar a imagem que esta na pagina do link.
      Para isso utilizo esta função:
      function getPreviewImage($url) { // Obter o conteúdo da página $html = file_get_contents($url); // Criar um novo objeto DOMDocument $doc = new DOMDocument(); @$doc->loadHTML($html); // Procurar pela tag meta og:image $tags = $doc->getElementsByTagName('meta'); foreach ($tags as $tag) { if ($tag->getAttribute('property') == 'og:image') { return $tag->getAttribute('content'); } } // Se não encontrar og:image, procurar pela primeira imagem na página $tags = $doc->getElementsByTagName('img'); if ($tags->length > 0) { return $tags->item(0)->getAttribute('src'); } // Se não encontrar nenhuma imagem, retornar null return null; } // Uso: $url = "https://example.com/article"; $imageUrl = getPreviewImage($url); if ($imageUrl) { echo "<img src='$imageUrl' alt='Preview'>"; } else { echo "Nenhuma imagem encontrada"; }  
      Mas estou com um problema, esta funcão funciona quando coloco em uma pagina de teste.php. Preciso mostrar em uma página inicial diversas fotos de todos os links. (No caso acima só funciona 1).
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, me permita tirar uma dúvida com os amigos.

      Tenho um Formulário onde o Usuário digita todos os Dados necessários.

      Minha dúvida:
      --> como faço após o usuário digitar os dados e salvar, o Sistema chamar uma Modal ou mensagem perguntando se deseja imprimir agora ?

      Grato,
       
      Cesar
    • Por Carcleo
      Tenho uma abela de usuarios e uma tabela de administradores e clientes.
      Gostaria de uma ajuda para implementar um cadastro
       
      users -> name, login, passord (pronta) admins -> user_id, registratiom, etc.. client -> user_id, registratiom, etc...
      Queria ajuda para extender de user as classes Admin e Client
      Olhem como estáAdmin
      <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Admin extends User {     use HasFactory;            protected $fillable = [         'name',         'email',         'password',         'registration'     ];      private string $registration;     public function create(         string $name,          string $email,          string $password,         string $registration     )     {         //parent::create(['name'=>$name, 'email'=>$email, 'password'=>$password]);         parent::$name = $name;         parent::$email = $email;         parent::$password = $password;         $this->registration = $registration;     } } User
      <?php namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class User extends Authenticatable {     /** @use HasFactory<\Database\Factories\UserFactory> */     use HasFactory, Notifiable;     static string $name;     static string $email;     static string $password;     /**      * The attributes that are mass assignable.      *      * @var list<string>      */     protected $fillable = [         'name',         'email',         'password',     ];          /**      * The attributes that should be hidden for serialization.      *      * @var list<string>      */     protected $hidden = [         'remember_token',     ];     /**      * Get the attributes that should be cast.      *      * @return array<string, string>      */     protected function casts(): array     {         return [             'email_verified_at' => 'datetime',             'password' => 'hashed',         ];     }          public function roles() : BelongsToMany {         return $this->belongsToMany(Role::class);     }       public function hasHole(Array $roleName): bool     {                 foreach ($this->roles as $role) {             if ($role->name === $roleName) {                 return true;             }         }         return false;     }         public function hasHoles(Array $rolesName): bool     {                 foreach ($this->roles as $role) {             foreach ($rolesName as $rolee) {             if ($role->name === $rolee) {                 return true;             }          }         }         return false;     }         public function hasAbility(string $ability): bool     {         foreach ($this->roles as $role) {             if ($role->abilities->contains('name', $ability)) {                 return true;             }         }         return false;     }     } Como gravar um Admin na tabela admins sendo que ele é um User por extensão?
      Tentei assim mas é claro que está errado...
      public function store(Request $request, Admin $adminModel) {         $dados = $request->validate([             "name" => "required",             "email" => "required|email",             "password" => "required",             "registration" => "required"         ]);         $dados["password"] =  Hash::make($dados["password"]);                  $admin = Admin::where("registration",  $dados["registration"])->first();                  if ($admin)              return                    redirect()->route("admin.new")                             ->withErrors([                                 'fail' => 'Administrador já cadastrados<br>, favor verificar!'                   ]);                            $newAdmin = $adminModel->create(                                    $dados['name'],                                    $dados['email'],                                    $dados['password'],                                    $dados['registration']                                 );         dd($newAdmin);         $adminModel->save();         //$adminModel::create($admin);                  return redirect()->route("admin.new")->with("success",'Cadastrado com sucesso');     }  
×

Informação importante

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