I need help getting a <div> to refresh on form submit - php

I have looked all over stack, and googled the crap out of it, but everytime I come across something I only come across snippets and I cannot find the full code, how can I get a div to reload on form submit?
this is the div I want to refresh
<div id="accsettings">
<?php require_once('profileform.php'); ?>
</div>
this is the form
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?username=' . $user_name; ?>">
Thanks
I need it to refresh on submit so that it shows the affect the player had on their profile
(by showing their comment and that they increased their rep on the webpage by +1 and removing the textfields/submit form, all that is already taken care of, I just need it to refresh on submit)

What's the name of you submit button? If it were submit, you could do something like:
<div id="accsettings">
<?php if (!isset($_POST['submit'])) { require_once('profileform.php');} else {echo '&nbsp';} ?>
</div>
This assumes that the form submits to the current page.

$("form").on('submit', function (e) {
$.post($(this).attr('action'), $(this).serialize() + '&submit=TRUE').done(
function () {
$("#accsettings").load('profileform.php');
}
);
e.preventDefault();
});
What this will do is an ajax load of profileform.php into the contents of the #accsettings div. This assumes that your form submission properly updates the output of profileform.php and is done via ajax (I see no evidence of that in your code currently, though).

Related

Ajax Refresh of Div on form submit oscommerce

In oscommerce I want to refresh the product div called 'left-div' with form field checked results on autosubmit- rather than whole page:-
I use oscommerce 2.3.4:-
Step wise I have below files-
I have pulled a form on index.php in a div called 'right-div',
which is called from a box module bm_form.php using below code-
if (class_exists(bm_form)) {
$boxdata = new bm_form;
echo $boxdata->getData();
}
Now this form has below code for action on bm_form.php:-
<form name="form_srch" id="form_srch" action="'.tep_href_link(FILENAME_DEFAULT).'" method="get" >.....</form>
The form is processed at this folder
ext/form/form.php
ext/form/form.js
ext/form/form.css
The above form process is called in my index.php using below code:-
at very top
require('includes/application_top.php');
require('ext/form/form.php');
The issue is I when I fill the form it triggers the entire page to refresh whereas I need to refresh only the div with form result.
My form.js uses below code for submit
$("#form_srch").submit(); // submit form
I tried using the idea given here for ajax refresh of Div-
Refreshing ajax div with form data
Editing this code in ext/form/form.js:-
$("#form_srch").submit(
function(e){
e.preventDefault();
$.get('ext/form/form.php', $(this).serialize(), function(data){
$('#left-div').html(data);
}
);
return false;
}); // submit form
And removed the action part from the form leaving action=""
But still it does not work at all the form stops working altogether,
Please can someone help me get this working......

Set post data as a session (PHP/jQuery)

I'm trying to create a form that users can bring with them on other pages and drag around (like Twitter's submit form). So once you hit "Write," a div will show up with the draggable form. I want it to set up so when I hit X on the div, it will submit to a page that will set it as a session, so when I hit "Write" again, the form will have all the information in it. Here's how I have it set up - the form:
<div id="writeOverlay"><form action="process.php" id="writeForm">
<input type="text" name="title" value="<?php if(isset($_SESSION['writeTitle"])){
echo $_SESSION['writeTitle'];?>">
X
<button type="submit">Submit</button>
</form></div>
And when you click the X, jQuery handles it as such:
$('#writeExit').click(function(){
$('#writeOverlay').hide();
event.preventDefault();
$.post('site.com/writeHandle.php', $('#writeForm').serialize(),function(){ // the $('#writeForm') was originally just $(this) but I changed it to see if I'd get different results. I did not.
console.log('Closed.');
});
});
writeHandle.php works like this
<?php
session_start();
$_SESSION['writeTitle'] = $_POST['title'];
?>
Hitting the submit button works as it should, but when I hit exit, the session is not saved. So when I click "Write" again, the form will load as empty. I hope to be clear and concise with this issue. If more information is required, leave a comment and I'll be sure to update this.
There's an error. The title variable that you are trying to get in PHP is not sent properly. It should be send something like:
...,{title: "this is my title"}, function(){...}
So, edit your input tag:
<input id="title" ...... >
then your post code:
$.post(
'site.com/writeHandle.php',
{
title: $("#title").val()
},
function(){ // the $('#writeForm') was originally just $(this) but I changed it to see if I'd get different results. I did not.
console.log('Closed.');
}
);

Hide the fact a page has been sent a form on reload

I have used a form to submit an image id to the another page. I have done this rather than r than via url because it makes the url cleaner. However, when the user now reloads, it asks if they want to submit the form again. The won't know they have submitted a form, as far as they are aware they have simply clicked an image and been brought to a page that displays that image bigger.
Is there any way around this, that saves the image id the hidden form field has sent via the form, yet refreshes the page for the user?
HTML
<a class="gallery-img span4 js-img-submit" href="#">
<img src="img.jpg"/>
<form action="/image" method="post">
<input type="hidden" value="<?=$img['id']; ?>" name="image_id"/>
</form>
</a>
JQUERY
$('.js-img-submit').click(function(){
$(this).find('form').submit();
})
PHP
$image_id = isset($_POST['image_id']) ? $_POST['image_id'] : false;
Somehow the parameter needs to be send to the image page.
GET: You dont want that.
POST: You use that, but causes the refresh problem.
SESSION: Will be hidden, but cause troubles, when he opens multiple images, and then refreshing the first page.
So, i would to the following:
Use the hashtag, and load the image via javascript then. finally remove the hashtag:
MainPage:
<a class="gallery-img span4 js-img-submit" href="/image#<?=$img['id']; ?>">
<img src="img.jpg"/>
</a>
ImagePage:
<script language="javascript">
$(document).ready(function(){
var imgid = document.location.hash.slice(1);
document.location.hash = ""; //Remove
loadImage(imgid);
})
</script>
loadImage then needs to be the required javascript function.
The user might notice it for a split second. IF the user is not allowed to see, then your only way would be to use the PHP Session with seperate variables for every opened image-window.
You can do something like this:
$('.js-img-submit').click(function()
{
$.post("image.php", {id: $(this).find('input').val()});
})

returning from a form submit call to a .php file

I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.

how to get form action response without ajax in a good way?

I know how to get an AJAX response:
$.post( '/action',
{ actiontodo: 'insert' }
function (data) { alert(data); } );
Int the action.php (server side):
<?php
if ($_POST['actiontodo'] == 'insert')
{
doInsertAction();
echo "inserted";
}
?>
Finally the output of this code is an alert BOX with the word: inserted.
BUT, without ajax, I have two ways to solve this (in the server side):
ONE:
<?php
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
header( "Location: " . $_SERVER['HTTP_REFERER'] . " &response=inserted" );
} ?>
TWO:
<?php
session_start();
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
$_SESSION['response'] = 'inserted';
}
header( "Location: " . $_SERVER['HTTP_REFERER'] );
?>
Returning to the page I get the answer from the SESSION or from GET and shows the alert.
I like more the ONE solution, but each solution has a problem:
ONE problem:
The returning URL is : http://www.foo.com/myrefererurl&response=inserted
If you types this URL without using the form, you will see the alert BOX each time you will refresh the page. The question is: How to show the message only ONE time? (ONLY AFTER THE FORM ACTION)
TWO problem:
The SESSION now has the value inserted ($_SESSION['response']), when the page returns from the action obviously the solution maybe delete this value of the session like: unset( $_SESSION['response'], but SUPPOSE the UNSET do not reached for any reason (connection failure or navigation stopped by the user, etc), when you go to another form in other page the alert will showed because the $_SESSION['response'] still exists (in another form without submit it and has nothing to do with that response). Inclusively WITH GET &response=inserted in another URL the problem will exists too.
I hope you understand this questions and bring a BEST WAY solution. Basically the question is how to control that responses......
Unobtrusive JS, or "progressive enhancement" is the way to go.
Step 1:
Build your page first to work without JavaScript. Let's say you have a simple application where a user selects something and hits submit. Depending on the selection, you will either display a helpful error message above the form or you'll update the page with the correct output and hide (or get rid of) the form. Build this page like you would for AJAX, but do not script anything yet.
Here's your page:
<html>
<head>
<style type="text/css">
p#feedback { display:none;}
</style>
</head>
<body>
<div id="feedback"></div>
<div id="form">
<form action="getaction.php" method="post" id="actionform">
<select name="requestedAction">
<option value="foo">Do Foo</option>
<option value="bar">Do Bar</option>
</select>
<input type="submit">
</form>
</div>
</body>
</html>
On a successful submission. the server will get a request with one $_POST value: requestedAction=foo (or bar). Based on this, your server script will construct a new page with everything from <html> to </html>.
At this point, you have a page that works in any non-JS-enabled browser. Old fashioned. Very reliable.
Step 2
Add the scripting to override the default submit behavior. Grab the data you need from the page and construct an AJAX submission. The only difference between this and the submission above is that you will add a flag telling the server that the request is coming via AJAX and to send back only the needed message (you could also send it to a different script). The server script will basically go through the same logic as above, but rather than building the entire page, it only sends back the message string and leaves it to AJAX to put that data in the right place. Your response could be just a text fragment, a block of HTML or an XML data structure. It depends on your needs.
<script type="text/javascript">
$(enhance); // at onDOMReady, run the enhance function
function enhance() {
// Override the default form submission behavior:
$('form#actionform').bind('submit',doSubmit);
};
function doSubmit(event) {
$.ajax(
{
type:'POST',
url:'/path/to/getaction.php',
data:'request=' + $('form#actionform select[name=requestedAction]').val() + '&type=ajax',
success:fnCallback
}
);
// Kill the submit action so the user doesn't leave the page
event.preventDefault();
};
function fnCallback(xhr) {
var strResponse = xhr.responseText;
if (strResponse === "error") {
$('div#feedback').text("There was an error. Please try again.");
}
else {
$('div#feedback').text(strResponse);
$('div#form').hide();
}
};
</script>
In this case, the AJAX submission will be identifiable to the server because there is a second POST parameter of type=ajax.
A site that does this really unbelievably well on a very big scale is ESPN. Turn off JS and check out their main story headlines under the big picture. The behavior is identical to their AJAX-enabled page and aside from the video not working, you really would never know if your JS was on or off. There's basically no way to build a site like this without starting from dumb HTML and building up.

Categories