1584949749
HTML forms can send an HTTP request declaratively while submitting forms and awaiting response. However, you have to wait for a full page reload before getting your results, which most times is not the best user experience.
Forms can also prepare an HTTP request to send via JavaScript, which makes for a better user experience. This article explores ways to do that using three different frameworks: Vue, React, and Hyperapp.
Vue is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. To learn more about Vue, you can visit the official homepage here.
First, let’s define our HTML structure. Create a file named vue.html
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div class="container" id="app">
<div class="row">
<div class="col-md-4">
<div class="panel">
<h4 class="heading"><strong>Quick </strong> Contact <span></span></h4>
<div class="form">
<input type="text" required="" placeholder="Please input your Name" value="" v-model="form.name" class="form-control">
<input type="text" required="" placeholder="Please input your mobile No" value="" v-model="form.mob" class="form-control">
<input type="text" required="" placeholder="Please input your Email" value="" v-model="form.email" class="form-control">
<textarea placeholder="Your Message" v-model="form.mess" class="form-control"></textarea>
<input type="submit" value="submit" name="submit" class="btn btn-primary" @click="submitForm()">
</div>
</div>
</div>
</div>
</div>
The code snippet above is a basic HTML declaration in which we:
POST
requests.You would notice that in each of the 5 elements, the first 4 declares a v-model
attribute to some certain properties of form
.
V-model
is a way of binding inputs to Vue, such that Vue has the values of these input as they change.
Form
does not refer to the HTML form, but refers to an object which we have used for the binding in our Vue component.
Last, if you look at the button element, you would notice a little directive called @click
. This directive binds the click event of the button to Vue, instructing Vue on what to do when the button is clicked.
Implementing Vue into the form
In the previous section, we have explained the reason you have seen attributes like v-model
in your HTML structure and the @click
directive. Here, we show what the Vue part that handles the rest looks like.
Open a script file in your HTML document and paste in:
<script>
var app = new Vue({
el: '#app',
data: {
form: {
name: '',
mob: '',
email: '',
mess: ''
}
},
methods: {
submitForm: function(){
axios.post('https://httpbin.org/anything', this.form)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
})
</script>
In the code block above, we defined an Object called form, which comprises our data. Next, we defined a method called submitForm
which does an Ajax request to [https://httpbin.org/anything](https://httpbin.org/anything)
. We use httpbin because their service allows us to perform free HTTP methods. The /anything
route would return the exact data which we had sent to it.
See how easy it is to submit a form using JavaScript? all you need do is change the URL to that of your server.
Why is my Form is not submitting? Often we note that after writing what looks like the right piece of code, the form does not submit. How do we troubleshoot this? Let me highlight common reasons your Vue form might not submit.
app
passed into the Vue object with the el
key does not exist, and the app is not bound to VueReact is a JavaScript library for building user interfaces developed and maintained by Facebook. React makes it painless to create interactive UIs. Design simple views for each state in your application and React will efficiently update and render just the right components when your data changes.
First, let’s define our HTML structure. Create a file named react.html
and add:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div class="container" id="app">
</div>
The code snippet above is a basic HTML declaration in which we:
POST
requestsapp
, which would be our root componentImplementing React into the mix
We have a basic setup with the required libraries available and a root element which react would be attached to. Let’s go ahead with the react implementation. Open a script tag and input:
class Root extends React.Component {
constructor(props) {
super(props);
this.state = {
form: {
name: "",
mob: "",
email: "",
mess: ""
}
};
this._onInputChange = this._onInputChange.bind(this);
this._onSubmit = this._onSubmit.bind(this);
}
_onInputChange(name, e) {
var form = this.state.form;
form[name] = e.target.value;
this.setState(form);
}
_onSubmit() {
axios
.post("https://httpbin.org/anything", this.state.form)
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
}
render() {
return (
<div className="row">
<div className="col-md-4">
<div className="panel">
<h4 className="heading">
<strong>Quick </strong> Contact <span />
</h4>
<div className="form">
<input
type="text"
required=""
placeholder="Please input your Name"
className="form-control"
onChange={e => this._onInputChange("name", e)}
/>
<input
type="text"
required=""
placeholder="Please input your mobile No"
className="form-control"
onChange={e => this._onInputChange("mob", e)}
/>
<input
type="text"
required=""
placeholder="Please input your Email"
onChange={e => this._onInputChange("email", e)}
className="form-control"
/>
<textarea
placeholder="Your Message"
className="form-control"
onChange={e => this._onInputChange("mess", e)}
/>
<input
type="submit"
value="submit"
name="submit"
className="btn btn-primary"
onClick={this._onSubmit}
/>
</div>
</div>
</div>
</div>
);
}
}
ReactDOM.render(<Root />, document.getElementById("app"));
Let’s take a review of what we have above. Here, in our constructor, we declared an initial state that comprises our form object, we then moved ahead to bind two functions which we will set the state as the input changes and submit the form.
In the _onInputChange
function, we receive two arguments, which are:
We use this two parameters to set the state of the exact input that was changed.
In the _onSubmit
function, we fire a post request to the [https://httpbin.org/anything](https://httpbin.org/anything)
endpoint, which returns the exact parameters sent. Here, which is what we use as our server.
Let us take a critical look at the render
function, where the elements are being rendered.
Here, we defined 5 elements, which comprise 3 inputs, a text area whose change events are bound to the _onInputChange
function, and a button element, whose click event is bound to the _onSubmit
method.
Finally, we attached the app to an element on our HTML markup.
Why is my Form not displaying? I bet you have been getting a blank screen and cannot understand where the error is coming from.
Taking a quick look at the render function, you would notice we have jsx
syntax in there. Now, here is the catch. Unless you are using babel to compile your app, jsx
would most likely fail. This is because jsx
isn’t regular javascript syntax, and here, we are using the browser build of React.
So how do we solve this? It’s a simple fix.
Any JSX block can be converted into a call to React.createElement
with three arguments:
div
, span
, ul
, e.t.c.class
, style
, required
, e.t.c.React.createElement
to get more elements.Replace the render function with this:
render() {
return (
React.createElement("div", { className: 'row' }, [
React.createElement("div", { className: 'col-md-4' }, [
React.createElement("div", { className: 'panel' }, [
React.createElement("h4", {}, 'Quick Contact'),
React.createElement("div", { className: 'form' }, [
React.createElement("input", {
type: 'text',
placeholder: "Please input your Name",
className: "form-control",
name: 'name',
onChange: (e) => this._onInputChange('name', e)
}),
React.createElement("input", {
type: 'text',
placeholder: "Please input your Mobile number",
className: "form-control",
name: 'mob',
onChange: (e) => this._onInputChange('mob', e)
}),
React.createElement("input", {
type: 'text',
placeholder: "Please input your Email",
className: "form-control",
name: 'email',
onChange: (e) => this._onInputChange('email', e)
}),
React.createElement("textarea", {
placeholder: "Please your message",
className: "form-control",
name: 'mess',
onChange: (e) => this._onInputChange('mess', e)
}),
React.createElement("button", {
type: 'button',
className: "btn btn-primary",
onClick: () => this._onSubmit()
}, "submit"),
])
])
]),
])
);
}
Also, update the ReactDom.render
call to this:
ReactDOM.render(
React.createElement(Root, null),
document.getElementById('app')
);
Why is my form not submitting? Even after performing each step we think is necessary and cross-checking our code, it is possible your form does not still submit, how do we trouble-shoot this?
axios
library or the library you use for post requests is referencedHyperApp is a JavaScript micro-framework for building web applications. This framework has aggressively minimized the concepts you need to understand to be productive while remaining on par with what other frameworks can do.
HyperApp holds firm on the functional programming front when managing your state, but takes a pragmatic approach to allowing for side effects, asynchronous actions, and DOM manipulations.
First, let’s define our HTML structure. Create a file named hyper.html
and add:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://unpkg.com/hyperapp"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div class="container" id="app">
</div>
The code snippet above is a basic HTML declaration in which we:
POST
requestsapp
, which would be our root componentIntroducing Hyperapp to the app We have a basic setup with the required libraries available and a root element which HyperApp would be attached to. Let’s go ahead with the react implementation. Open a script tag and input:
const h = hyperapp.h;
const app = hyperapp.app;
const state = {
form: {
name: '',
mob: '',
email: '',
mess: '',
}
}
const actions = {
onInputChange: (event) => state => {
state.form[event.target.name] = event.target.value;
return state;
},
submitForm: () => {
console.log(state.form)
axios.post('https://httpbin.org/anything', state.form)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
const view = (state, actions) => (
h("div", {class: 'row'}, [
h("div", {class: 'col-md-4'}, [
h("div", {class: 'panel'}, [
h("h4", {}, 'Quick Contact'),
h("div", {class: 'form'}, [
h("input", {type: 'text', placeholder: "Please input your Name", class:"form-control",
name: 'name',
oninput: (e)=>actions.onInputChange(e)}),
h("input", {type: 'text', placeholder: "Please input your Mobile number", class:"form-control",
name: 'mob',
oninput: (e)=>actions.onInputChange(e)}),
h("input", {type: 'text', placeholder: "Please input your Email", class:"form-control",
name: 'email',
oninput: (e)=>actions.onInputChange(e)}),
h("textarea", {placeholder: "Please your message", class:"form-control",
name: 'mess',
oninput: (e)=>actions.onInputChange( e)}),
h("button", {type: 'button', class:"btn btn-primary",
onclick: ()=>actions.submitForm()}, "submit"),
])
])
]),
])
)
app(state, actions, view, document.getElementById('app'))
Let’s take a review of what we have above. Here, we declared an initial state that comprises our form object, we then moved ahead to declare two actions which we will set the state as the input changes and submit the form.
In the onInputChange
function, we receive one argument, which is:
We use this two parameters to set the state of the exact input that was changed.
In the _onSubmit
function, we fire a post request to the [https://httpbin.org/anything](https://httpbin.org/anything)
endpoint, which returns the exact parameters sent. Here, which is what we use as our server.
Here, we must have seen the similarities between React and Hyperapp. For our purposes, I’ll describe Hyperapp as a lightweight alternative to React.
In the render function of the code above, we would notice the exact similarities to React. In fact, the only differences you would notice is the use of class
instead of React’s className
and onInput
in place of onChange
.
For the same reason we did not use
_jsx_
in the React form, is the same reason we have not used_jsx_
here. If you use the_npm_
package and prefer to use_jsx_
, please feel free.
In this tutorial, we have seen how easy it is to submit forms using 3 different JavaScript frameworks. We have also seen how to solve common issues when our forms are not displaying or not submitting as intended. Do you have any observations about this tutorials or views you want to share? Let us know in the comments.
#html #javascript #vue #react
1667425440
Perl script converts PDF files to Gerber format
Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.
The general workflow is as follows:
Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).
See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.
#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;
use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)
##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file
use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call
#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.010, -.001, #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.065 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#line join/cap styles:
use constant
{
CAP_NONE => 0, #butt (none); line is exact length
CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
#number of elements in each shape type:
use constant
{
RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
rect => RECT_SHAPELEN,
line => LINE_SHAPELEN,
curve => CURVE_SHAPELEN,
circle => CIRCLE_SHAPELEN,
);
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes.
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load
#############################################################################################
#junk/experiment:
#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html
#my $caller = "pdf2gerb::";
#sub cfg
#{
# my $proto = shift;
# my $class = ref($proto) || $proto;
# my $settings =
# {
# $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
# };
# bless($settings, $class);
# return $settings;
#}
#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;
#print STDERR "read cfg file\n";
#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names
#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }
Author: swannman
Source Code: https://github.com/swannman/pdf2gerb
License: GPL-3.0 license
1615040237
PHP jquery ajax POST request with MySQL. In this tutorial, you will learn how to create and submit a simple form in PHP using jQuery ajax post request. And how to submit a form data into MySQL database without the whole page refresh or reload. And also you will learn how to show an error message to the user if the user does not fill any form field.
And this tutorial also guide on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.
Just follow the few below steps and easily create and submit ajax form in PHP and MySQL with client-side validation.
https://www.tutsmake.com/php-jquery-ajax-post-tutorial-example/
#jquery ajax serialize form data example #submit form using ajax in php example #save form data using ajax in php #how to insert form data using ajax in php #php jquery ajax form submit example #jquery ajax and jquery post form submit example with php
1594963828
List of some useful JavaScript Frameworks and libraries for website, web apps, and mobile apps development, that developers should know about to make selection easier.
This article will help you understand the various types of JavaScript Framework available in the market. When it comes to choosing the best platform for you, it’s not only the number of features you need to consider but also its functionality. The ease with which it fits within your project is also an essential factor. The next step is to choose the framework that best fits your company requirements or you can select the best from the list of top web development companies to develop your product based on your requirements.
#javascript frameworks for web applications #web applications development companies #progressive javascript framework #javascript frameworks #javascript #frameworks
1671521622
00:00 Intro
00:05 Preview
00:40 HTML & CSS
10:40 Step 1: Events for touch and mouse
11:00 Step 2: Detect touch device
15:00 Step 3: Update Rating
17:35 Step 3: Display Message
We start with an HTML file. First, copy the code below and paste it into your HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Star Rating</title>
<!-- Font Awesome Icons -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
/>
<!-- Google Fonts -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="bg"></div>
<div class="wrapper">
<p id="message">Rate Your Experience</p>
<div class="container">
<div class="star-container inactive">
<i class="fa-regular fa-star"></i>
<span class="number">1</span>
</div>
<div class="star-container inactive">
<i class="fa-regular fa-star"></i>
<span class="number">2</span>
</div>
<div class="star-container inactive">
<i class="fa-regular fa-star"></i>
<span class="number">3</span>
</div>
<div class="star-container inactive">
<i class="fa-regular fa-star"></i>
<span class="number">4</span>
</div>
<div class="star-container inactive">
<i class="fa-regular fa-star"></i>
<span class="number">5</span>
</div>
</div>
<button id="submit" disabled>Submit</button>
<div id="submit-section" class="hide">
<p id="submit-message">Thanks for your feedback</p>
</div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
Please style this app using CSS. For this copy provided to your below and paste it into your stylesheet.
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
.bg {
position: absolute;
height: 50vh;
width: 100vw;
background: linear-gradient(#fe3b5a, #fd7914);
}
.wrapper {
font-size: 1.2ee;
width: 25em;
position: absolute;
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
background-color: #ffffff;
border-radius: 0.5em;
padding: 4em 2em;
box-shadow: 0 1.25em 2.5em rgba(18, 0, 76, 0.15);
}
.container {
width: 100%;
display: flex;
justify-content: space-around;
}
.fa-star {
font-size: 1.5em;
color: #ffd700;
}
.number {
display: block;
text-align: center;
}
#submit {
display: block;
position: relative;
background: linear-gradient(#fe3b5a, #fd7914);
border: none;
padding: 0.8em 2em;
color: #ffffff;
font-size: 1.2em;
border-radius: 2em;
margin: 1em auto 0 auto;
cursor: pointer;
}
#submit:disabled {
cursor: not-allowed;
}
#message {
text-align: center;
margin-bottom: 2em;
}
#submit-section {
position: absolute;
height: 100%;
width: 100%;
background-color: #ffffff;
top: 0;
left: 0;
place-items: center;
border-radius: 0.5em;
}
.hide {
display: none;
}
.show {
display: grid;
}
Finally, we implement the logic using JavaScript. Copy the code below and paste it into your script file.
let starContainer = document.querySelectorAll(".star-container");
const submitButton = document.querySelector("#submit");
const message = document.querySelector("#message");
const submitSection = document.querySelector("#submit-section");
//Events For touch and mouse
let events = {
mouse: {
over: "click",
},
touch: {
over: "touchstart",
},
};
let deviceType = "";
//Detect touch device
const isTouchDevice = () => {
try {
//We try to create TouchEvent (it would fail for desktops and throw error)
document.createEvent("TouchEvent");
deviceType = "touch";
return true;
} catch (e) {
deviceType = "mouse";
return false;
}
};
isTouchDevice();
starContainer.forEach((element, index) => {
element.addEventListener(events[deviceType].over, () => {
submitButton.disabled = false;
if (element.classList.contains("inactive")) {
//Fill Star
ratingUpdate(0, index, true);
} else {
//Regular stars (remove color)
ratingUpdate(index, starContainer.length - 1, false);
}
});
});
const ratingUpdate = (start, end, active) => {
for (let i = start; i <= end; i++) {
if (active) {
starContainer[i].classList.add("active");
starContainer[i].classList.remove("inactive");
starContainer[i].firstElementChild.className = "fa-star fa-solid";
} else {
starContainer[i].classList.remove("active");
starContainer[i].classList.add("inactive");
starContainer[i].firstElementChild.className = "fa-star fa-regular";
}
}
//Message
let activeElements = document.getElementsByClassName("active");
if (activeElements.length > 0) {
switch (activeElements.length) {
case 1:
message.innerText = "Terrible";
break;
case 2:
message.innerText = "Bad";
break;
case 3:
message.innerText = "Satisfied";
break;
case 4:
message.innerText = "Good";
break;
case 5:
message.innerText = "Excellent";
break;
}
} else {
message.innerText = "";
}
};
submitButton.addEventListener("click", () => {
submitSection.classList.remove("hide");
submitSection.classList.add("show");
submitButton.disabled = true;
});
window.onload = () => {
submitButton.disabled = true;
submitSection.classList.add("hide");
};
#html #css #javascript
1606912089
#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html