Imagine the page always refreshes after submitting a comment form. That is annoying since the comments are at not at the top of the page and you always have to scroll to the bottom to see your comment and the other ones.
I thought it would be a lot better to use ajax to submit the form.
HTML
<form id="com-form" method="post">
<textarea type="text" name="text" required=""></textarea>
<input type="submit" value="Post"/>
</form>
<div id="com-refresh"></div>
jQuery
$("#com-form").on('submit', function(e) {
e.preventDefault();
var form = $(this),
form_data = form.serialize();
$.post('/php/comments/add.php', form_data, function(data) {
$("#com-refresh").append(data);
});
});
PHP
<?php
session_start();
require_once 'comment.class.php'; //require a class with methods
$text = $_POST['text'];
if($_SESSION['status'] == 'loggedin') {
if(isset($text)) {
$comment = new Comment(); //initialize the Comment object
echo $comment->add_comment($text); //safe the comment in the database and output it
} else echo "Your comment is empty.";
} else echo "Please log in to post comments.";
I hope the code is understandable.
Do you think it is smart or a bad practice to use ajax to not refresh the page after submitting a form?
How should it be done? Do you have a better idea, a cleaner solution?
You could simply do:
$(document).ajaxSuccess(function(e, xhr, settings) {
$(".mydiv").html(xhr.responseText);
});
having your php file print what ever html you want to replace.
further reading: ajaxSuccess
example of what might be your solution
form file:
<form method="post">
<textarea type="text" name="comment" id="com-area"></textarea>
<input type="submit" id="com-submit"/>
</form>
<div id="com-refresh">
<?php require_once "comments/build.php"; ?>
</div>
$(function() {
$(".cmtx_form").submit(function(e) {
e.preventDefault();
var form = $(this);
var text = $(".cmtx_textarea_field").val();
$.ajax({
type: 'POST',
url: 'comments/add.php?ajaxCall=true',
cache: false,
data: { comment: text }
});
});
});
$(document).ajaxSuccess(function(e, xhr, settings) {
$("#com-refresh").html(xhr.responseText);
});
your add.php file should look somewhat like so:
// ... code code code...
if (isset($_GET['ajaxCall']) && $_GET['ajaxCall']) {
include_once('/path/to/build.php');
}
simply you can redirect the file from add.php to build.php after complete the process using header('location:comments/build.php'); or some other else, so second ajax call was unnecessary.
The problem was the php code. I have rewritten the functions that generate the comments in OOP style which helped a lot. I edited the post know so it can be useful in the future.
To make it short:
Use ajax! Your website's user experience will be a lot better, because you are able to provide live updates, etc.
It is recommendable to use the built-in jQuery function .serialize() to safe data into a "text string in standard URL-encoded notation", that can make your work more simple.
I know there is a lot of discussions about OOP, but it really helps understanding, organizing and maintaining your code more easily
Related
I want to use another page of my site to validate HTML form input. If the input is NOT valid, I want to show an error somewhere on my form page without reloading. And otherwise, if it IS valid, I want to submit the form normally.
After reading similar SO questions, I didn't found any exact solution, but actually invented my own, which works for me. Though, I still think that my solution is a bit weird, so I'm asking for proper ideas.
HTML:
<form id="form" method="POST"> ... some inputs ... </form>
<button id="submit" type="submit">Save</button>
<p id="errors"></p>
JS:
$('#form').submit(function (event) {
var formData = $(this).serializeArray();
event.preventDefault();
$.ajax({
type: "POST",
url: '/validate/',
data: formData,
success: function(data) {
if(!data)
{
$('#form').unbind('submit');
$('#submit').trigger('click');
}
else
{
$('#errors').text(data);
}
}
});
return false;
});
NB: It works as expected, I'm asking for better solutions.
I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.
I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.
You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>
You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>
dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}
There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable
UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.
This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.