sending form to php with iframe - php

I am writing a form, where user can send info, and attach a file, which sends via email to certain users.
I've built a HTML form, and because I don't wanna to refresh the page I sent it via a hidden iframe.
Everything was working, until I added captcha to my form. Now I've got a problem. I store a generated string for captcha in the session on the main form page. But because the form is sending from an iframe I think PHP is creating a new session, which is empty.
Can anyone have suggest how can I connect iframe and my form page to same the session? I would like to mention, that the iframe is created dynamically by JavaScript when the user clicks to send the form.
thanks for advice!
edit:
my code
HTML form page:
<input type="text" name="name"/><br />
<input type="text" name="email"/><br />
<textarea name="message"></textarea><br />
<input type="file" name="file"/><img id="captchaimg" src="http://xxx/mailsend.php?application=xxx&image=get"/><input type="text" name="captcha"/>
<input type="button" id="send" value="send"/>
my JS file:
function sendFromIframe() {
if ($('#hiddeniframe').length == 0) {
var iframe = ('<iframe name="hiddeniframe" id="hiddeniframe" src="" border="0" height="0" width="0" style="display:none"></iframe>');
$("body").append(iframe);
}
setTimeout(function() {
var form = $('#feedback');
form.attr('target', 'hiddeniframe');
form.attr('method', 'POST');
form.attr('action', 'http://xxx/mailsend.php');
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.submit();
wait4refresh();
}, 550);
}
function wait4refresh(counter){
var counter = counter || 0;
var bolean = false;
var request = $.ajax({
async: false,
url: 'http://xxx/mailsend.php',
type: 'GET',
data: 'application=' + $('input[name="application"]').val() + '&issend'
});
request.done(function(msg){
if (msg == 'true'){
bolean = true;
}
});
if (bolean){
refreshCaptcha();
}
else if (counter > 10){
return false;
}
else{
setTimeout(function(){
counter++
wait4refresh(counter);
},500);
}
}
function refreshCaptcha() {
var application = $('input[name="application"]').val();
d = Math.round(Math.random() * 100);
$('#captchaimg').attr('src', 'http://xxx/mailsend.php?application=' + application + '&image=get' + '&' + d);
}
and the PHP file:
i get error "connection reset by peer" when I'm trying to add my PHP code here. what can I do?

CouldnĀ“t you just create a <div id='htmlform'> </div> and just make it visible/invisible with jquery?

Related

Submitting forms thru in PHP on jQuery

I have a registration form that is currently in a popup modal window coded in jQuery. I have a PHP submit button on the bottom and I have added jQuery code that stops the button from submitting. This is because it will stop my modal window from closing when I submit the page. My issue now is that submitting the form would be impossible. Is there a way to submit my form over all this crowded pop-ups and jQuery? Say is it possible to use AJAX or jQuery to submit the form and allow my PHP to handle it.
Since I am writing in PHP, there is quite a bit of server side validation going on, so the point of this is to allow my viewers to fix their validation mistakes before the modal window closes.
Here is my jQuery, I didnt bother to mess with that anymore as it does what I need.
$(document).ready(function() {
$('a.modal-window').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
$(loginBox).fadeIn(300);
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
Here is the code I used to stop the form from submitting:
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
// submit the form dynamically
});
});
and below is my form, it might not matter although its there for the viewing.
<form method="post" id="loginform" action="<?php echo $_SERVER['PHP_SELF']?>">
<table style="color: white;">
<tr><th style="float:left;">Register a new account with us.</th></tr>
<tr><td>Username</td><td><input type="text" name="txtUser"/></td></tr>
<tr><td>Password</td><td><input type="text" name="txtPass"/></td></tr>
<tr><td>Email</td><td><input type="text" name="txtEmail"/></td></tr>
<tr><td>Confirm Email</td><td><input type="text" name="txtEmail2"/></td></tr>
<tr><td>First Name</td><td><input type="text" name="txtFname"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="txtLname"/></td></tr>
<tr><td>Address</td><td><input type="text" name="txtAddress"/></td></tr>
<tr><td>City</td><td><input type="text" name="txtCity"/></td></tr>
<tr><td>Postal Code</td><td><input type="text" name="txtPostal"/></td></tr>
<tr><td>Birth Year</td><td><input type="text" name="txtBirth"/></td></tr>
<tr><td>Gender</td><td><input type="radio" id="radio-1-1" name="radicalSex" class="regular-radio" value="m" selected="true" /><label for="radio-1-1"></label> Male</td></tr>
<tr><td></td><td><input type="radio" id="radio-1-2" name="radicalSex" class="regular-radio" value="f"/><label for="radio-1-2"></label> Female</td></tr>
<tr><td colspan='2' style="color: #FF6600;float:left;font-size:70%;"><?php echo $Error;?></td></tr>
<tr><td colspan="2"><input type="submit" name="btnRegister" ID="btnBlueTemp" value="Submit Registration" /></td></tr>
<tr><td colspan='2' style="float:left; font-size:70%;">Address information is optional</td></tr>
</table>
</form>
Let me give you an example of how you can do that .
<html>
<head>
<title></title>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
function validate(name, addr){
if(name=="") {
alert('Name is Blank');
return false;
} else if(addr=="") {
alert('Address is Blank');
return false;
} else {
return true;
}
}
$("#save").click(function(event){
event.preventDefault();
var name = $("#name").val();
var addr = $("#addr").val();
if(validate(name,addr)){
$.ajax({
type:'POST',
data:'name='+name+'&addr='+addr,
url:'test2.php',
success:function(data) {
alert(data);
}
})
}
});
});
</script>
</head>
<body>
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value=""/><br>
<input type="text" name="addr" id="addr" value="" /><br>
<input type="submit" name="save" id="save" value="Save"/>
</form>
</body>
</html>
Now in test2.php You can do your php codes
<?php
if(isset($_POST['name'])) {
echo $_POST['name'];
}
?>
Hope this gives you an Idea.
You need to serialize the form data before posting it to PHP.
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('submitted');
}
});
return false;//stop actual form submit
});
</script>
Then, submit your form via ajax
Jquery AJAX
On AJAX URL on which the request is sent, you can write necessary codes for validation and return accordingly. For eg. if some one the form element doesn't meet the validation, you can throw the flag accordingly as json value.
Its possible, why not.
Once you have done all the input validation at client side, just submit the form...
$("#loginform").submit();
Then you will have your server do the rest of the validation.
If you want to stay in the page and show the validation output from server, the. You should submit using Ajax.
It will send your form data to server, then you can do server validation, and output any errors. You will get this in your Ajax complete handler, which you can use to show error messages to user.
To stop the form from reloading the page you needn't call any prevent methods as a simple script request would do the trick.
For instance,
$('#loginForm').submit(function() {
// Do the relevant tasks needed here, form is already prevented from being submitted
});
Check out this demo for more information on what I am referring to

AJAX Hash Submit Form

I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information

submit a form via Ajax and update a result div

I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...&param2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}

Uploading image via AJAX along with username and email address

I am having some trouble with my file upload script. The HTML is as follows:
<form method="post" name="imgsubmit" id="contact_form" action="PHP/imgupload.php" enctype="multipart/form-data">
<label id="namelabel" for="username">Your name:</label><input id="username" type="text" name="username" rel="req">
<label id="labelemail" for="imgemail">E-mail:</label><input id="imgemail" type="email" name="imgemail" rel="req">
<label id="filelabel" for="file">Your photo:</label><input id="file" type="file" name="file">
<input id="imgsubmit" type="submit" name="submit" value="SUBMIT"></form>
I have a jquery validation script as which checks the username and email fields to see if they are valid, and returns a white border around them if they are not entered:
$(function () {
$('#contact_form').submit(function (e) {
e.preventDefault();
var form = $('#contact_form');
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;
req_fields.each(function () {
field = $(this).val();
if (field == '' || field == 'Required') {
$(this).css('border', '1px solid white').val('');
pcount += 1;
} else {}
});
if (pcount == 0) {
submit_form = true;
}
if (submit_form) {
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (msg) {
$(form).fadeOut;
form.html(msg).fadeIn();
}
});
}
});
});
The problem is that the username gets submitted to the php script, the email gets submitted to the php script, but the image doesn't get uploaded. I'm aware that AJAX now supports image uploading and that the form.serialize() is likely the root cause of the problem, but have not been able to edit this code correctly to support the image submission.
How can I adjust this code to include the image to be submitted to the php?
`if (window.FormData)`
check this and file must be `
file = $('#elemet').files.
and ajax option should be data: FormData,
where formdata = new FormData();
I like to use the jQuery Form Plugin for this kind of stuff, you just need to bind your form submittal when the DOM is ready for it to work. The example bellow is providing a success callback, but there are other events you could use, like error, beforeSubmit, and so forth:
$('#contact_form').ajaxForm(function() {
alert("Thank you for your data!");
});
It supports both regular input values and also file uploads (in older browsers it will fake an ajax file upload using iframes), and if your browser can handle it you can even display a progress bar.

Jquery submit() html form based on php script's return value

Ok, if somebody could take a look at this, I'd really appreciate it. I'm implementing a captcha in an html form. The captcha is php based, so i need to use jquery to post the submitted form to the captcha check script.
The php script returns 1 if the check was correct, or 0 if it was incorrect.
This is all working great, the problems i am having are with actually submitting the form, or preventing it based on what the php script returns. My the code is as follows:
<form id="contactform" action="FormHandler.cgi" method="POST">
<input name="requiredContact" size="25" type="text" />
<input name="requiredEmailFrom" size="25" type="text" />
<input name="requiredTelephone" size="18" tabindex="3" />
<textarea cols="25" name="comments" rows="4"></textarea>
<select length="2" name="requiredContactMethod" tabindex="5">
<option selected="" value="Email">Email</option>
<option value="Telephone">Telephone</option>
</select>
<img src="captcha/captcha.php" style="float:none; margin:0px 0px -8px 0px; height:26px;"></img>
<input type="text" id="CAPTCHA" style="margin-left: -5px; height:26px;">
<p id="caperror"></p>
<p><input name="B1" type="submit" value="Submit" />
<input name="B2" type="reset" value="Clear" /></p>
</form>
<script>
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
if(result == 1){
alert('was correct');
return true;
}
else{
alert("error" + result);
return false;
}
}
function postfail(){
alert('post failed');
return false;
}
</script>
So what i would like to happen, is when my success function returns false, it stops the form from submitting. If it returns true, go ahead and submit the form. This is what I would like
$('#contactform').submit(function(){
//The ajax post here
//check the value of the ajax success function here;
if(success(result)) {
return true;
}
else {
return false;
}
});
I am not good with function scopes in javascript. If I define a variable inside the success function, I can't check the value in the form submit function, because it only has a local scope. I could just use a link to submit the form, and then call submit(); but I want the form to be accessible to those without java.
Is there any way to get the ajax post success function's result back to the scope of the submit() handler?
Unless I'm missing something, you should be submitting the form in the AJAX call's success function. The AJAX call should also not be being thrown upon form submit. The form should not be being submitted in any way until the check has come back true. IE:
$.ajax(
//Parameters and stuff
).success(function() {
//Submit the form
$('#contactform').submit();
}).fail(function() {
//Onoes your call has failed. Do not submit le form :(
});
As far as "scoping" goes, this shouldn't be a "scoping" issue. Let me know if you need further instruction.
I would write the function like this only setting submitForm on a 1 result.
$('#contactform').submit(function(){
var submitForm = False;
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
success:function(result){
if(result == 1){
submitForm = True;
}
}
});
return submitForm;
});
I was going to suggest that in your success function you call $('#contactform').submit(), but that would just call your event handler again and you'd be stuck in a loop.
What instead you can do is call the form element's submit function, like this:
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
myform = this; // added this line
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
context: myform, //added this line
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
// because we added the context option, we can now access the form with the "this" keyword
if(result == 1){
alert('was correct');
// $('#contactform').submit() // this will make an infinite loop
this.submit(); // this will submit the form
return true;
}else{
alert("error" + result);
return false;
}
}
Try making the ajax call on the submit button click not on the form submit.
If the return of the click call is true, you call the submit function.

Categories