{"id":30154,"date":"2023-01-13T13:59:01","date_gmt":"2023-01-13T08:29:01","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/"},"modified":"2023-01-13T13:59:01","modified_gmt":"2023-01-13T08:29:01","slug":"solved-change-php-code-to-js","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/","title":{"rendered":"[Solved] Change PHP code to JS"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-35206433\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"35206433\" data-parentid=\"35200225\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>I echo the comment above.  I believe StackOverflow is <strong>not<\/strong> a code writing service unless something changed very recently.<\/p>\n<p>However, let&#8217;s look at the code you posted. <\/p>\n<p>I think it would help to refactor this code into a more logical sense before attempting this in Javascript.  That should make it easier to transpose. Every time there is repetition of similar code (e.g. <code>$ak1 = $_POST['ak1']; $ak2 = $_POST['ak2']; ...<\/code>) I would think there must be a more efficient way of getting your programming language to do the hard work. Computers are good at repetitive tasks after all.<\/p>\n<p>I assume you have labelled all of the input fields in your form individually but you can actually pass them to <code>$_POST<\/code> as arrays if you give them all the same name and append square brackets like so:<\/p>\n<pre><code>&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n&lt;input type=\"text\" name=\"ak[]\"&gt;\n\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n&lt;input type=\"text\" name=\"akcs[]\"&gt;\n<\/code><\/pre>\n<p>I don&#8217;t know why you have two different sets of names for the input fields &#8211; it might help to merge these into one unless you have a good reason not too.<\/p>\n<p>Now you have the HTML in a more maintainable format, you can seriously cut down on the amount of variable assignment that is needed in PHP:<\/p>\n<pre><code>if(isset($_POST['ak'], $_POST['akcs'])){\n  extract($_POST);\n  $all_fields = array_merge($ak, $akcs);\n  $total = array_sum($all_fields);\n  if($total){\n    echo \"&lt;p&gt;&lt;i&gt;Sent at:&lt;\/i&gt;\" . date('H:i, jS F');\n    $ak_values   = [140, 285, 160, 120, 180, 210, 250, 120, 300, 200, 110, 110, 130, 200];\n    $value = array_sum(array_map(function($a, $b){\n      return $a * $b;\n  }, $all_fields, $ak_values));\n    echo '&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;strong&gt;Total: &lt;\/strong&gt;'.$total;\n    echo '&lt;hr width=\"20%\"&gt;';\n    echo '&lt;strong&gt;Total to pay: &lt;\/strong&gt;&lt;font face color=\"green\"&gt;'.$value.'&lt;\/font&gt;&lt;strong&gt; $&lt;\/strong&gt;';\n  } else {\n  echo '&lt;br&gt;&lt;br&gt;&lt;strong&gt;You did not make any order&lt;\/strong&gt;';\n  }\n}\n<\/code><\/pre>\n<p>Making use of PHP&#8217;s features such as <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/function.extract.php\">extract<\/a>, <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/function.array-sum.php\">array_sum<\/a>, <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/function.array-map.php\">array_map<\/a> and <a rel=\"nofollow noopener\" target=\"_blank\" href=\"http:\/\/php.net\/manual\/en\/function.array-merge.php\">array_merge<\/a> (which is necessary to combine the two sets of input fields in your form &#8211; see? You know it makes sense to only have the one type \ud83d\ude09 ) makes it much less repetitive and also more maintainable should you wish to amend the form at a later date.<\/p>\n<p>So how does this convert to JavaScript? <\/p>\n<p>I&#8217;m glad you asked.<\/p>\n<pre><code>var ak_values   = [140, 285, 160, 120, 180, 210, 250, 120, 300, 200, 110, 110, 130, 200];\nvar order_date = document.getElementById('order_date');\nvar message = document.getElementById('message');\nfunction sum(a,b){ return a+b }\ndocument.getElementById('sum').addEventListener('click', function(){\n  var ak = [];\n  Array.prototype.slice.call(document.querySelectorAll('[name=\"ak[]\"], [name=\"akcs[]\"]')).forEach(function(i){\n    ak.push( i.value === \"\" ? 0 : parseInt(i.value));\n});\n  var total = ak.reduce(sum);\n  if (total){\n    order_date.innerHTML =  \"&lt;i&gt;Sent at:&lt;\/i&gt;\" + new Date();\n    ak = ak.map(function(item, index){\n      return item * ak_values[index];\n    });\n    var value = ak.reduce(function(sum, item){\n      return sum + item;\n    });\n    message.innerHTML = '&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;strong&gt;Total: &lt;\/strong&gt;' + total + '&lt;hr width=\"20%\"&gt;&lt;strong&gt;Total to pay: &lt;\/strong&gt;&lt;font face color=\"green\"&gt;' + value  + '&lt;\/font&gt;&lt;strong&gt; $&lt;\/strong&gt;';\n  } else{\n    message.innerHTML = '&lt;br&gt;&lt;br&gt;&lt;strong&gt;You did not make any order&lt;\/strong&gt;';\n  }\n});\n<\/code><\/pre>\n<p>Javascript has comparable functions for <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/map\">map<\/a> and <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Global_Objects\/Array\/Reduce\">reduce<\/a> to get the array sum etc. and you can see how taking the approach in PHP to use such standard functions makes it easier to translate in to another language. <\/p>\n<p>A few things to consider:<\/p>\n<ul>\n<li>Do you want these sorts of calculations to occur in the browser? The prices presumably would be stored in a database which would need to be retrieved <\/li>\n<li>The user can manipulate values (like the ones stored in the <code>var ak_values<\/code> array) in Javascript <\/li>\n<li>Using AJAX might be better?<\/li>\n<li>Inline styles?<\/li>\n<\/ul>\n<p>Here is a (slightly ugly) but working JSFiddle <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/jsfiddle.net\/codebubb\/3tht5y8v\/1\/\">https:\/\/jsfiddle.net\/codebubb\/3tht5y8v\/1\/<\/a><\/p>\n<p>I hope you have found this post useful.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">2<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Change PHP code to JS <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] I echo the comment above. I believe StackOverflow is not a code writing service unless something changed very recently. However, let&#8217;s look at the code you posted. I think it would help to refactor this code into a more logical sense before attempting this in Javascript. That should make it easier to transpose. Every &#8230; <a title=\"[Solved] Change PHP code to JS\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\" aria-label=\"More on [Solved] Change PHP code to JS\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[333,339,994,1097],"class_list":["post-30154","post","type-post","status-publish","format-standard","hentry","category-solved","tag-javascript","tag-php","tag-post","tag-sum"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Change PHP code to JS - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Change PHP code to JS - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] I echo the comment above. I believe StackOverflow is not a code writing service unless something changed very recently. However, let&#8217;s look at the code you posted. I think it would help to refactor this code into a more logical sense before attempting this in Javascript. That should make it easier to transpose. Every ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2023-01-13T08:29:01+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Change PHP code to JS\",\"datePublished\":\"2023-01-13T08:29:01+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\"},\"wordCount\":391,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"javascript\",\"php\",\"post\",\"sum\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\",\"name\":\"[Solved] Change PHP code to JS - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2023-01-13T08:29:01+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Change PHP code to JS\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Change PHP code to JS - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Change PHP code to JS - JassWeb","og_description":"[ad_1] I echo the comment above. I believe StackOverflow is not a code writing service unless something changed very recently. However, let&#8217;s look at the code you posted. I think it would help to refactor this code into a more logical sense before attempting this in Javascript. That should make it easier to transpose. Every ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/","og_site_name":"JassWeb","article_published_time":"2023-01-13T08:29:01+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Change PHP code to JS","datePublished":"2023-01-13T08:29:01+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/"},"wordCount":391,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["javascript","php","post","sum"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/","url":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/","name":"[Solved] Change PHP code to JS - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2023-01-13T08:29:01+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-change-php-code-to-js\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Change PHP code to JS"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/30154","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=30154"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/30154\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=30154"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=30154"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=30154"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}