Form submit button in a DataTable not working as subarray

Hello i am using a datatable to retrive data with dynamic table data. using subarray to fetch data . i have included a form to that aray but the form function is not working whene i script to the fetch file. please help me with this.

    <?php
session_start();
// $id = $_SESSION['id'];
//fetch.php
$connect = mysqli_connect('localhost', 'sbcldb_management', 'management_server2021', 'sbcldb_management');
$columns = array('C_Number', 'coupon', 'date', 'District','Upazilla','storename','eye');
$query = "SELECT * FROM code_genarate WHERE status='1' ";
if(isset($_POST["search"]["value"]))
{
 $query .= 'AND
  (C_Number LIKE "%'.$_POST["search"]["value"].'%"
  OR coupon LIKE "%'.$_POST["search"]["value"].'%"
  OR date LIKE "%'.$_POST["search"]["value"].'%"
  OR District LIKE "%'.$_POST["search"]["value"].'%"
  OR Upazilla LIKE "%'.$_POST["search"]["value"].'%"
  OR storename LIKE "%'.$_POST["search"]["value"].'%")
  ';
}

if($_POST["district"] != '')
{
$did = $_POST["district"];
$sql = "SELECT * FROM districts WHERE id = '$did'";
$res = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($res))
{
  $district = $row['district'];
}
$uid = $_POST["upazilla"];
if($uid > 0){
  $sql = "SELECT * FROM upazilla WHERE id = '$uid'";
  $res = mysqli_query($connect, $sql);
  while($row = mysqli_fetch_array($res))
  {
    $upazilla = $row['upazilla'];
  }
 $query .= "AND District='$district' AND Upazilla= '$upazilla'";
 }else{

 $query .= "AND District='$district'";
 }

$query1 = '';

if($_POST["length"] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));

$result = mysqli_query($connect, $query . $query1);

$data = array();
// $total = 0;
while($row = mysqli_fetch_array($result))
{
  // $total += $row["Amount"];
  $sub_array = array();
  // $sub_array[] = '<a href="../customers/customerdetails.php?id='.$row['C_Number'].'">'.$row['C_Number'].'</a>';
  // $sub_array[] = $row["Amount"];;
  // $sub_array[] = $row["SaleDate"];
  $sub_array[] = $row["C_Number"];
  $sub_array[] = $row["coupon"];
  $number = $row['C_Number'];

  $sub_array[] = $row["date"];
  $sub_array[] = $row["District"];
  $sub_array[] = $row["Upazilla"];
  $sub_array[] = $row["storename"];

  $sub_array[] = '<form name="submit-to-gateway" id="myForm">
  <div id="form_alerts"></div>
  <div class="row">
    <div class="col-8">
  <input type="hidden" name="text" value="Dear Retailer, Your Software Download link is http://sbcldb.ltd/application/sbcldb.apk  ,With the best Regards, SBCLDB LIMITED." </input>
  <input type="text" class="form-control" name="number" value="'.$row['C_Number'].'"/>
  </div>
  <div class="col-4">
  <button class="btn btn-primary" type="submit" class="form-control" id="sms_btn" name="sms_btn">Send</button>

</div>
</div>
  </form>';
  $data[] = $sub_array;
}
function get_all_data($connect)
{
$quer = "SELECT * FROM retailer_sales";
 $result = mysqli_query($connect, $quer);
 return mysqli_num_rows($result);
}

$output = array(
 "draw"    => intval($_POST["draw"]),
 "recordsTotal"  =>  get_all_data($connect),
 "recordsFiltered" => $number_filter_row,
 "data"    => $data
);




echo json_encode($output);



<script>
  const scriptURL = 'https://script.google.com/macros/s/AKfycbzfMQmBwDEO8k0H8jeLlKTE_GzK0XuQ1unZd_5ib_DDBhM17b6FVahIW5f3W4FyfCNOAw/exec'
  const form = document.forms['submit-to-gateway']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, {
        method: 'POST',
        body: new FormData(form)
      })
      .then(response => $("#form_alerts").html("<div class='alert alert-success'>Id Sent Successfully.</div>"))
      .catch(error => $("#form_alerts").html("<div class='alert alert-danger'>Id Could not be Sent.</div>"))
      $('#myForm')[0].reset();
  })
</script>


?>

the form is submitting on a html page perfectly but i cant merger this to the datatable.
please help me with this.

React JS: Unexpected token < in JSON at position 0

I’m trying to parse and get fetch data from URL, but got the error like:

Unexpected token < in JSON at position 0

the URL contains this such of data:

<wfs:FeatureCollection xmlns="http://www.opengis.net/wfs" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:kict="kict" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://192.168.0.70:28080/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd kict http://192.168.0.70:28080/geoserver/wfs?service=WFS&version=1.0.0&request=DescribeFeatureType&typeName=kict%3Av_plans_photo">
<gml:boundedBy>
<gml:null>unknown</gml:null>
</gml:boundedBy>
<gml:featureMember>
<kict:v_plans_photo fid="v_plans_photo.fid-400b9b06_17e425c6260_-1a99">
<kict:rownum>61689</kict:rownum>
<kict:plan_id>6178a7a0974e58001ac90ac5</kict:plan_id>
<kict:cmo>5c38212c23b65b0d045d2de8</kict:cmo>
<kict:cmo_str>5c38212c23b65b0d045d2de8</kict:cmo_str>
<kict:plan_name/>
<kict:plan_cn>포트홀 작업추가</kict:plan_cn>
<kict:opert_ty>B1</kict:opert_ty>
<kict:operTy>B1</kict:operTy>
<kict:opert_sttus>A4</kict:opert_sttus>
<kict:opert_plan_cn>포트홀 작업추가</kict:opert_plan_cn>
<kict:create_at_year>2021</kict:create_at_year>
<kict:create_at_month>10</kict:create_at_month>
<kict:create_at_week>43.0</kict:create_at_week>
<kict:created_at>2021-10-27T01:13:04.557Z</kict:created_at>
<kict:created_by>강릉_보수원002</kict:created_by>
<kict:cvpl_ty>5cfda3bab615b60845c79dda</kict:cvpl_ty>
<kict:acmslts_id>6178a89e974e58001ac90b02</kict:acmslts_id>
<kict:cvpl_ty_code>900900</kict:cvpl_ty_code>
<kict:cvpl_ty_nm>포트홀</kict:cvpl_ty_nm>
<kict:cvpl_name>포트홀</kict:cvpl_name>
<kict:cmo_org_code>1613208</kict:cmo_org_code>
<kict:cmo_grp_nm>원주청</kict:cmo_grp_nm>
<kict:cmo_code>22</kict:cmo_code>
<kict:cmo_nm>강릉국토관리사무소</kict:cmo_nm>
<kict:cmoNm>강릉국토관리사무소</kict:cmoNm>
<kict:photo_type>완료</kict:photo_type>
<kict:begin_lat>37.7164584026444</kict:begin_lat>
<kict:begin_lon>128.987696737366</kict:begin_lon>
<kict:photo_lat>37.7161098</kict:photo_lat>
<kict:photo_lon>128.9880585</kict:photo_lon>
<kict:geom>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">128.9880585,37.7161098</gml:coordinates>
</gml:Point>
</kict:geom>
<kict:photo_url>http://hms.molit.go.kr:9080/api/uploads/2021/6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:photo_url>
<kict:store_path>uploads/2021/6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:store_path>
<kict:photo_filename>6178a7a0974e58001ac90ac5_202110271017147661635297434478.png</kict:photo_filename>
<kict:photo_size>1122621</kict:photo_size>
</kict:v_plans_photo>
</gml:featureMember>
</wfs:FeatureCollection>

I just used fetch to parse and fetch data like below:

let url = "/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=kict:v_plans_photo&srsName=EPSG:4326&maxFeatures=10000&format_options=callback:getJson&cql_filter=INTERSECTS(geom, POINT (128.9880585 37.7161098))"

if (url) {
    fetch(url, {
       headers : { 
          'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then((response) => {
        console.log(response)
     },
     (error) => {
      this.setState({
         isLoaded: true,
         error
       });
       console.log(`fetch failed: ${this.state.error}`)
       }
     )
  }

How can I get data from that URL using fetch?

Proper way to return streaming data mongoose

I am trying to return some data that is streamed from an express server. Here is my code:

const cursor = Review.find({}).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
 console.log(doc);
 // Prints documents one at a time 
 res.status(200).json(doc); 
}

What is the proper way to return the data to the frontend so that doc ends up populating an array?

form wont export when search (search and export conflict)

I got one form with two submit button.

blade.php

    <form method="GET" id = "uploadForm">
        @csrf

        <div class="form-group">
            <button type="submit" value="Search" class="btn btn-info" id="search_btn" onclick="searchForm()">Search <i class="fa fa-search"></i></button> &nbsp;
            <button type="submit" value="Export" class="btn btn-success float-right" id="export_btn" onclick="exportForm()">Export <i class="fa fa-download"></i></button>
        </div>
    </form>

js file

function searchForm() get data and display as datatable
{
    let form = $('#uploadForm');
    let table = $('.datatable');

    form.attr('action', '/search').submit(function(e) {
        e.preventDefault();

        if ($.fn.DataTable.isDataTable(".datatable")) {
            table.DataTable().clear().destroy();
        }

        table.DataTable({
            processing: true,
            serverSide: true,
            bDestroy: true,
            bJQueryUI: true,
            ajax: {
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url : form.attr('action'),
                type : form.attr('method'),
                data : {
                    type: $("#type").val(),
                    from: $("#from").val(),
                    to  : $("#to").val(),
                },
            },
            columnDefs: [
                {'data': 'trx_id',      "targets": 0, title: "Trx ID"},
                {'data': 'type',        "targets": 1, title: "Type"},
                {'data': 'sender_id',   "targets": 2, title: "Sender ID"},
                {'data': 'receiver_id', "targets": 3, title: "Receiver ID"},
                {'data': 'amount',      "targets": 4, title: "Amount"},
                {'data': 'remark',      "targets": 5, title: "Method"},
                {'data': 'fee',         "targets": 6, title: "Fees"},
                {'data': 'afterFee',    "targets": 7, title: "Amount After Fees"},
                {'data': 'date',        "targets": 8, title: "Date"},
            ],
            error(){
                alert("error");
            }
        });
        // prevent submit multiple time
        e.stopImmediatePropagation();
        return false;
        // prevent submit multiple time
    });
}

function exportForm() //export data and download excel 
{
    $('#uploadForm').attr('action', '/export');
    $('#uploadForm').attr('target', '_blank').submit();
}

Search_form and export_form both work fine. But it have problem when I call search_form then call export_form, it will always go into search_form and will not download excel. I have run out of idea how to solve this issues.

Is the anyway to solve build error in nextjs?

I am building a site in nextJS. Recently I got an error when I run yarn run dev for building. Which is,

> Build error occurred
Error: Export encountered errors on following paths:
        /[page]/[pid]/[slug]
    at /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/export/index.js:500:19
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:987:17
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async /home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:861:13
    at async Span.traceAsyncFn (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/trace/trace.js:74:20)
    at async Object.build [as default] (/home/ubu/Desktop/Projects/HexaCom-Final One/HexaCom/node_modules/next/dist/build/index.js:82:25)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I tried to solve it by adding solutions from the internet like adding log files inside
getStaticProps function. Nothing solving the issue.

Validation different message on the condition in password?

Hi i would like some help on my password field where i have this 2 type of validation message

first if the input for password when user click on submit button it be display please enter password!

2nd if the input for password is incorrect where it didnt meeet the requirement it display password do not meet the requirement!

Here my code for my html for the password and submit button

                                <div class="form-group row">
                                <label for="validationpassword" class="col-form-label passwordadduser">*Password:</label>
                                <div class="col-6 d-flex">
                                <input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="password" placeholder="Password"  required>
                                <i class="bi bi-eye-slash" id="togglePassword"></i>
                                <div style="margin-left: 15px;" class="invalid-tooltip password-empty" hidden>
                                    Enter a password!
                                </div>
                                <div style="margin-left: 15px;" class="invalid-tooltip password-notmeet" hidden>
                                    Password do not meet the requirement!
                                </div>
                                </div>
                            </div>

                        <button type="submit" class="btn-primary submitbutton">Add</button>

I have try a Jquery/JavaScript but seems not working i think i doing something wrong here

var empty = $(document.getElementById("password").value == '')
 if (empty){
 $('.pass').removeAttr('hidden');
 }
 else{

 $('.pass').attr('hidden', '');
 }

needed help as i not familiar with how the input should work ?

why the template ui did not show the vue data

I am a newbie with Vue, now I define the vue code like this:

import Vue from "vue";

export default Vue.extend({
  data: () => {
    message: "show message";
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div id="app">
    <div v-text="message"></div>
  </div>
</template>

why the UI did not show the Vue data message? this is my sandbox version code: https://codesandbox.io/s/loving-sea-snvfj?file=/src/App.vue:149-237

Js local user entry [duplicate]

I was trying to make a user entry in local and write this code but always “else”
working even if i write correct info. Can you help me with making this code working ?

var email1 = "[email protected]";
var password1 = "1234";

var eposta = document.getElementById("email");
var sifre = document.getElementById("pass");

function login() {
    if (eposta == email1 && sifre == password1) {
    window.location.href = "products.html";
    alert("Welcome", email1);
    }
    else {
        alert("Wrong e-mail or password")
    }
}

Issue with Javascript in Posting system

So, I have a posting system. When you type a post in the input field and click the submit button, the post displays with the help of PHP and AJAX.

Now on that post are stuff like a like button and comment button, and when you click the like button, it turns blue. Now, after making a post and the post displaying, clicking the like button will make it blue. However, let’s say you make another post. For that post, everything works, except when you click the like button on the second or third post, it makes the like button on the first post only turn blue, similarly with the comment button. Also, the first post has a background color of silver (#C0C0C0), however any other post, like the second or third post, don’t. They have no background color.

This stuff (turning blue on click) is accomplished using JavaScript. What I identified from this is that the JS isn’t working for any other post besides the first post. To resolve this, I tried changing the position of the JS in the code because I thought it had something to do with the scope, but it didn’t. Please help, with the JS and the background color issue.

PHP/HTML/CSS Code:

<style>
.textPost {
  margin-top: 170px;
  width: 650px;
  height: 400px;
  position: fixed;
  background-color: #C0C0C0;
  margin-left: 685px;
  border-radius: 15px;
}

.textpostFormat {
  margin-left: -640px;
  position: fixed;
}
</style>

<div class="textPost">
  <?php

  $sql = "SELECT * FROM posts";
  $result = mysqli_query($connection, $sql);
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

  ?>
  <div class="textpostFormat" id="textpostFormat">
    // all the post content (like, comment buttons, etc.)
  </div>
  <?php

  }
}

  ?>
</div>

AJAX code (to display posts without page refresh):

function makePost() {
  var postContent = $("#postContent").val();
  if (postContent.length > 0) {
    jQuery.ajax({
      url:"yourposts.php",
      data:{
        postContent: postContent
      },
      type:"POST",
      success:function(data){
        if (data == "success") {
          $("#textPostFormat").html(postContent);
        }
      }
    });
  }
}

Javascript code (for turning like button blue and stuff):

<script type="text/javascript">

function changetextUpvote() {
  var textUpvoteImg = document.getElementById('textUpvoteImg');
  if (textUpvoteImg.src.match("orangeupvote")) {
    textUpvoteImg.src = "img/upvote.png";
  } else {
    textUpvoteImg.src = "img/orangeupvote.png";
    textDownvoteImg.src = "img/downvote.png";
  }
}

function changetextDownvote() {
  var textDownvoteImg = document.getElementById('textDownvoteImg');
  if (textDownvoteImg.src.match("orangedownvote")) {
    textDownvoteImg.src = "img/downvote.png";
  } else {
    textDownvoteImg.src = "img/orangedownvote.png";
    textUpvoteImg.src = "img/upvote.png";
  }
}

function textLikeClick() {
  document.getElementById('textLike').style.color = "blue";
}

function textCommentClick() {
  document.getElementById('textComment').focus();
}

</script>

Why can’t I get text with .text method when text exists?

I’m practicing web scraping using Selenium, and I hope to get the color of this dress. When I inspect the website, I can see the text content under the ‘screen-reader-text’ class but when I try to fetch it, I always get an empty value. What’s going on? Is it because the Zara website blocks me to scrape it? My code is the following,

driver_path = 'D:/Python/Selenium/chromedriver'
option1 =  webdriver.ChromeOptions()
option1.add_experimental_option('detach',True)

driver = webdriver.Chrome(chrome_options=option1,executable_path=driver_path)
driver.get(url)

color = driver.find_element_by_xpath('//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul/li[1]/button/span/span/span').text

Since I wish to get all the possible colors, I also tried the following code, which doesn’t work as well:(

colors = driver.find_elements_by_xpath('//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul')
col = []
for i,color in enumerate(colors):
    prefix = '//*[@id="main"]/article/div[1]/div[2]/div[1]/div[3]/ul'
    try: 
        col.append(color.find_elements_by_xpath(prefix+f'/li[{i}]'+'/button/span/span/span').text)
    except:
        pass
col

enter image description here

Why Lazy load doesn’t Perfectly?

Hello there I working on lazy load images and it works perfectly, but I face a problem when I have to add, different attributes in images extension to enhance the quality.

when I scroll down to the bottom at class has been added lazy-img, src attribute src has been implemented into the image tag and lazy load works perfectly.

where is my code which will only at the class lazy-img

this is the older jsFiddle not working
Older jsFiddle code

$(function($) {
  /**
   * @return {?}
   */
  $.fn.lazyimg = function() {
    return this.each(function() {
      /**
       * @return {undefined}
       */
      function o() {
        var threshold = $(window).height();
        if ($(window).scrollTop() + threshold > t.offset().top) {
          /** @type {!Image} */
          var a = new Image;
          /**
           * @return {undefined}
           */
          a.onload = function() {
            t.addClass("lazy-img");
          };
          a.src = s;
        }
      }
      var t = $(this);
      var a = t.attr("src");
      /** @type {number} */
      var i = Math.round(t.height());
      /** @type {string} */
      var s = "";
      s = a.match("s72-c") ? a.replace("/s72-c", i) : a;
      $(window).on("load scroll", o);
      o();
    });
  };
});

on other hand, in same condition my friend also used is jQuery code, which works perfectly without any problem.
he told me just rewrite the code reshuffle and use it for your project, but due to insufficient knowledge about jQuery I am not able to do this anyone can help me to rewrite this code again.

New jsFiddle working file
jsFiddle New

Please check this jsFiddle file it’s perfectly working for lazy load I want to arrange this code and so that I can use in my project.

I know it’s doesn’t sound good but I have to do nothing more good options available to use lazy load.
The permission has been taken from my friend that I can use this code for my project

Any kind of help or advice is highly appreciated

Get hidden input value on form POST after redirect to another page?

I’m using Visual Studio with asp.net, vb.net, and javascript in order to implement an API. I am editing sample code from Authorize.Net.

I need to pass the values of dataValue and dataDescriptor

<input type="hidden" name="dataValue" id="dataValue" />
<input type="hidden" name="dataDescriptor" id="dataDescriptor" />

to the next page after the form POSTS

    'This returns as EMPTY!!! right now
    Dim infoValue = Request.Form("dataValue")
    Dim infoDescriptor = Request.Form("dataDescriptor")

How can I pass these two hidden field values over to the next page?

FULL CODE

PaymentInfo.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="PaymentInfo.aspx.vb" Inherits="AuthorizeAccept.PaymentInfo" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<!--
    This file is a standalone HTML page demonstrating usage of the Authorize.net
    Accept JavaScript library when integrated with your own payment form.

    For complete documentation for the Accept JavaScript library, see
    https://developer.authorize.net/api/reference/features/acceptjs.html
-->
<head runat="server">
    <title>Sample form</title>
</head>

<body>

<script type="text/javascript"
    src="https://jstest.authorize.net/v1/Accept.js"
    charset="utf-8">
</script>

<form id="paymentForm" runat="server"
    method="POST"
    action="PaymentProcess.aspx" >
    <input type="text" name="cardNumber" id="cardNumber" placeholder="cardNumber" value="4111111111111111"/> <br><br>
    <input type="text" name="expMonth" id="expMonth" placeholder="expMonth" value="12"/> <br><br>
    <input type="text" name="expYear" id="expYear" placeholder="expYear" value="2028"/> <br><br>
    <input type="text" name="cardCode" id="cardCode" placeholder="cardCode" value="123"/> <br><br>
    <input type="text" name="amount" id="amount" placeholder="cardCode" value="6.00"/> <br><br>
    <input type="text" name="accountNumber" id="accountNumber" placeholder="accountNumber"/> <br><br>
    <input type="text" name="routingNumber" id="routingNumber" placeholder="routingNumber"/> <br><br>
    <input type="text" name="nameOnAccount" id="nameOnAccount" placeholder="nameOnAccount"/> <br><br>
    <input type="text" name="accountType" id="accountType" placeholder="accountType"/> <br><br>
    <input type="hidden" name="dataValue" id="dataValue" />
    <input type="hidden" name="dataDescriptor" id="dataDescriptor" />
    <button type="button" onclick="sendPaymentDataToAnet()">Pay</button>
</form>

<script type="text/javascript">

function sendPaymentDataToAnet() {
    var authData = {};
    authData.clientKey = "6bpMZ759ELh6K3dAWx7MVNqyYX88zsN5R3zj7FChrwnYjTQ3bQ93TS7h6YjcE64M";
    authData.apiLoginID = "93cWyMh9Kd6G";

    var cardData = {};
        cardData.cardNumber = document.getElementById("cardNumber").value;
        cardData.month = document.getElementById("expMonth").value;
        cardData.year = document.getElementById("expYear").value;
        cardData.cardCode = document.getElementById("cardCode").value;

    // If using banking information instead of card information,
    // build a bankData object instead of a cardData object.
    //
    // var bankData = {};
    //     bankData.accountNumber = document.getElementById('accountNumber').value;
    //     bankData.routingNumber = document.getElementById('routingNumber').value;
    //     bankData.nameOnAccount = document.getElementById('nameOnAccount').value;
    //     bankData.accountType = document.getElementById('accountType').value;

    var secureData = {};
        secureData.authData = authData;
        secureData.cardData = cardData;
        // If using banking information instead of card information,
        // send the bankData object instead of the cardData object.
        //
        // secureData.bankData = bankData;

    Accept.dispatchData(secureData, responseHandler);

    function responseHandler(response) {
        if (response.messages.resultCode === "Error") {
            var i = 0;
            while (i < response.messages.message.length) {
                console.log(
                    response.messages.message[i].code + ": " +
                    response.messages.message[i].text
                );
                i = i + 1;
            }
        } else {
            paymentFormUpdate(response.opaqueData);
        }
    }
}

function paymentFormUpdate(opaqueData) {
    document.getElementById("dataDescriptor").value = opaqueData.dataDescriptor;
    document.getElementById("dataValue").value = opaqueData.dataValue;

    // If using your own form to collect the sensitive data from the customer,
    // blank out the fields before submitting them to your server.
    document.getElementById("cardNumber").value = "";
    document.getElementById("expMonth").value = "";
    document.getElementById("expYear").value = "";
    document.getElementById("cardCode").value = "";
    document.getElementById("accountNumber").value = "";
    document.getElementById("routingNumber").value = "";
    document.getElementById("nameOnAccount").value = "";
    document.getElementById("accountType").value = "";

    document.getElementById("paymentForm").submit();
}
</script>

</body>
</html>

PaymentProcess.aspx

Imports System
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports AuthorizeNet.Api.Controllers
Imports AuthorizeNet.Api.Contracts.V1
Imports AuthorizeNet.Api.Controllers.Bases

Public Class PaymentProcess
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'EMPTY!!!
        Dim infoValue = Request.Form("dataValue")
        Dim infoDescriptor = Request.Form("dataDescriptor")

        Run()
    End Sub

    Private Sub Run()
        ' Public Shared Function Run(ByVal ApiLoginID As String, ByVal ApiTransactionKey As String, ByVal amount As Decimal) As ANetApiResponse
        Console.WriteLine("Create an Accept Payment Transaction Sample")
        ApiOperationBase(Of ANetApiRequest, ANetApiResponse).RunEnvironment = AuthorizeNet.Environment.SANDBOX
        ApiOperationBase(Of ANetApiRequest, ANetApiResponse).MerchantAuthentication = New merchantAuthenticationType() With {
                .name = ConfigurationManager.AppSettings("AUTHORIZE_NET_API_LOGIN"),
                .ItemElementName = ItemChoiceType.transactionKey,
                .Item = ConfigurationManager.AppSettings("AUTHORIZE_NET_TRANSACTION_KEY")
            }
        Dim opaqueData = New opaqueDataType With {
                .dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT",
                .dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9"
            }
        Dim billingAddress = New customerAddressType With {
            .firstName = "John",
            .lastName = "Doe",
            .address = "123 My St",
            .city = "OurTown",
            .zip = "98004"
        }
        Dim paymentType = New paymentType With {
            .Item = opaqueData
        }
        Dim lineItems = New lineItemType(1) {}
        lineItems(0) = New lineItemType With {
            .itemId = "1",
            .name = "t-shirt",
            .quantity = 2,
            .unitPrice = New Decimal(15.0)
        }
        lineItems(1) = New lineItemType With {
            .itemId = "2",
            .name = "snowboard",
            .quantity = 1,
            .unitPrice = New Decimal(450.0)
        }
        Dim transactionRequest = New transactionRequestType With {
            .transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
            .amount = "5.00",
            .payment = paymentType,
            .billTo = billingAddress,
            .lineItems = lineItems
        }
        Dim request = New createTransactionRequest With {
            .transactionRequest = transactionRequest
        }
        Dim controller = New createTransactionController(request)
        controller.Execute()
        Dim response = controller.GetApiResponse()

        If response IsNot Nothing Then

            If response.messages.resultCode = messageTypeEnum.Ok Then

                If response.transactionResponse.messages IsNot Nothing Then
                    Console.WriteLine("Successfully created transaction with Transaction ID: " & response.transactionResponse.transId)
                    Console.WriteLine("Response Code: " & response.transactionResponse.responseCode)
                    Console.WriteLine("Message Code: " & response.transactionResponse.messages(0).code)
                    Console.WriteLine("Description: " & response.transactionResponse.messages(0).description)
                    Console.WriteLine("Success, Auth Code : " & response.transactionResponse.authCode)
                Else
                    Console.WriteLine("Failed Transaction.")

                    If response.transactionResponse.errors IsNot Nothing Then
                        Console.WriteLine("Error Code: " & response.transactionResponse.errors(0).errorCode)
                        Console.WriteLine("Error message: " & response.transactionResponse.errors(0).errorText)
                    End If
                End If
            Else
                Console.WriteLine("Failed Transaction.")

                If response.transactionResponse IsNot Nothing AndAlso response.transactionResponse.errors IsNot Nothing Then
                    Console.WriteLine("Error Code: " & response.transactionResponse.errors(0).errorCode)
                    Console.WriteLine("Error message: " & response.transactionResponse.errors(0).errorText)
                Else
                    Console.WriteLine("Error Code: " & response.messages.message(0).code)
                    Console.WriteLine("Error message: " & response.messages.message(0).text)
                End If
            End If
        Else
            Console.WriteLine("Null Response.")
        End If
    End Sub
    '   Return response
    'End Function
End Class

Is there a way to reduce expected conv2d_Conv2D1_input from 4 dimensions to 3?

Problem:

  • a ValueError is saying that conv2d_Conv2D1_input is expecting to have 4 dimension(s), but got array with shape [475,475,3]

However:

  • The inputShape is set to [475,475,3]
  • when logged, tensors have the shape [475,475,3]

Error: ValueError: Error when checking : expected conv2d_Conv2D1_input to have 4 dimension(s), but got array with shape [475,475,3]

Tensor:

Tensor {
  kept: false,
  isDisposedInternal: false,
  shape: [ 475, 475, 3 ],
  dtype: 'int32',
  size: 676875,
  strides: [ 1425, 3 ],
  dataId: {},
  id: 8,
  rankType: '3',
  scopeId: 4
}

Complete Code:

var tf = require('@tensorflow/tfjs');
var tfnode = require('@tensorflow/tfjs-node');
var fs = require(`fs`)

const main = async () => {
  const loadImage = async (file) => {
    const imageBuffer = await fs.readFileSync(file)
    const tensorFeature = await tfnode.node.decodeImage(imageBuffer, 3)
    return tensorFeature;
  }

  const tensorFeature = await loadImage(`./1.png`)
  const tensorFeature2 = await loadImage(`./4.png`)
  const tensorFeature3 = await loadImage(`./7.png`)

  console.log(tensorFeature)
  console.log(tensorFeature2)
  console.log(tensorFeature3)

  tensorFeatures = [tensorFeature, tensorFeature2, tensorFeature3]

  labelArray = [0, 1, 2]
  tensorLabels = tf.oneHot(tf.tensor1d(labelArray, 'int32'), 3);

  const model = tf.sequential();
  model.add(tf.layers.conv2d({
    inputShape: [475, 475, 3],
    filters: 32,
    kernelSize: 3,
    activation: 'relu',
  }));
  model.add(tf.layers.flatten());
  model.add(tf.layers.dense({units: 3, activation: 'softmax'}));

  model.compile({
    optimizer: 'sgd',
    loss: 'categoricalCrossentropy',
    metrics: ['accuracy']
  });

  model.summary()

  model.fit(tf.stack(tensorFeatures), tensorLabels)

  const im = await loadImage(`./2.png`)
  model.predict(im)
}
main()