Simple HTML form:
<form action="test.php" method="post" name="my_form" id="my_form" >
<input name="c_name" type="text" id="c_name" maxlength="90"/>
</form>
test.php with the following code:
<?php
$name=$_POST['c_name'];
if ((!isset($name)) || ($name==''))
{
echo 'Fill in the name';
}
else
{
echo $name;
}
?>
Now, I want the following upon form submission:
1) Not to leave the current browser window as PHP to display the corresponding message.I want the form window to stay there.
2)I do not want just a simple response message. For example, I want instead of "Fill in the name" a more graphical way to interact like making a hidden div to appear; in other words I want to write Jquery inside PHP and make it execute. Is it possible and how?
I know I have to use AJAX, however I do not know what to do exactly! Could you give me some code as to realise the above two things?
I believe that if you're new to all of this, as you seem to are, you are best of using jQuery indeed. An ajax example can be found here: http://api.jquery.com/jquery.ajax/
Code in this case is q bit extensive. Cause you would not only want to check if it is in fact empty, but you also want to preg_match it. Which means you want to make sure that what your users send you actually want (and not break or hack or inject your server, which is important).
So seeing this I would recommend to read a tutorial, something like this (fast google search): http://code.tutsplus.com/tutorials/5-ways-to-make-ajax-calls-with-jquery--net-6289
And familiarize yourself with some basics before getting into the next steps.
To get the effect you are wanting. I like to use the jQuery Form Plugin, it makes it easy to create an AJAX form out of any existing form. Then simply echo your results in the .php file you submit to (Hint: you can echo div's with styling too.) The below example, assuming you have the jQuery Form Plugin included on your page, will submit the form using AJAX and return the echoed results to a div with id=status.
$(document).ready(function(){
var status = $('#status');
$('#my_form').ajaxForm({
beforeSend: function() {
status.empty();
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
Related
I would like to auto-submit a form on my page after a short delay based on a variable value (which is present in the URL string, as well as declared by another JS script). Not sure what the best practice way to do this would be?
MY PAGE URL:
http://www.domain.com/mypageaddress?var_1=value1&var_2=value2&var_3=Returning%20Applicant&var_4=value4
So when var_3=Returning%20Applicant , the form should submit without user input (and I would love a 1-second delay built in before that auto submit). Another script on the page also declares a JS variable for that same condition that might be easier to work with than the query string - JS var/value pair returningapplicant=1 is the same as the URL string var_3=Returning%20Applicant that I'm trying to target. This is powered by a third party tool which I don't 100% understand, but they say that this JS variable can be referenced.
I would love some sample code that I could try for this function. Any help much appreciated and here's the extra info that will probably be needed for the JS script:
FORM ACTION URL
<form method="post" action="https://www.tfaforms.com/responses/processor" class="hintsSide labelsLeftAligned" id="tfa_0">
CURRENT FORM SUBMIT ELEMENT
<div class="actions" id="tfa_0-A"><input type="submit" class="primaryAction" value="Next"></div>
-in js
Wait for the window to load.
document.onload = function() {}
Evaluate the url with the condition/s you describe. /
If the condition/s are met submit the form after waiting one second.
if (window.location.href.match('var_3=Returning%20Applicant')) {
setTimeout(function() {
//submit form
document.forms["your-form"].submit();
},1000);
}
Are you doing anything if something doesn't pass the conditions?
Your asking a whole bunch of stuff at once but that's the gist of what you're looking to do. I'd probably parse the url params and evaluate them individually, validate the form, etc... if I were serious about this. Hopefully this can get you started. Good luck.
First question after starting with netbeans and wamp server 2 days ago. Only have some desktop vb background, so my jargon may be off. In vb I would want to set the focus on a control.
I have a long, as in a lot of scrolling, webpage form in html that displays the way I want it. There are about 300 controls, almost all checkboxes.
When the Submit button is clicked at the bottom of the form I want to find any incomplete data, scroll the page to that control and give the user a message so I don't insert unfinished records.
How do I do that?
I think you need to validate data with javascript and with a function to do scroll. Check this:
scroll to div ajax/javascript
In the form, add the 'required' attribute to each input tag.
EX:
<input type="text" required>
When the form is submitted, the first input tag with the 'required' attribute will be scrolled to, and the user will be notified.
What you are looking for is called validation. You should validate data on the server with PHP to make sure that the data meets your defined criteria (since the data could come from a manipulated form and users can deactivate javascript). You should also look into escaping data, for example with mysqli_real_escape_string to prevent SQL injection (an attack where a malicious user enters SQL statements in your form to alter/expose data in your database). And you should sanitize your data.
But that is all server-side. What you also want is to have a good user experience and not even send data to the server unless is is valid. This is done with javascript on the client side. The upside is: Immediate feedback without a page load. But it has little to do with security since it's easy to manipulate that or turn javascript off.
I would recommend using jQuery and then a plugin like jQuery Validation. And for the scrolling part you could use jQuery scrollto. You could combine those two with a callback from jquery validation. For example (just a quick and dirty example):
$(".form-selector").validate({
invalidHandler: function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
// Now scroll to the first error message
var first_element = validator.errorList[0].element;
$(window).scrollTo(first_element);
} else {
$("div.error").hide();
}
}
});
But the best thing would be to start with a jQuery tutorial and then dig into that.
I'm hoping there is a simple solution to this, or else its possible AJAX time!
I WAS using ClickBank. I had a simple button on my page. That sent the form data to a script, I processed the data, and then added a redirect at end of script to jump to the "pay" link. Nice n' easy
But now I'm switching to "Click2Sell" ... and they have a direct href to their site.
Now I COULD use javascript to read the form data, place it into their "cp_" prefix, and create a super long (about 400 chars) query string and send that to their server, then re-read the data at the IPN stage ...
?country=UK&area=essex&desc=This is the data entered by the user 'whatever'
(but that leads to a little fact that certain parts might need to be escaped(?) such as the spaces and the " ' " or whatever other symbol they enter)
So I devised this method:
<javascript>
function send_data(){
document.user.submit();
return true;
}
</javascript>
<div name="noshowdiv"><object name="noshow"></object></div>
<form method="post" target="noshow" name="user">
<input type="text" name="country">
<input type="text" name="area">
<textarea name="desc"></textarea>
</form>
<img src="xxx" onclick="return send_data();">
In a nutshell, when the button is clicked, it jumps to the function, and submits the form data to my script, and then returns to the hyperlink to submit the second form via the hyperlink.
Two problems: Firstly, the data returned by my script is opening in a new tab rather than the <div>, (I suspect 'cos the submit option loses track of the sending window) and also, I need to get a response from my script which I can then append to the href link.
For example, if the form records the user's data on line 5 on my server, the script will return "id=5" I would then make the hyperlink "click2sell.asp?cp_id=5"
As I've said, I suspect this is a job for Ajax and a HttpRequest ... which is a whole new area to me. Any advice?
For the first problem, it opens a new tab because you have target="no-show" on your form.
For the second problem, if you want to use Ajax, I recommend you use jQuery, it will simplify a lot of the code.
But the best option is probably that you completely remove the direct link to click2sell, and just add a submit button to your form. Post the form to your site, which will store whatever info it needs, assigns an ID, and builds the click2sell URL with the ID in one of the parameters, and redirect to it.
Now how you would do that depends on what server-side language you use.
(I think) I have managed to find a work around, which was using the first option to reconstruct the href link. I couldn't iterate through the form as there are values that don't need to be forwarded. First I get the value, load it into a variable, then use an encode function I discovered online, and then reassign to the form ...
var cp_cc=document.getElementById('cc').value;
var cp_cs=document.getElementById('cs').value; // plus 10 other values
var str='&cp_cc='+encodeURIComponent(cc)+'&cp_cs='+encodeURIComponent(cs)+ // etc
var send_str=document.getElementById('c2s_bn_lnk_36288').href;
document.getElementById('c2s_bn_lnk_36288').href=send_str+str;
The "no-show" was a slip up in my typing! Alas, the answer given above wouldn't work as the Click2sell button also includes two calls to external JS files - and they give you no idea what they do, but is something to do with initializing the button, (it passes the "36288" to the script to do ???). And whilst using "Location: ..\n\n" on my server would redirect to their site, it wouldn't action whatever those external files do. (OK, so I didn't give the full facts, but I didn't want to increase the post size with data I felt didn't relate to problem)
** Now got to amend the listening scripts such that rather than set the ID number up front then jump to C2S, it now waits for C2S to send the data back to me and then sets up the database!!
I have a contact form which initially "onsubmit" calls a javascript function to validate the content. If this function returns true it then posts the data to a php file.
At the end of this file I would like to return to the contact page, currently I am using this:
header('Location: ' . $_SERVER['HTTP_REFERER']);
is there a better way?
I would also like to change the css on an element on the contact page to display when I return (a thank you message), is this possible? I can set it to display using jQuery in the initial javascript function but that gets wiped out when it goes to the php file.
Thanks
Post to self then you if statement after post has been handled to redirect.
Do you redirect like you have said, using headers.
So make it post to self on the action part of your form
<form action="yourpage.php">
Then added PHP to handle post on yourpage.php
if(isset($_POST)){
//Handle POSTed data.
//if handled correctly
{
header("Location: somewhere.com")
}
}
The HTTP_REFERER is not the best solution to accomplish a history -1 in PHP.
As stated in the documentation :
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
The best solution is to explicitly write the page to return in the header function.
For the second question, you can redirect with a query parameter:
header('Location: script.php?valid=1');
And then test it in your view:
if (isset($_GET['valid']) && $_GET['valid'] == '1') {
// display the message
}
Make the form submit the data to the same page of the contact form.
Then from the PHP script check if a form has been submitted, do your processing code and return a div with your thank you message.
Say the name of your contact page was index.php. You could setup your form with the correct action (although it should be this way by default) and then check in the header for a submission parameter. Code below
<?php
if (array_key_exists("submit_btn",$_REQUEST) {
//display a thank you
}
?>
<!-- more code here-->
<form action="index.php">
<input name="whatever" type="text">
<input type="submit" name="submit_btn">
</form>
I found a few ways to do this in the end thanks to various peoples answers. Thanks all.
The simplest way was just to re-direct to a contact thank you page using the following header:
header("Location: http://{$_SERVER['SERVER_NAME']}/contact-thankyou.html");
I changed to using SERVER_NAME as HTTP_REFERER wasn't a great solution.
The second solution, which was a bit uglier but did the job was to return to the same page with a header like this:
header("Location: http://{$_SERVER['SERVER_NAME']}/contact.html?submitted");
Then use the following Javascript to detect the query parameter and change the css:
if (window.location.search.substring(1) == "submitted")
{
$("#message-sent").css({"display": "block"});
}
This is NOT a great solution, as I'd prefer to get the query parameter using php but I'm restricted to html and Javascript on pages with the template system I'm having to build on.
Thanks all.
I have troubles to change content in my HTML document with javascript after submitting a form with a POST method. I need to change the color of a div inside my HTML document to yellow, I have already done it, but the problem is that after it changes to yellow then the HTML website gets refreshed in the navigator and then it goes back to normal(white). It kind of flashes the yellow and then goes to white again.
Here is my HTML code:
<form action="" method="post" onSubmit="return changeColor()">
.
.
.
<div id="divColor">
.
.
And this is my javascript code to change the div color:
function changeColor()
{
var div = document.getElementById("courselist");
div.style.backgroundColor='yellow';
}
I need to do it this way because is part of the assignment, so I cannot change the color with CSS and so far we can only use HTML and javascript. This is not the whole assignment in case somebody thinks I want to cheat, this is the part that I am stucked with. I cannot make the div keep the yellow color after the navigator has refreshed the HTML website after the POST method.
Thank you!
When you submit a form, it goes to the next pages specified in action="". Therefore, when you click the submit button, it changes color, then the next page loads. Due to the lack of page specified in action="", it is reloading the same page so it turns yellow, then refreshes.
This is what you are probably looking for. You use AJAX to submit information to POST without actually loading a different page.
There are three ways to achieve your aim.
Using ajax to submit information, so that the page is not refreshed, and the status remain.Or you can do it like the following, it has the same effect as ajax:
< iframe name="myIfr" style="display:none">< /iframe>
< form method="post" target="myIfr">...< /form>
Changing "action" of "", record the status in the url, like this: "mypage.php?status=1", After the page is refreshed, you can get the status from the url.
Using Cookie. I think it's not a good idea.
You could separate it so that the form only prints out if other conditions are met. Use a variable called $output_form (or whatever you feel like naming it) and set it to false, then have the code print out one thing before the POST is sent, and something after the POST is sent. Here is a really stripped down version of some code I finished a little while ago, might help you see what you can do:
<?php
if(isset($_POST['Submit'])){
{SOME CODE HERE}
$output_form = true;
}
}
else{
$output_form = true;
}
if (!$output_form){
{SOME CODE HERE}
}
else{
{OTHER STUFF HERE}
$output_form = true;
mysqli_close($dbc);
}
}
if ($output_form){
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Hi guys I finally solved my problem.
I had to return false in my changeColor() function and the website will change color, but not refresh itself. I like the approach with cookies.
Thank you for your help, I could not use either AJAX or PHP because they have not taught us that yet.