Get posted data using jquery - javascript

I want to get posted data using jquery. I have implemen
Html Form
<form id="login_form" action="userPref.php" method="post" >
<div hidden id="error" style="color:red; text-align:center;" > <p> user not found </p> </div>
<div class="form-group">
<label for="usrname"><span class="glyphicon glyphicon-user "></span> User Id</label>
<input type="text" value="" class="form-control" required="required" id="usrname" name="usrname" placeholder="Enter User Id" >
</div>
<button type="submit" id="login" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Login</button>
</form>
In userPref.php I am using php to get data but I actually want to use jquery
var userid = <?php echo $_POST["usrname"] ?>;
I have also tried to access the form data using jquery but I was not able to access the data. Please help me.

POST data is data that is handled server side. And Javascript/jQuery is on client side. So there is no way you can read a post data using JavaScript/jQuery.
But good way is
var post_data= <?php echo json_encode( !empty($_POST) $_POST : array());?>;
now you can access $_POST['username'];
alert(post_data.username);
so you can access all posted data in this way.

check this :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div id="results"></div>
<form action="" method="post">
<input typte="text" name="uName" /> <input typte="password"
name="passKey" /> <input type="submit" />
</form>
<script type="text/javascript">
$('form').submit(function(e){
if(this.uName.value != ''){
alert(this.uName.value);
}
if(this.passKey.value != ''){
alert(this.passKey.value);
}
});
</script>
</body>
</html>

On server side you need something like this:
<input type="text" value="" class="form-control" required="required" id="usrname" name="usrname" placeholder="Enter User Id"<?php echo isset($_POST["usrname"]) ? ' value="'.$_POST["usrname"].'"' : ''; ?> >
and then you can use it with jquery, like this:
$("#usrname").val()

$("form").serializeArray();
See Documentation: http://api.jquery.com/serializeArray/

Related

How to move to the page entered in the form

let me start by saying that I'm a freshman. I would like to create a form with a button that, when pressed, will generate a page written in an inputa. How to do it? example:
<form action="" method="post">
<!-- a hidden input -->
<input type="hidden" name="a_hidden_input"/>
<!-- a text input -->
<input type="text" name="a_text_input"/>
<!-- submit button -->
<input type="submit" value="Submit"/>
</form>
This is the basic example for getting your data and displaying in the page .
<head>
<script>
function generate() {
debugger
var strText = document.getElementById("txtName").value;
var strText1 = document.getElementById("txtEmail").value;
document.getElementById("p1").innerHTML = strText;
document.getElementById("p2").innerHTML = strText1;
window.location.href = "http://mywebsite.com/home.html";
}
</script>
</head>
<body>
<form>
<input type="text" name="Name" id="txtName" placeholder="Name">
<input type="text" name="Email" id="txtEmail" placeholder="Email">
<input type="button" value="Submit" id="btnSubmit" onclick="generate()">
</form>
<div>
<h1>New Page</h1>
<p id="p1"></p>
<p id="p2"></p>
</div>
</body>
If u use any library like react js or framework like angular with backend technologies like php,nodejs, with databases as sql , mongodb or firebase it will be super easy for u .

PHP Form not posting all fields data

I have a form I am trying to submit. For the life of me, I can't figure out why none of the data from the fields is posting. Here is the form.
I've tried to change different input types and the name's but nothing is working.
UPDATE:
I was able to fix the problem. 3rd party script was preventing posting of all data
Your code is confusing. you have id attributes o the submit button in two places. you also have id set to myform at form parameter. Which Id are you using to send the form. In your absence of your javascript and php backend. you can try the code below and see if it helps
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"submit.php",
method:"POST",
data:$(this).serialize(),
dataType:"html",
beforeSend:function(){
alert('am about to submit');
},
success:function(data){
$('#myresult').fadeIn('slow').prepend(data);
}
})
});
});
</script>
// display ajax result in div below...
<div id="myresult"></div>
<form id="myForm" class="form" method="post">
<input type="text" class="form-control center-block" id="fname" placeholder="First Name" name="fname" required>
<input type="text" class="form-control center-block" id="lname" placeholder="Last Name" name="lname" required>
<input type="email" class="form-control center-block" id="email" placeholder="Email Address" name="email" required>
<input type="text" class="form-control center-block" id="location" value="modal" placeholder="location" name="location" hidden>
<input type="button" class="btn-success btn-lg" name="submit" id="submit" value="Submit!"/>
</form>
submit.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$location = $_POST['location'];
//If everything were okay echo success
echo "success. myname is: $fname $lname and my email is: $email";
?>
You have actually two ids in the submit button:
<input type="button"
id="submitFormData"
onclick="SubmitFormData();"
class="btn-success btn-lg"
name="submit"
id="submit"
value="Submit!"
/>
id="submitFormData" AND id="submit"
Also you have a JS function called when onclick event SubmitFormData()
These things are pretty suspicious...

another javascript redirecting

My view :
<div class="container">
<form class="form-signin" method="post" action="">
<h2 class="form-signin-heading">Admin Login</h2>
<input type="text" id="inputUsername" name ="inputUsername"
class="form-control" placeholder="Admin" required autofocus />
<label for="inputPassword" class="sr-only"> Password</label>
<input type="password" id="inputPassword" name="inputPassword"
class="form-control" placeholder="Password" required />
<br/>
<button class="btn btn-lg btn-primary btn-block" name="login"
type="submit">Login</button>
</form>
</div>
My controller :
if (isset($_POST['login'])) {
$username = $_POST['inputUsername'];
$password = $_POST['inputPassword'];
echo "<script>window.location.href = 'collections.php';</script>";
}
When I clicked the button,
it doesnt redirect me to collections.php , what I missed here ?
use php header to redirect the page ,it's easy and better compaire to what you did here.
header('Location: http://www.example.com/');
you redirect from php
<?php
if (isset($_POST['login'])) {
$username = $_POST['inputUsername'];
$password = $_POST['inputPassword'];
header('Location: collections.php'); //<------- php redirect to other page
}
?>
this is what you were trying outputting JS in PHP for redirection be careful with url if you use relative
$redirectURL = "../controller/collection.php";
print("<script>");
print("var t = setTimeout(\"window.location='".$redirectURL."';\", 3000);");
print("</script>");

Populate form with data from another form

I have a page with a small tour, within the tour points are inputs. Also on this page is another form, these forms have similar inputs including first, last name, etc...
If the user inputs their first name into form 1, how can I populate the first name field of form 2?
This is form 1:
<form role="form" id="inviteform3" class="form-inline" action="name.php" method="POST">
<div class="form-group">
<input type="text" class="form-control input-sm" name="name" placeholder="First Name"
id="hello" autocomplete="off" style="margin-top:10px">
</div>
<center>
<span id="start">Let's get started, <span id="result"></span></span>
<button class="btn btn-brand btn-sm next-screen animated bounceInUp"
id="go" style="margin-top:5px; display:none" href="#services" data-animation-delay=".5s">
Let's Go!</button></center>
<button class="btn btn-block btn-brand btn-xs invitebtn3" id="casi" type="submit"
style="margin-top:5px"><i class="fa fa-thumbs-o-up"></i> Submit</button>
</form>
This is form 2:
<form role="form" id="inviteform" class="form-inline"
action="http://omnihustle.net/demo/invitations/invite_request" type="POST"><div
class="form-group">
<input type="text" class="form-control input-sm" id="InputFirstName" placeholder="First
Name">
</div>
<div class="form-group">
<input type="text" class="form-control input-sm" id="InputLastName" placeholder="Last
Name">
</div>
<div class="form-group">
<input type="email" class="form-control input-sm" id="InputEmail" placeholder="Email">
</div>
<button class="btn btn-brand btn-sm invitebtn" type="submit" data-toggle="modal" data-
target=".bs-example-modal-sm"><i class="fa fa-check fa-fw"></i> Invite Me</button></form>
Here is my php file which the form is sent to:
<html>
<body>
<?php session_start(); ?>
<?php
if (isset($_POST['name']) && !empty($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
?>
<?php echo $_POST["name"]; ?>
</body>
</html>
Jquery has not worked since I am unable to enter html into the "value" field of the form, so what is the alternative?
Here is what ive tried;
<script>
$(document).on("ready", function(){
//Form action
$("#inviteform3").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'name.php',
data:$('#inviteform3').serialize(),
success: function(response)
{
$('#inviteform3').find('#result').html(response);
$('.coupontooltip5').find('#result2').html(response);
$('#announcement').find('#result3').html(response);
$('#announcement2').find('#result4').html(response);
$('#progressbutton').find('#result5').html(response);
$('#inviteform').find('#result6').html(response);
}});
});
});
</script>
I have tried inputting "span id="result6" into the "value" tag of the input and the form does not allow the function, just shows the html as the default value of the input..
You can add a 'keyup' handler which copy the content to the second field. Add the following lines into the 'ready' handler.
$('#hello').on('keyup', function() {
$('#InputFirstName').val($(this).val());
});
If you add a 'change' handler instead of this 'keyup' handler, the handler is called only after the the field loses the focus.
By the way, name.php does not work. session_start() must be called before any output is made. Hence:
<?php session_start(); ?>
<html>
<body>

Passing a JavaScript Array To PHP Through JQuery $.post

This piece of code gets all the form variables and sends them via AJAX to the PHP script. But I want the calculated results from the PHP script that is being returned to the javascript via a JSON encoded array to be in the form of "post":{"uname":"someNamefromForm","email":"someEmail","fname":"namefromtheform","lname":"lastnamefromform"
}... The output I'm getting now is "uname=e&email=e&fname=e&lname=euname".. This is the JSON array I want to displayed at the bottom of the page for debugging purposes. Can someone tell me how to format it please
This is my HTML form
<div id="wrapper">
<h2> Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="uname" value="" />
</div>
<div>
<label for="email">Email Address <em>*</em></label>
<input id="email" type="text" name="email" value="" />
</div>
<div>
<label for="fname" class="error">First Name <em>*</em></label>
<input id="fname" type="text" name="fname" value="" size="50" class="error"/>
<p class='note'>All error message go here </p>
</div>
<div>
<label for="lname">Last Name <em>*</em></label>
<input id="lname" type="text" name="lname" value="" size="50" />
</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
<a >Refresh this Page</a>
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
This is my javascript
$("#ajax-form").submit(function(){
var variableToSend = $(this).serialize();
$.post(
'ajaxformval_post.php',
{variable: variableToSend},
function(data){$("#debug").html(data)},
"json"
);
})
This is the php
<?php
$variable = $_POST['variable'];
echo json_encode($variable);
/*$json = array(
'booleanFlag' => TRUE,
'someText' => "AJAX should be renamed AJAJ",
'anArrayOfData' => array('name' => 'Mickey', 'ears' => 'very Big')
);*/
?>
You can send your serialized variable directly like this:
$("#ajax-form").submit(function(){
var variableToSend = $(this).serialize();
$.post(
'ajaxformval_post.php',
variableToSend,
function(data){$("#debug").html(data)},
"json"
);
});
Then on the server side simply output the json_encoded post:
<?php
$variable = $_POST;
echo json_encode($variable);
?>
Did you try changing the "json"-parameter from the $.post-method?
According to documentation https://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
So I guess if you give him "json" he will automatically decode the returned data.

Categories