How to get input from form using PHP/Jquery live? - javascript

I have a simple HTML form that includes an input field and a submit button.
How can I use JQuery to get the text from the input field live and then send that data to a PHP file that evaluates the data?
Form:
<form action='file_that_will_process_data.php' method='POST'>
<input id='text' type='text' name='txt'>
<button type='submit'>Submit</button>
</form>
Edit: here's what I want it to look like
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>';
echo "<script>$(function() {
$('button').on('click', function() {
var txt = $('#txt').val();
sendTextTo_file_that_will_process_data_AndReturnTheValueThat_file_that_will_process_dataReturns(txt)
})</script>";

Your current code doesn't need jquery to get the text from the input field in PHP.
When the user clicks on the Submit button, you can retrieve the text from the input with this code that you've to put in the file_that_will_process_data.php file
<?php
if (isset($_POST['txt'])) {
var_dump($_POST['txt']); // $_POST['txt'] contains the text from the input field
// TODO: make your treatment here...
}
But if what you're looking for is to allow users to make something like a live search, you don't need the submit anymore. Then you can do something like this using jquery:
$(function() {
$('input[name="txt"').on('keyup', function() {
const $form = $(this).closest('form');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: {
txt: $(this).val()
},
success: function (data) {
// data contains the result of your treatment in the file_that_will_process_data.php file. Do whatever you want with it here
}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action='file_that_will_process_data.php' method='POST'>
<input type='text' name='txt'>
<button type='submit'>Submit</button>
</form>

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

OnClick button Get from database and display on a input field live

I am trying to input some text on a input field and on click the button it should display data from mysql on another input field name autofiller.
$(function () {
$('#button').on('click', function () {
var text = $('#fromInput');
$.ajax({
url:"serv.php",
method: "GET",
data: {
"id": text
},
success: function(data) {
var name=JSON.parse(data);
document.getElementsByClassName("autofiller").value=name.name;
}
});
});
});
HTML form
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="button" value="button" id="button">
This is my back-end php script-->
<?php
$link=mysqli_connect("localhost","root","","employee");
$data=$_GET["id"];
$result = mysqli_query($link,"SELECT * FROM user where userid='$data'");
header('Content-type:application/json');
exit(json_encode($result));
?>
I hope this would help you to solve
$(function () {
$('#button').on('click', function () {
var text = $('#fromInput');
$.ajax({
url:"serv.php",
method: "GET",
data: {
"id": text
},
success: function(data) {
var name=JSON.parse(data);
$(".autofiller").val(name.name);// Try this
}
});
});
});
document.getElementsByClassName("autofiller")[0].value=name.name;
You should use getElementById() to get the single element reference because getElementByClassName() will return an array of reference of elements with that class name.
try this
document.getElementById("autofiller").value=name.name;
where autofiller should be the "id" instead of class
in HTML
<input type="text" id="autofiller"/>
Maybe you should try this:
var text = $('#fromInput').val();
Update
There are many bugs in your code, as below:
In Backend
$result = mysqli_query($link,"SELECT * FROM user where userid='$data'");
This does not return the data as you expect, you have to use mysql_fetch_array to fetch the data from the result which can be something like this:
$sql = "SELECT * FROM users where id='$data'";
$result = mysqli_fetch_array(mysqli_query($link,$sql));
In frontend
You don't need to parse the data to JSON as you are already sending the response with a JSON data:
var name=JSON.parse(data);
Instead you can do something like this:
document.getElementById("autofiller").value=data.name;
Notice here, Using id instead of class is a better approach, as you would want to set the value to a specific input, not a group of inputs, so you might have to add an id to autofiller like this
<input type="text" class="autofiller" id="autofiller"/>

PHP validation for Javascript

I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Is there a way in JavaScript to retrieve the form data that *would* be sent with a form without submitting it?

If I have an HTML form, let’s say...
<form id='myform'>
<input type='hidden' name='x' value='y'>
<input type='text' name='something' value='Type something in here.'>
<input type='submit' value='Submit'>
</form>
... and then I use jQuery to respond to the form submission event, e.g.
$('#myform').submit(function() {
...
return false;
});
Now suppose I want to submit the form as an AJAX call instead of actually submitting it the “traditional” way (as a new page). Is there an easy way to get a JS object containing the data that would be sent, which I can pass into $.post()? So in the above example it would look something like...
{
x: 'y',
something: 'Type something in here.'
}
or do I have to bake my own?
See the serialize() method.
$('#myform').submit(function() {
jQuery.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function () {
//
}
});
return false;
});
As you're already using jQuery, use jQuery.serialize().
$('#myform').submit(function() {
var $form = $(this);
var data = $form.serialize();
// ...
});

Categories

Resources