Blog post comment without page refresh (ajax) - php

I'm trying to make comments on my page just like the ones in wordpress. When you press post comments your page updates without reload. How can I do that?
I understand I have to use jquery post, and I've had several attempts but for some reason my web page keeps reloading. I have a form like this :
<form name="postForm" id="postForm" action="addComments.php" method="post">
<textarea name="commentContent"></textarea>
<input type="submit" name="commentButton" id="commentButton">
</form>
I tried $("#commentButton").click(function() do something .. but I still get the page reload. I mean I have the php part ready, working with page reload like an ordinary form just fine, just I'd like to learn and do this without page reload. Any idea how can I make this happen?

try using http://www.malsup.com/jquery/form/. It is jQuery plugin to submit form without page load... hope it will help you..

There is a great tutorial I found while i was searching something similar like adding, deleting comments without page refresh.
http://www.9lessons.info/2009/11/insert-delete-with-jquery-and-ajax.html

You must return false from the click handler function to prevent default browser action – which is, submit the form. So your handler might look something like this:
$("#commentButton").click(function() {
...do your stuff...
return false;
});
Or you can bind to the submit event also:
$("#postForm").submit(function() {
...do your stuff...
return false;
});

$('#postForm').submit(function() ...

Related

cakephp 3.0 submit part of form

is there way to submit part of a form without refreshing the whole page? Basically, I want to add a search box with a button in the view, when I click this button it runs a function / action in the controller. My apology if this has been asked before but I've searched for couple of hours and I couldn't understand the ones I came across.
This page will help you learn about how CakePHP handles AJAX:
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html
Now, be aware the default behavior of a form is submit itself to a page or to the same page (reloads). If you want to prevent the form from submitting (reload the page) have something like this:
<form onsubmit = myFunc() >
..
function myFunc(){
//Send the ajax request. You can use JQuery
//Handle response
return false; //This will prevent the page reload...
}

Disable submit button after click and keep POST/REDIRECT/GET working

I use the POST/REDIRECT/GET trick to prevent refresh-resend of forms.
Now I would like to disable a form submit button (after click) that should not be clicked twice.
Although I tried all javascript examples I found, they all conflict with POST/REDIRECT/GET.
In most cases it doesn't even submit but just redirects to itself.
Any solution ? Thanks for your help.
Something I've tried and conflicts is this example:
the script first runs headers.php with this in:
if (isset($_POST['start-diff-scan']))
{
$_SESSION['SCAN_START'] = true;
header('HTTP/1.1 303 See Other');
header('Location: '.APP_URL.'scan.php');
exit;
}
and then scan.php with this form:
<form name="start-diff-scan" id="start-diff-scan" method="post">
<button
name="start-scan"
id="start-scan"
value=""
class="start-scan btn btn-primary"
type="submit"
method="post">
Start New Scan
</button>
</form>
and works fine. but the js trick conflicts this. I added the js code at the very end of scan.php
<script>
$('#start-diff-scan').submit(function()
{
$('#start-scan').prop('disabled', true);
});
</script>
What happens is it only redirects to the same page (scan.php) without executing anything.
Thanks for all yoru answers and help so far this is great.
Any ideas appreciated thanks very much
You cannot prevent it this way, since it's user-side scripting, and people can easily delete this code, before sending the form. Even you disable the button. Make checks in your server-side script, whether the request is already inserted, so you will display them either an error, or get them back to the page
$('#start-scan').attr("disabled", true);
Should work
If the "disable" method is messing up your code and all else fails :
You can try to overlay the button with a "loader gif" making it not clickable.
$('#start-scan').click(function()
{
$('#start-scan').before('<div>LOADING</div>'); //Set the loading overlay width, height and background-color
});
The problem you have is setting the disabled when the person clicks causes the button to be disabled and the click action does not fire off.
Add a setTimeout to delay setting the disabled property.
Other option is to hide the button and replace it with text that says submitting.
$('#start-scan').attr('disabled', true);
or use
.prop("disabled", true)
$('#start-scan').prop("disabled", true)
You can just add this in the form:
onClick="this.disabled=true"
try prop()
$('#start-scan').prop('disabled', true);

PHP onSubmit action on an <a>

So basically my question is very simple, I have two buttons, I for page forward, one for page backwards, If one of those is pushed, a javascript function is called inside an onClick Event. Javascript then gets the variables of the page and then redirects to the next page, the only problem is, that I need to pass those variables to PHP in order to put them into the Database. So for that I make a load of cookies to pass the variables.
However, I was wondering if something like this would work :
<form>
<a onClick="nexpage();" onSubmit="phpScript.php"> <img src = "previous button.jpg"/> </a>
</form>
The idea behind this is that I want to store the variables in a PHP script, which will put them in a display:none; <div> and then for javascript to get the variables out. This instead of using cookies.
So is it possible to run a PHP script to get the variables and when the script is finished to get them, Javascript kicks in to redirect to the next page...
The reason I don't test this at this moment, is that my code is 100% complete, I don't want any sudden changes that maybe won't work at all. Yes I know back-up this and that, but I thought just asking here, maybe someone will know the answer!
Sincerly,
Harmen Brinkman
You can also use onClick = "this.form.submit(); return false;".
There is no any event like onSubmit for link, instead form do have onSubmit event.
Normal Way as OP asked.
<form action = "phpScript.php" method = "POST">
you can use document.getElementById("my_form").submit();
#Dipesh Parmar – Good point. You could also do:
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
// do what you want with the form
// AJAX POST CALL TO PHP PAGE
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
});
Inspiration by Capture a form submit in JavaScript

Do browsers support autocomplete for ajax loaded login forms at all?

My problem is, that the browsers' (IE&FF) autocomplete does not work for my login form.
I have a webapp with CakePHP & jQuery. To allow visitors to login/register unobtrusively. The login form is inside a div, which is loaded via AJAX. (This enables logging in without a page reload.)
The browsers do recognize it as a login field, as they prompt me to save the credentials when clicking login. And they really do save the username/password, as they appear between the saved ones in the browser settings. But the saved username/password is never entered automatically. They do not appear pre-entered when the page loads. When I start typing in the username, the username appears as a suggestion, but even when you select it, the password is not entered next to it. Why? How can I get this working?
That you can test it yourself, here is a simple AJAX login form:
http://gablog.eu/test/ajaxlogin.html
It loads the following login form, if you go to the url below, autocomplete will work for just the plain form, so it is not a problem with the form itself, but rather that it is AJAX loaded:
http://gablog.eu/test/loginform.html
The layout:
<div id="user-bar">
<script type="text/javascript">
$(function() {
$("#user-bar").load('loginform.html').html();
});
</script>
</div>
The view loaded (when not logged in):
<form id="form-login" action="" onsubmit="login(); return false;">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" value="Login"/>
<div id="login-error" class="error-message"></div>
</form>
<script type="text/javascript">
function login() {
$.post('/ajax/login', $("#form-login").serialize(), function(data) {
if (data.success) {
$("#user-bar").load('userbar.html').html();
} else {
$("#login-error").html(data.message);
}
}, "json");
}
</script>
To clarify: I do not want to use AJAX autocomplete, I want the browser's autocomplete to work for my login form. This is an issue between my form and the browser. jQuery submission seems to play a minor role, as the usernames/passwords are saved. They are just not auto-entered for ajax loaded HTML elements! (The test site does not use jQuery submission.) Related question: browser autocomplete/saved form not work in ajax request
Autocomplete, in Firefox at least, triggers during page load. Adding the content afterwards would miss the window of opportunity.
A login form is tiny. I'd include it in the page from the outset and consider hiding it with CSS until it is wanted.
In case it helps, msdn says (towards the bottom of the page):
Note: if both of the following
conditions are true:
The page was delivered over HTTPS
The page was delivered with headers or a META tag that prevents
caching
...the Autocomplete feature is
disabled, regardless of the existence
or value of the Autocomplete
attribute. This remark applies to IE5,
IE6, IE7, and IE8.
I've emboldened the interesting bit.
.
I don't think you can get the form autocomplete to work if you load the form via ajax (security-wise I don't know if it can be really be abused or not, but the fact that a script could start loading fields into the page to see what data gets inserted doesn't look too good to me).
If you can, the best option would be to add a conditional block to the php file and include the form or not depending on whether the user is logged or not. If for some reason you can't do that, you might want to try to do a document.write() instead of the ajax call (and yes, using document.write is ugly :)
I see case when login form has to be pulled with ajax - if rest of the website loads as static html (cache). Login form (or authed user info) cant be displayed statically.
So your solution is to pull the form right after declaration (end tag) of the DOM element that serves as parent element for ajax-pulled loginform's html, ex:
<div id="loginforms_parent"></div>
<script language="javascript">
/* ajax request and insert into DOM */
</script>
And browser has the form in DOM onLoad. Tested, firefox does autocomplete in that case.
I'm not happy with loading the login form into my page at load time so I filed a issue with Chrome instead;
http://code.google.com/p/chromium/issues/detail?id=123955&thanks=123955&ts=1334713139
there is answer given : http://www.webmasterworld.com/javascript/4532397.htm . it does something with submit method and then uses click method. as i know values are not saved if form is not submitted. i think author of that solution just makes it submitted though submit button is not clicked by user.

Changing the address of the website, as per the php being used

I have a button in my abc.html page
<input type="button" onclick="javafun();">
on the click it goes to javascript, which further send info to my abc.php ...and the javascript function looks like:
function login()
{
xmlhttp=GetXmlHttpObject();
//alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="login.php";
url=url+"?id="+username+"&passwrd="+passwrd;
xmlhttp.onreadystatechange=statechangedLogin;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
function statechangedLogin()
{
//alert(xmlhttp.readyState);
if(xmlhttp.responseText=="<font color='red'>Your User Name or Password is incorrect. Please try again.</font>")
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
else
{
//hwin=window.location="http://forum.research.bell-labs.com/zeeshan/qotw/login.php";
document.getElementById("mainbody").innerHTML=xmlhttp.responseText;
//hwin.document.innerHTML=xmlhttp.responseText;
//alert();
}
}
Everything works fine, but the address of the website in the address bar remains the same:
http://severname.com/abc.html
i want this address bar to change, according to the php. it should come to ...
http://severname.com/abc.html/login.php
but still should not show ?id=username&passwrd=passwrd
Is this possible, and if it is how??
Zeeshan
POST the request to ../login.php ?
instead of using ajax, wrap your form elements in
<form method=POST action="login.php">
User Name: <input name="username"><br>
Password: <input name="passwrd" type="password"><br>
<input type="submit" name="Login">
</form>
Why are you doing AJAX if you want the address bar to change?
Edit
Added real values to the form
Edit 2 More clarity.
You really should do the login via form (see #nathans post).
Rename your html login form into a php page. Lets call it loginForm.php.
Remove all the javascript functions from loginForm.php
Insert the form into loginForm using the form tag.
In login.php, you check to see if they user logged in successfully,
If the login suceeded:
$failMsg = urlencode("Logged in successfully")
header("Location: loginForm.php?okMsg=$msg&redirect=home.php");
If the login failed:
$failMsg = urlencode("Failed to login")
header("Location: loginForm.php?failMsg=$msg");
In your loginForm.php where you are displaying your error messages now, put:
<? echo htmlentities($_REQUEST['failMsg']);?>
In loginForm.php where you are displaying success log in message put
<? echo htmlentities($_REQUEST['okMsg']);?>
And in the head tag put
<? if(array_key_exists($_REQUEST,'redirect'))
{
echo "<meta http-equiv='refresh" content='5;url=/".$_REQUEST['redirect']."' />";
}
?>
There no javascript and the user gets nice pretty error messages and is forwarded to the home page after logging in.
<form method="post" action="login.php">
You don't need AJAX to do that at all. If you're using the Javascript to validate the input you can add onSubmit="return my_validation_function() ... your validation function should return true if everything was okay or false if it was not. (The false return value will stop the form from submitting)
It sounds like you don't want AJAX at all, just a regular form, unless I'm missing something.
I think you have misunderstood the whole point of AJAX. Ajax is supposed to work in the background, i.e. not changing the url. If you want that, try document.location="foobar";
Ajax hides JS interaction with your server. That's what is for. If you want your browser to point to some URL, then you shouldn't use Ajax.
The thing you're trying to archieve can be easily implemented using a simple POST request, using the good old <form>.
HTTP POST requests hide the parameters of the request from the URL, passing them inside the header of the message itself. So URLs can be clean.
As other commenters have touched upon, the real answer is that you can't change the URL of a web page (other than the "#" fragment identifier, but that's not useful to you) without causing the browser to send a request to that url.
You want to not bother trying to change the URL if you're submitting via AJAX. Or, you can make a post request as suggested in other comments.
<form method="post" action="login.php">
Your method is somewhat insecure and vulnerable to some scripting attacks. I'd look at not doing an Ajax login and just use a regular form as well. This article helped me a ton:
http://www.evolt.org/PHP-Login-System-with-Admin-Features
Evolt has another one that looks similar to what you were trying to accomplish, but I've not read it -- just Google "evolt ajax login"

Categories