Error in passing value from JS to PHP - php

I am trying to pass a value from javascript to php using POST method but it is not working .Here is the code:
<head>
<script type="text/javascript">
function Email()
{
var e=prompt("Your Email","");
if(e==null||e=="")
{
alert("You need to enter an email..Try again");
Email();
}
return e;
}
function Code()
{
var f=prompt("Activation code","");
if(f==null||f=="")
{
alert("You need to enter the code..Try again");
Code();
}
return f;
}
</script>
</head>
<body>
<form method="post">
<input type="hidden" id="Email" name="Email" />
<input type="hidden" id="Code" name="Code" />
</form>
<script>
var email=Email();
var code=Code();
document.getElementByID("Email").value=email;
document.getElementByID("Code").value=code;
</script>
<?php
$email=$_POST["Email"];
$code=$_POST["Code"];
echo $email.$code;
?>
</body>
I get these errors :
Notice: Undefined index: Email
Notice: Undefined index: Code
Anybody please help me out...

Okey if you want to print those values you need to create a form form them, a proper one. If you just want to submit form no need for JS there because if you just want to submit some values there is no need for form, you want to use jQuery Post for that.
<form method="post" action="">
<label for="email">Email</label>
<input type="text" name="email" />
<label for="code">Code</label>
<input type="text" name="code" />
<input type="submit" value="Submit" />
</form>​
Fiddle: here
Edit
Then this is what you want. (Note that this code is using jQuery library)
$(function(){
// Create both variables
var code, email;
// Ask for code and check if it's not null or empty
do{
code = prompt('Activation code', null);
}
while(code == null || code == '');
// Ask for email and check if it's not null or empty
do{
email = prompt('Your email', null);
}
while(email == null || email == '');
// Make POST request via AJAX to your script
$.post('yourscript.php', { code: code, email: email }, function(data) {
// If success alert response (in your case should be "email.data" values)
alert(data);
});
});

Related

Multiple fileds : remember input values after submit

I have a multiple field input and I want to remember the input values after submitting it , how can I do that using php or maybe another language if it is possible?
I have this input:
<input type="text" name="passport[]" class="form-control" aria-describedby="basic-addon1"required/>
I have tried something like this :
value="<?php if(isset($_POST['passport'])) { echo $_POST['passport'][$i]; } ?>"
but nothing works.
You can use browser local storage to keep the value after form submission.
<form method="post" action="" onSubmit="return saveElement();">
<input type="text" name="passport[]" id="password"/>
<input type="submit" name="submit" value="save"/>
</form>
<script type="text/javascript">
document.getElementById("password").value = localStorage.getItem("password");
function saveElement() {
var passValue = document.getElementById("password").value;
if (passValue == "") {
alert("Please enter a password first!");
return false;
}
localStorage.setItem("password", passValue);
location.reload();
return false;
}
</script>

Only pass GET information if isset

I am using a form with the method of GET to add to the query string.
I am running into an issue. When the form is submitted every field is sent and added to the query including with no values.
Example:
http://web.com/?filter-types=news&filter-document-type=&filter-topics=we-have-a-topic&filter-featured=&filter-rating=
Can I not add these to the query string if they are not set? !isset() or is there another way to do this?
You could alternatively manipulate the form inputs thru javascript, just a Mike said in the comments, on submit check the fields, if empty, disable them so that they wont be included on submission.
This is just the basic idea (with jQuery):
<form method="GET" id="form_inputs">
<input type="text" name="field1" value="field_with_value" /><br/>
<input type="text" name="field2" value="" /><br/><!-- empty field -->
<input type="text" name="field3" value="field_with_value" /><br/>
<input type="submit" name="submit_form" id="submit_form" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[name="submit_form"]').on('click', function(e){
e.preventDefault();
$('form').children().each(function(i, e){
if($(e).is('input') && $(this).val() == '') {
$(this).prop('disabled', true);
// or $(this).attr('name', '');
}
});
$('form').submit();
});
</script>
Or if you do not want to use jquery at all:
document.getElementById('submit_form').addEventListener('click', function(e){
e.preventDefault();
var children = document.getElementById('form_inputs').childNodes;
for(i = 0; i < children.length; i++) {
if(children[i].type == 'text' && children[i].value == '') {
children[i].disabled = true;
}
}
document.getElementById('form_inputs').submit();
});
The reason all those keys show up in query string is because they exist as inputs in the form. If you don't want them sent, remove them from the form, or at least give them some meaningful defaults.
I guess you are looking a condition
if (!empty($_POST['var'])) {
}
OR
if (!isset($_POST['var']) && !empty($_POST['var'])) {
}

AJAX code not working on button click

Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});

newbie ajax (jquery) issue

I'm pretty strong with PHP, but javascript is totally new to me.
I need to add various ajax functionality to my projects, for example for form validation etc.
I've done some searching, watched some tutorials, and come up with a basic working example as follows:
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax form test</title>
<style>
form input, form textarea {
display:block;
margin:1em;
}
form label {
display:inline;
}
form button {
padding:1em;
}
</style>
</head>
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js:
$('form.ajax').on('submit', function() {
console.log('trigger');
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#form_content').load('server.php', data);
}
});
return false;
});
and finally, server.php:
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='')
{
?>
<h4>Your data was submitted as follows</h4>
<br />name: <?=$_POST['name']?>
<br />email: <?=$_POST['email']?>
<br />message: <?=$_POST['message']?>
<?php
} else {
?>
<h3>please fill in all form data correctly:</h3>
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
<?php
}
This all works fine, in that if I enter all form data and click submit, the ajax magic happens and I get a confirmation of the data. Also if not all data is loaded, the form is re-presented on the page. The problem is that in such a case, continuing to fill out the form data and then submit it loads the server.php page instead of repeating the ajax call until the form data is valid..
I'm sure there's a better way to do this as it's my first attempt, but I haven't been able to find any solution by searching either here or on google, but that's probably mostly because I don't really know what to search for. how can I make the behaviour in the first instance repeatable until the form is submitted correctly ?
This happens because you are removing your form element during your load() call and overwrite it with a new version of the form. Therefore all attached event handlers will vanish along with it.
You will need to use a delegate on an element that does not change:
$('#form_content').on('submit', 'form.ajax', function() {...});
Explanation:
In the above example, you attach the event listener to the #form_content element. However, it only listens to events that bubble up from the form.ajax submit event. Now, if you replace the form with a new version, the existing handler is attached higher up in the chain (on an element that doesn't get replaced) and continues to listen to events from lower elements, no matter if they change or not... therefore it will continue to work.
Your primary problem is that you are validating the form on the PHP side, when you should really validate it on the client side - THEN, instead of returning an appropriate response and continuing processing on the client side, you are finishing processing on the PHP side. Steve's answer (above) applies to what you are seeing.
As to the approach you have taken, it might be better to not use a <form> construction at all, because with AJAX you often don't need to. In my opinion, <form> is an archaic structure, not often needed in the age of AJAX. Notice how you had to add return false following the AJAX block to abort the default form functionality -- to stop it from sending the user over to server.php? That should tell you something.
Here is another way to structure it:
HTML:
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="button" id="mybutt" value="send">
</div>
<div id="responseDiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
JAVASCRIPT/JQUERY:
$(document).ready(function() {
//Next line's construction only necessary if button is injected HTML
//$(document).on('click', '#mybutt', function() {
//Otherwise, use this one:
$('#mybutt').click(function() {
console.log('trigger');
var valid = "yes";
var that = $(this),
url = "server.php",
type = "POST",
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (value=="") valid = "no";
data[name] = value;
});
if (valid == "yes") {
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#responseDiv').html(response);
/* OPTIONALLY, depending on what you make the PHP side echo out, something like:
if (response == "allgood") {
window.location.href = "http://www.google.com";
}else{
//this is how you would handle server-side validation
alert('Please complete all fields');
}
*/
}
}); //END AJAX
}else{
alert('Please complete all fields');
}
}); //END button.click
}); //END document.ready
PHP Side: server.php
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='') {
$r = '';
$r .= "<h4>Your data was submitted as follows</h4>";
$r .= "<br />name: " . $_POST['name'];
$r .= "<br />name: " . $_POST['email'];
$r .= "<br />name: " . $_POST['message'];
} else {
$r = "Please complete all form fields";
}
echo $r;

Using php form inside phonegap

I have asked before for help to get my php form working inside an phonegap ipa. I did exactly as I was told and everything works just fine, even inside the ipa. Only problem I have is that I get this alert right at the moment when the page loads, obviously it should show up when client forgets to fill in a required field.
Here is what I did:
FORM in contact.html
<form action="http://mobile.alicante-intermedia.com/submit_contact.php" method="get">
<div class="form-element">
<label for="txtfullname">Firstname</label>
<input id="txtfullname" name="FirstName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtemail">Lastname</label>
<input id="txtemail" name="LastName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtcontact">Email</label>
<input id="txtcontact" name="Email" type="email" placeholder="optional" />
</div>
<div class="form-element">
<label for="txtmessage">Message</label>
<textarea id="txtmessage" name="MessageText" placeholder="required" rows="5" required ></textarea>
</div>
<input type="button" onclick="submit()" value="submit contact"/>
</form>
Then I created a jquery_form.js file which loads only inside the conatct.html
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
FirstName: $('#FirstName_input').val(),
LastName: $('#LastName_input').val(),
Email: $('#Email_input').val(),
MessageText: $('#MessageText_input').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
And the php looks like this:
<?php
// VARS
$FirstName=$_GET["FirstName"];
$LastName=$_GET["LastName"];
$Email=$_GET["Email"];
$MessageText=$_GET["MessageText"];
$Headers = "From:" . $Email;
//VALIDATION
if(
$FirstName=="" ||
$LastName=="" ||
$Email=="" ||
$MessageText==""
) {
echo "Error";
} else {
mail("myemail#email.com","mobile app message",$MessageText, $Headers);
echo "Success";
}
?>
Everything works fine except the alert screen. Anyone here who has an idea what went wrong?
Your JavaScript code is "bare", not wrapped in any function or attached to any event handler, and therefore executes as soon as it is loaded - so it immediately posts an empty form when the jQuery script is first parsed.
Place it into the onclick event handler for the submit button:
// When the document has loaded...
$(document).ready(function() {
// Bind this action as a function to be executed when the button is clicked...
$('input[type="button"][value="submit contact"]').click(function() {
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
// EDIT: You have the wrong ids on these...
FirstName: $('#txtfullname').val(),
LastName: $('#txtemail').val(),
Email: $('#txtcontact').val(),
MessageText: $('#txtmessage').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
});
});
Since it is bound in the JavaScript code, remove the onclick from the button in your markup:
<input type="button" value="submit contact"/>
Edit:
The PHP you have is looking for values in $_GET, but you have posted them from jQuery. Look instead in $_POST.
$FirstName=$_POST["FirstName"];
$LastName=$_POST["LastName"];
$Email=$_POST["Email"];
$MessageText=$_POST["MessageText"];

Categories