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.
Related
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...
Here is the HTML: Line 18 below is not carrying over to $_POST['storename'] after Submit is hit. All other text fields are carrying over just fine. The only difference is that this autofills with data from database using PHP and AJAX. I've attached all coding in reference to that field.
Here's the link to the site: http://drmwebdesign.com/project002/product-insert.php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="text" name="pname" id="pname" value="<?php echo $pname;?>" placeholder="Product Name" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="brand" id="brand" value="<?php echo $brand;?>" placeholder="Product Brand" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="price" id="price" value="<?php echo $price;?>" placeholder="Product Price" />
</div>
<div class="6u 12u(mobilep)">
<input type="text" name="upc" id="upc" value="<?php echo $upc;?>" placeholder="Product UPC" />
</div>
</div>
<div class="row uniform">
<div class="12u">
<input type="text" name="storename" id="storename" class="form-control" placeholder="Enter Store Name" />
<div id="storeList"></div>
</div>
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" value="Submit Product" /></li>
</ul>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$('#storename').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"php/storelist.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#storeList').fadeIn();
$('#storeList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#storename').val($(this).text());
$('#storeList').fadeOut();
});
});
</script>
Try the following :
1) Use the chrome network to check the request / response
2) If the field contains a long data check the max post size
3) If the field is a list, and you are selecting multiple choices you need to check this question
4) check if multiple fields have the same name/id
$(document).on('click', 'li', function(){
$('#storename').val($(this).text());
$('#storeList').fadeOut();
});
Triggers when you press the submit button, setting #storename value to nothing.
Add a class to the store names and target onclick using that.
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/
I am using javascript to check whether username and password are not empty. If one of these is empty, javascript alert is displayed and PHP script should not work, that is username and password validation should not occur and login page should be displayed once again. Is there any simple code to do this?
Nobody need to build whole form. I have already build login form and PHP script for its validation, I just want to know is there any method or function in PHP to stop script on entering empty username/password and submitting
Try This
Php Code :
<p>
<label for="first">User Name:</label>
<input type="text" name="First Name" id="first" />
</p>
<p>
<label for="last">Password:</label>
<input type="text" name="Last Name" id="last" />
</p>
<input type="submit" name="Submit" id="button2" value="Submit" onClick="javascript:verify()"/>
JavaScript Code :
function verify() {
if (document.getElementById('first').value=="") {
alert("Please Enter Your Name");
return false;
}
else if (document.getElementById('last').value=="") {
alert("Please Enter Your Password");
return false;
}
else {
document.form.submit();
}
}
Working Model : http://jsfiddle.net/NWWL4/24/
It took me awhile to get this right. I have my form in my html index
page. On a closed question here, I read this couldn't be done.
This php works VERY well with my form.
It generates a Javascript alert for good and bad results and
links back to the index page in either instance.
If you look at the 2nd echo, you'll see where you can redirect to
another page. I just loaded same page to clear form.
If you want to see the ccs, just ask.
PHP:
<?php
if(isset($_POST['submit'])) {
$to = "admin#blahblah.com";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$subject_field = $_POST['subject'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field:\n Subject: $subject_field\n Message: $message\n";
}
if(empty($name_field) || empty($email_field) || empty($subject_field) || empty($message)) {
echo '<script type="text/javascript">alert("There is a problem, please check the fields");window.history.go(-1);</script>';
}
else {
if(mail($to, $subject_field, $body)) {
echo '<script type="text/javascript">alert("Message successfully sent");window.location = "https://www.blahblah.com/";</script>';
}}
exit;
?>
html:
<div class="clear"></div>
<div class="container">
<div class="row">
<div class="col-md-3">
<form role="form" action="php\mailer.php" method="post" id="form">
<div class="form-group">
<input name="name" type="text" class="form-control" id="name" placeholder="Your Name" maxlength="30">
</div>
<div class="form-group">
<input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
</div>
<div><input type="submit" name="submit" class="btn btn-primary" value="Send Message"></input></div>
</div>
<div class="col-md-9">
<div class="txtarea">
<textarea name="message" rows="10" class="form-control" id="message"></textarea>
</form>
<div class="clear"></div>
<div class="col-lg-12" style="text-align:center">
<a class="btn btn-large btn-contact-link" href="#blahblah_home">Home</a>
What I would like to achieve:
A index page (index.html), which allows the user to register, which runs on JavaScript (index.js) to check the fields (not mentioned in snippet index.js), and then to redirect to a register page (scripts/register.php), which then adds the values to the database.
What is actually happening:
It redirects to the PHP page correctly, however none of the values seem to be transferred when using the $_GET method: I get an empty page.
What am I doing wrong?
Code:
index.html (only a snippet)
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
<script type = "text/javascript", src = "index.js">
</script>
index.js (only a snippet)
document.getElementById("signup").onclick = signup;
var aref = "refcode";
function signup()
{
window.location.href = 'scripts/register.php?emailaddress=' + document.getElementById("email").value + '&username=' + document.getElementById("user").value + '&password=' + document.getElementById("pass").value + '&aref=' + aref;
}
scripts/register.php (only a snippet)
<?php
echo $_GET['emailaddress'];
echo $_GET['username'];
echo $_GET['password'];
echo $_GET['aref'];
?>
EDIT: I accidentally copied the wrong code for 'scripts/register.php', sorry to all the answers who corrected it for me
You're never submitting the form (because you don't seem to have one), thus never getting anything but the data that you embed into the URL (which is very unsecure, not a good idea to send sensitive data like passwords like that).
I'm not sure, however, why are you complicating things like that.
If you want to use GET, no need to build the URL yourself, just set up the form with GET method and use regular submit to send it, no javascript needed. Use the hidden field for the aref value (you can populate it when the form is generated, before submitting, etc, whatever works for you):
<form method="GET" action="scripts/register.php">
<input name="aref" type="hidden" value="refcode" />
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
</form>
Again, changing the method to POST would be a much better idea. Of course, then you need to access the variables like $_POST['aref'], etc. Just like this:
<form method="POST" action="scripts/register.php">
<input name="aref" type="hidden" value="refcode" />
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
</form>
And the PHP (for POST):
<?php
echo $_POST['email'];
echo $_POST['user'];
echo $_POST['pass'];
echo $_POST['aref'];
?>
Your fields are not named the same way in the URL and in register.php. Try this.
<?php
echo $_GET['emailaddress'];
echo $_GET['username'];
echo $_GET['password'];
echo $_GET['aref'];
?>
window.location.href = 'scripts/register.php?emailaddress=' + document.getElementById("email").value + '&username=' + document.getElementById("user").value + '&password=' + document.getElementById("pass").value + '&aref=' + aref;
To access them:
$_GET['username']
$_GET['password']
etc...
In your code you never use the good variable names:
<?php
echo $_GET['email'];
echo $_GET['user'];
echo $_GET['pass'];
echo $_GET['accountref'];
?>
For an Solution without JS, and PHP instead:
<form action="scripts/register.php?<? echo $refcode /* HERES YOUR REFCODE */?>" method="GET">
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
</form>
The normal way to do what you want is using method Attribute in your form or the .submit() event in jquery. I'll show how I would do that:
HTML
without javascript using POST
<form method="post" id="login_form" action='register.php'>
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
</form>
php using $_POST
$user = isset($_Post['user']) ? $_Post['user'] : NULL;
$email = isset($_Post['email']) ? $_Post['email'] : NULL;
$pass = isset($_Post['pass']) ? $_Post['pass'] : NULL;
HTML using Jquery
<form id="login_form" method="post" action="">
<input name="user" type="text" id="user" size="25" />
<input name="email" type="text" id="email" size="25" />
<input name="pass" type="password" id="pass" size="25" />
<input type="submit" name="signup" id="signup" value="Sign Up" />
</form>
<script type = "text/javascript" src = "index.js"></script>
//You have a type with a comma
JS
$('#login_form').submit(function(e){
var data = $(this).serializeArray();
$.post('register.php',data,
function(result){
//Your callback function
})
})
NOTE
My advise to you is that you should use POST method in this case
GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
and
POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.