How to turn following PHP process into AJAX process? - php

On my website I give users an option to subscribe to blog authors. Right now it is a php process and requires page refresh each time user clicks "SUBSCRIBE" or "UNSUBSCRIBE" button. I was thinking that it is a time to make this process sort of AJAX based, so when users click "SUBSCRIBE" or "UNSUBSCRIBE" buttons there would be no page refresh, but their subscription arrays would be updated. therefore buttons will change respectively e.g. if user clicks "SUBSCRIBE" button it will change to "UNSUBSCRIBE" and backwards.
The problem is that I never used AJAX before and I can't find useful information to achieve this specific task, because there is a lot of it.
So could anyone suggest how to make this process sort of AJAX, so no page refresh takes place? If possible jQuery based solution would be great.
HTML & PHP for Buttons
//SUBSCRIBE Button
<?php if (($isLogedIN) && ($canSubscribe) && (!$isBlogOwner)) { ?>
<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="subscribe" value="Subscribe"/>
</form>
<?php } ?>
//UNSUBSCRIBE Button
<?php if (($isLogedIn) && ($canUnSubscribe) && (!$isBlogOwner)) { ?>
<form id ="unsubscribeform" name="unsubscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="unsubscribe" value="Unsubscribe" />
</form>
<?php } ?>
PHP to update database records
//Subscribe
if (isset $_POST['subscribe'])){
//First Update Visitors Subscription Array
if($subscription_array != ""){
$subscription_array = "$subscription_array,$blogauthid";
} else {
$subscription_array = "$blogauthid";}
$updateSubscription_array = mysql_query("UPDATE members SET subs='$subscription_array' WHERE id='$reader'") or die (mysql_error());
//Then Update blog writers subscribers array
$subArray7 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT1");
while($subrow7=mysql_fetch_array($subArray7)) {subscription_array7 = $subrow7["subscribers"];}
if ($subscription_array7 !="") {
$subscription_array7 = "$subscription_array7,$reader";
} else {
$updateSubscription_array7 = mysql_query("UPDATE members SET subscribers='$subscription_array' WHERE id='$blogauthid'") or die (mysql_error());
header("location: blog.php?id=$blogid");exit();
//Unsubscribe
if (isset($_POST['unsubscribe'])){
//First Update visitors subscription array
foreach ($subscription_array2 as $key => $value) {
if ($value == $blogauthid)
unset($subscription_array2[$key]);
}
}
$newSubArray = implode(",", $subscription_array2);
$updateSubscription_array = mysql_query("UPDATE members SET subs='$newSubArray' WHERE id='$reader'") or die (mysql_error());
//Than update blog writers subscription array
$subArray9 = mysql_query("SELECT subscribers FROM members WHERE id='$blogauthid' LIMIT 1");
while($subrow9=mysql_fetch_array($subArray9)) {subscriber_array9 = $subrow9["subscribers"];}
$subscriber_array9b = explode(",", $subscriber_array9);
foreach ($subscribe_array9b as $key9 => $value9) {
if ($value9 == $reader) {
unset($subscriber_array9b[$key9]);
}
}
$newSubArray9 = implode(",", $subscriber_array9b);
$updateblogSubsArray = mysql_query("UPDATE members SET subscribers='$newSubArray9' WHERE id='$blogauthid'") or die (mysql_error());
header ("location: blog.php?id=$blogid");exit();

Basically you want to have a JavaScript function like this:
function subscribe(id)
{
if (window.XMLHttpRequest)
{// code for real browsers
xmlhttp=new XMLHttpRequest();
}
else
{// code for abominations
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.status==200 && xmlhttp.readyState==4)
{
document.getElementById("subscribeStatus").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","blog.php?id="+id,true);
xmlhttp.send();
}
Call it and pass it the variable (id) you want with a button like this on the frontend.
<input type="button" name="click" value="Subscribe" onmousedown="subscribe(document.getElementById('id').value);">
Embed the user's ID as a hidden form field with id = "id" (or whatever).
Then on the PHP side (blog.php) just handle it with $_GET instead of $_POST. And duplicate it for unsubscribe or find a way to work it together using a switch (or if) statement.
Hope that helps.

This could be optimized a little, but it's functionality is more clear at each step and it should work. This is Jquery $.post, as requested.
You only need one form element:
<form id="subscribeform" name="subscribeform" method="post" action="blog.php?id=<?php echo $id;?>">
<input type="submit" name="subscribe" value="Subscribe"/>
</form>
At the bottom of your document, just before the closing body tag, link the jquery library, followed by the script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#subscribeform input:submit').click(function() {
// $.post is the jquery shorthand method for $.ajax - it always uses POST
$.post(
// url
'blog.php?id=<?=$id?>',
// serialized form data to POST
$('#subscribeform').serialize(),
// success callback toggles form value
function(data) {
if ($('#subscribeform input:submit').val() == 'Subscribe') {
$('#subscribeform input:submit').
attr('name','Unsubscribe').val('Unsubscribe');
}
else {
$('#subscribeform input:submit').
attr('name','Subscribe').val('Subscribe');
}
}
);
});
});

Related

Execute PHP code on button press without navigating away from page

I have a page finduser.php which is accessed by clicking a button on another page user.php. user.php is a simple form that takes a couple of parameters from an end user, submits to finduser.php which appends that user to a list.
user.php
<form action="finduser.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
finduser.php
<?php
//session start is on another page included on every page
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
?>
The way the UX handles is that you begin on user.php, submit form and are navigated to finduser.php, but if you want to keep searching for users, you need to press back and resubmit the form. I'd like a way to not redirect on form submit, but still execute the code on finduser.php.
I notice some sites use a similar concept for adding items to a cart. Some sites redirect you to the cart on adding something, but some stay on the same page without disrupting UX. A little box might appear "x has been added to cart", which lets you add multiple things from the same page to cart but without seeing the cart between.
How can I accomplish this? To reiterate what I'm trying to do:
user types a name in user.php
user presses submit, the PHP in finduser.php is executed
perhaps a box appears "[name] has been added to the list"
there are no page redirects
I could do something like the below:
user.php
<?php
//session start is on another page included on every page
if ((sizeof($_POST) == 1) && isset($_POST["username"])) {
$theUser = $_POST["username"];
if (!isset($_SESSION["users"])) {
$_SESSION["users"] = array();
} else {
$_SESSION["users"][] .= $theUser;
}
}
<form action="user.php" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
</form>
?>
This way only one page is needed, but it still needs to redirect (to itself), and is prone to disruption when someone refreshes the page for example.
You need to use AJAX to process your PHP code and return the result. Here's an option using jQuery's AJAX handler:
# File: yourform.html
<form action="finduser.php" id="findUserForm" method="post">
<input type="text" name="username" required="required"/>
<input type="submit" value="Find User"/>
<div class="messages"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#findUserForm').submit(function(e) {
// Stop the regular post action
e.preventDefault();
var $form = $(this);
// Define the request that should happen instead
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
dataType: 'json',
data: {
username: $('input[name="username"]').val()
}
}).done(function(result) {
// Append the results to the messages div
$('.messages').append('<p>' + result.message + '</p>');
});
});
});
</script>
Then your backend script to process the username:
# File: finduser.php
<?php
session_start();
if (isset($_POST['username'])) {
// do your processing...
if (empty($_SESSION['users'])) {
$_SESSION['users'] = [];
}
// Add it to the array
$_SESSION['users'][] = trim($_POST['username']);
// do more processing?
// Return a result
echo json_encode(
'success' => true,
'message' => $_POST['username'] . ' was successfully added!'
);
exit;
}
// Handle errors!
echo json_encode(
'success' => false,
'message' => 'No username was posted.'
);
I haven't tested this, but the idea is that you tell jQuery to override the default way it handles that form being submitted, and instead it should send the username via AJAX to finduser.php. That script will do things that you tell it to, add the user to the session array, then output a JSON result message. jQuery's .done() event then processes that result message and adds the message to the .messages div.
You can use the success => bool option to control how the messages might display, for example:
.done(function(result) {
var $elem = $('<p></p>');
// Add a CSS class for display
if (result.success) {
$elem.addClass('success');
} else {
$elem.addClass('error');
}
// Append the results to the messages div
$elem
.html(result.message)
.appendTo($('.messages'));
});
Then add some CSS like so:
.success {
color: green;
}
.error {
color: red;
}
In theory, your result messages should then be colour coded.

I need to grab the $_GET['loc'] that is sent via AJAX

I have an index.php page where there are 2 kinds of queries first is location and secondly the search query. I am using ajax on location query
html structure :
<ul class="dropdown">
<li>City</li>
<li>North</li>
<li>South</li>
</ul>
<form action="" method="post">
<input type="text" name="search" id="search">
</input value="submit" type="submit"/>
</form>
<div id="content_from_AJAX">
<ul id="li_start">
</ul>
</div>
The ajax.js code :
$(document).ready(function(e) {
function getLoc(param){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("li_start").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getresult.php"+param,false);
xmlhttp.send();
}
//handle anchor clicks
$("ul#location li a").click(function(){
var loc = $(this).attr("href");
getLoc(loc);
return false;
});
});
the getresult.php code :
require ('connect_to_mysql.php');
if(isset($_GET['loc']) && empty($_GET['loc'])===false){
$loc = mysql_real_escape_string($_GET['loc']);
$query = "SELECT * FROM TB_name WHERE loc=";
}
else{
$query = "SELECT * FROM TB_name";
}
$query_run = mysql_query($query);
$count = mysql_num_rows($query_run);
if($count<1){
echo 'no result found';
}
else{
while($result == mysql_fetch_assoc($query_run)){
echo "ALL results";
}
// Here is what I want to be able o access on index.php
return $_GET['loc']
}
I want the $_GET to be accessed on index.php so I can use it to filter result on search queries on the form above ie:
"SELECT * FROM `TB_name` WHERE `keyword` LIKE '$keyword' AND `loc`='".$_GET['loc']."'"
//I need to do this on index.php not on getresult.php
And also I want the AJAX.js to send queries on getresult.php if a user clicks on the loc links if the $_POST['search'] isset.
Please help really need this project and I am starting to be so depressed X_X.. Thank you any help is appreciated alot :)
change this
xmlhttp.open("GET","getresult.php"+param,false);
to
xmlhttp.open("GET","getresult.php?loc="+param,false);
^^^^ // forgot ?loc=
then use $_GET["loc"] in your getresult.php page.
Why have you put your function in document.ready() ?
If it would be me then i would have done like this
function getLoc(param){
$.get('getresult.php',{loc:param},function(data){
//Do some stuff with data
});
}
Your code needs some rethinking. You have a dropdown with href links in it and a form that submits information (which it shouldn't if you want ajax results).
And why is your getresults.php doing a database query and then returning the GET variable back. That makes no sense, because the database query is now pointless as its results are not used for anything.
What I think you want is onClick event listeners on the dropdown, and then have an Ajax request fire on each change, the getresults.php file then does a MySQL search and returns the results of the search (not $_GET['loc'] as index.php already knows this value).
Also, use mysqli* or PDO for your database queries, the mysql* set of functions are now deprecated and prone to sql injection.

HTML form post to PHP call using AJAX

I'm trying to POST and email address entry from a HTML form to a PHP script to store the result in a database. The script is also responsible for firing an error message should the user enter an invalid email address etc. I would like the whole process to involve an AJAX call so that the page doesn't have to be reloaded each time that the user hits the submit button on the form.
As of now, each time the user hits the form submit button the page is being refreshed and i'm getting a response from the ajax call but it is immediately being written over due to the refresh.
Here's my HTML and Javascript/ajax:
<div id="emailform">
<form method="post"><!--action="planethome.php"-->
<input class="emailinput" type="text" name="email" maxlength="80" placeholder="enter your email address"/>
<input class="submitemailbutton" name="send_button" type="submit" value="Send" onClick="ajaxFunction()/>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
</div>
<div id="errororsuccess">
</div>
<!--ajax stuff:---------------------------------->
<script language="javascript" type="text/javascript">
//Browser Support Code"
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Ajax is struggling in your browser.");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('errororsuccess').innerHTML = ajaxRequest.responseText;
}
}
// Create a function that will receive data sent from the server
ajaxRequest.open("POST", "addemailtodatabase.php", true);
ajaxRequest.send(null);
}
and here's my PHP:
<?php
require_once ('planetconfig.php');
if (isset($_POST['submitted'])) { /
require_once (MYSQL);
$email = FALSE;
$trimmed = array_map('trim', $_POST);
if (!empty($_POST['email']))
{
if (preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[#][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$_POST['email'])) {
$email = mysqli_real_escape_string ($dbc, $trimmed['email']);
} else {
echo "Invalid";
}
} else {
echo "You need to enter an email address";
}
if ($email) {
$q = "INSERT INTO planetemail (email, time) VALUES (AES_ENCRYPT('$email', 'password'), NOW())";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_affected_rows($dbc) == 1) {
echo "Thanks, we'll be in touch";
exit();
} else {
echo '<p class="error">We\'re sorry, something has gone wrong.</p>';
}
}
mysqli_close($dbc);
}
?>
I'm sure it's something to do with my POST method or how I have my ajax call set up.
I'm new to all this, can anyone tell me what I'm doing wrong or suggest a better implementation. I have a deadline of tomorrow morning to have this done.
You're problem is that you are using a submit button. The submit button will submit the form, change it from a type="submit" to type="button" and it will work and as #juzerali suggested, use jQuery, that code hurts my head.
1st, yes that is awful, use jquery. 2nd although you have bound ajax call with onclick of submit button, you have not prevented the default behaviour from executing. The form will still get submitted the usual way.
if (isset($_POST['submitted'])) { /
There is a stray / in your code.
Also, Change type="submit" to type="button"
The onClick event handler will pick up the submit becuase you are making an AJAX request, no need to POST.
return false; at the end of the script to keep it from submitting the normal way.

How do I submit a POST variable with Javascript?

So I am trying to submit a variable and the name of the variable via a form. I switched a button from submit to button because I need additional validation.
Anyway, here's the button now:
<button type="button" onclick="subForm()" name="del" id="deletebutton" value="'.$org.'">Delete</button>
Here's my current validation:
<script type="text/javascript">
function subForm()
{
if(confirm("Are you sure you want to delete this?"))
document.forms["addorg"].submit();
else
return false;
}
</script>
And here's my script on the other side:
if (isset($_POST["del"]) && ($_POST['del'] !== '')) {
$del = mysql_real_escape_string(html2txt($_POST['del']));
$resfile = mysql_query('SELECT file_loc from organization WHERE org_id = '.$del);
$org_name = mysql_real_escape_string(html2txt($_POST['orgname']));
if (!$resfile)
header('Location: '.$admin.'?error=query');
while ($filerow = mysql_fetch_array($resfile)) {
$fileplace = $filerow['file_loc'];
unlink(".".$fileplace);
rmdir($org_name);
}
mysql_query("DELETE from organization where org_id='".$del."'");
header('Location: '.$admin);
}
It is not currently deleting the records that I want. How do I pass along the "del" name to the other page?
You can use <input type="hidden">:
echo '<input type="hidden" name="org_id" value="'.$org_id.'" />'
This should render something like:
<input type="hidden" name="org_id" value="1" />
Using this code you can access the hidden field data using:
$org_id = $_POST['org_id'];
instead use onsubmit
<form method='POST' onsubmit='return subForm();'>
and
<script type="text/javascript">
function subForm()
{
if(confirm("Are you sure you want to delete this?"))
return true;
else
return false;
}
</script>
edit:
you can also change
if (isset($_POST["del"]) && ($_POST['del'] !== '')) {
to
if ( !empty($_POST['del']) ) {
but i think this line is your problem
$resfile = mysql_query('SELECT file_loc from organization WHERE org_id = '.$del);
try
$resfile = mysql_query("SELECT file_loc from organization WHERE org_id = '".$del."' ");
Looking at http://www.w3schools.com/tags/tag_button.asp suggests that the 'name' of a button isn't submitted as opposed to its 'value' or 'text'. Why not use an input of type hidden as just suggested?
I suggest you rethink using a form at all and consider AJAX. This would solve the problem of knowing which button was clicked and the page doesn't need to reload.
Here is a sample of what you're trying to do:
<html>
<head>
<script type="text/JavaScript">
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
function deleteOrganization(orgID)
{
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// in your PHP file, have it echo something like "SUCCESS" or "FAIL", and the response will be alerted here
alert(xmlhttp.responseText);
refreshList(); // either call another function to update the list or return the new list after the success/fail response.
}
};
xmlhttp.open("GET", "delete.php?orgID="+ orgID, true);
// OR - xmlhttp.open("GET", "page.php?action=DELETE&orgID="+ orgID, true);
xmlhttp.send();
}
function refreshList()
{
// either delete the row with JavaScript or make another AJAX call to get the new list after the entry was deleted.
}
</script>
</head>
<body>
<button onclick="deleteOrganization('<?php echo $org; ?>')">Delete</button>
</body>
</html>

What's wrong with this PHP/JavaScript form validation?

I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.

Categories