PHP - Autoupdate With Php/ajax
Hey guys.
I was hoping that someone could tell me how i could make an auto update sort of thing. my php: for($i = $num; $i <= 100; $i++){ //lots more code here echo $i } But what i want it to do is echo $i once the code has finished then when it dose it agien it replaces $i with the new $i Thanks JRagon Similar TutorialsHello again; I'm trying to build a little php site and some with mysql, when a record is saved on the DB i want a column with the timestamp. I've been doing a bit of reading and *i think* the database part is done but i cant figure how the insert should be done. The column on mysql is: Type: timestamp Default: current_timestamp Attributes: on update current_timestamp The structure on the table is: id, timestamp, column1, column2. I thought that since it is 'on update current_timestamp' it would fill itself properly, but when i do my insert: $query = "INSERT INTO tbl_process VALUES ('','','$value1','$value2')"; mysql_query($query) or die ("Error in query: $query " . mysql_error()); The only saved value is "0000-00-00 00:00:00" so obviusly i'm missing something... for extra points: the 'id' value is autoincrement so on the insert i just leave the value empty with ''. Is that the "correct" way of filling that field or is there a "best practice" for that? Thanks everyone Right now I redirect to index page after I delete a record. However I am looking to make it so that I can delete a record without redirecting the page. I know this can be accomplised using Ajax. I have spent countless hours before trying to make it work, but it did not work.
So here is a basic setup I created. Can you please update it with ajax code so that I can see how it's done properly?
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div class="record" > <a href="record.php?id=<?php echo $record_id ?>"><?php echo $record_name; ?></a> <div class="delete-record"> <a href="delete.php">Delete Record</a> </div> </div> </body> </html> Edited by man5, 18 August 2014 - 08:55 PM. Now I'm having this strange issue with my website I'm currently working on a tester system and I've encountered a problem that I'm unable to find the issue, tho I'm thinking my ajax php part of the script to be the thing causing it even tho it seems strange that it would cause it. The first part which is connected to where the problem occurs is the echo"<form>"; and from there, It should take you to index.php?page=tester&select=answer, now that is where it in the browser goes there tho it still shows the page stuff from the last page which is index.php?page=tester&select=applications, so it's like showing both &select=answer and &select=applications on the same page. <?php $q=$_GET["q"]; include'../config/connection.php'; $result = mysql_query("SELECT * FROM applications WHERE id = '$q'"); echo "<center><table border='1'> <tr> <th>Account Name</th> <th>Character Name</th> <th>Gender</th> <th>Skin Color</th> </tr>"; $row = mysql_fetch_array($result); echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['charactername'] . "</td>"; echo "<td>" . $row['gender'] . "</td>"; echo "<td>" . $row['race'] . "</td>"; echo "</tr></table></center>"; echo"<br/>"; echo"<table><tr> <th>Description</th> <th>Metagaming</th> <th>Powergaming</th></tr>"; echo"<tr>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['description']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['mg']."</textarea></td>"; echo "<td><textarea readonly='readonly' style='width:22em; height:20em;'>".$row['pg']."</textarea></td>"; echo"</tr></table><table><br/><center><h1>Answer</h1><br/><form action='index.php?page=tester&select=answer' method='post'>"; echo"<textarea name='why' style='height:10em; width:60em;'></textarea><br/>"; echo"<input type='submit' name='answer' value='Accept' /><a/>"; echo"<input type='submit' name='answer' value='Decline' /></center>"; echo"<input type='hidden' name='id' value='$q'/>"; echo"</form></table>"; ?> Now on &select=answer it included a page which the script of that include consist of the stuff below, it outputs that the query was successfully, and all that. <? if(!empty($_POST['why'])) { $why = mysql_real_escape_string($_POST['why']); $answer = trim($_POST['answer']); $id = $_POST['id']; if($answer == "Accept") { $query1 = mysql_query("UPDATE characters SET accepted = '1' WHERE id = '".$id."'"); echo"Successfully accepted"; $answer = 1; } elseif($answer == "Decline") { echo"Successfully declined"; $answer = 0; } $query = mysql_query("UPDATE applications SET answer = '$why' AND tester = '".$_COOKIE['Username']."' AND accepted = '$answer' AND answered = '1' WHERE cid = '".$id."'") or die('Could not connect: ' . mysql_error()); if($query) { echo"<br/>Query went through without problems"; header("Refresh: 5;url=index.php?page=tester"); } } ?> This is the ajax part javascript of it which gets the information for index.php?page=tester&select=applications Code: [Select] <script type="text/javascript"> function showApplication(str) { if (str==""||str==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","tester/applications.php?q="+str,true); xmlhttp.send(); } </script>If you need any more information feel free to ask for it. Thanks in advance. Hello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb As the title say, I can not for the life of me get the "$bank" content to display, no matter HOW much I try... Does anyone see any errors. I am sooooooo wiped out at this! main page <? $body = ' <script type="text/javascript" src="change-content.js"></script> <div id="addSold"> <form action="'.$_SERVER['REQUEST_URI'].'" method="post" name="form" autocomplete="off"> <fieldset id="Vehicle"> <legend>Vehicle</legend> <ul> <li><label for="Year">Year</label>'.$Year.'</li> <li><label for="Make">Make</label>'.$Make.'</li> <li><label for="Model">Model</label>'.$Model.'</li> <li><label for="Trim">Trim</label><input type="text" name="Trim" id="Trim" size="10" value="'.$trim.'" disabled="disabled"></li> </ul> <ul> <li><label for="Mileage">Mileage</label><input type="text" name="Mileage" id="Mileage" size="5" maxlength="6" value="'.$row['mileage'].'"></li> <li><label for="VIN">VIN</label><input type="text" name="VIN" id="VIN" size="23" maxlength="17" value="'.$row['vin'].'" disabled="disabled"></li> <li><label for="Color">Color</label>'.$Exterior.'</li> </ul> </fieldset> <fieldset id="Deal"> <legend>Deal</legend> <ul> <li> <label for="soldDte1">Date</label> <input type="text" name="soldDte1" id="soldDte1" size="1" maxlength="2" onkeyup="return autoTab(this, 2, event)" value="08"> / <input type="text" name="soldDte2" id="soldDte2" size="1" maxlength="2" onkeyup="return autoTab(this, 2, event)" value="30"> / <input type="text" name="soldDte3" id="soldDte3" size="1" maxlength="2" value="'.$year.'"> <a href="#"><img id="date_'.$row[stock].'" src="images/Icons/dateOff.png" onfocus="this.select();lcs(this)" onmouseover="MM_swapImage(\'date_'.$row[stock].'\',\'\',\'images/Icons/dateOn.png\',1)" onmouseout="MM_swapImgRestore()" alt="Choose Date"></a> </li> <li> <label for="salesman">Salesman</label> <select name="salesman" id="salesman"> <option></option> '.$salesmen.' </select> </li> </ul> <ul> <li> <label for="dealType">Deal Type</label> <select name="dealType" class="select-content" onchange="getFile(this.value)"> <option></option> <option value="AL">Auto Loan</option> <option value="Cash">Cash</option> <option value="CAC">Credit Acceptance</option> <option value="IH">In House</option> <option value="SAL">Sensible Auto</option> </select> </li> <li> <label for="tradeDrop">Trade</label> <select name="tradein" id="tradeDrop" onchange="show_hide_trade(this.value);"> <option value="No">No</option> <option value="Yes">Yes</option> </select> </li> </ul> </fieldset> <div id="Bank" class="view">'.$bank.'</div> </form> </div> '; ?> get_Bank.php <? if ($_GET['dealType'] == "AL") { $bank = ' <fieldset id="AL"> <legend>Auto Loan Figures</legend> <ul> <li><label for="price">Price</label><input type="text" name="price" id="price" class="price" size="7" onchange="currency(this)"></li> <li><label for="down">Down</label><input type="text" name="down" id="down" class="price" size="6" onchange="currency(this)"></li> <li><label for="tax">Tax</label><input type="text" name="tax" id="tax" class="price" size="6" onchange="currency(this)"></li> <li><label for="reg">Plates</label><input type="text" name="reg" id="reg" class="price" size="4" onchange="currency(this)"></li> <li><label for="gap">Gap</label><input type="text" name="gap" id="gap" class="price" size="4" onchange="currency(this)"></li> </ul> <ul> <li> <label for="pymtNum">--------------- Payment ---------------</label> <input type="text" name="pymtNum" id="pymtNum" size="3" maxlength="3" onkeyup="return autoTab(this, 3, event)"> @ <input type="text" name="pymtAmnt" id="pymtAmnt" class="price" size="5" onchange="currency(this)"> per <select name="pymtType"> <option value="Weekly" selected="selected">Week</option> <option value="Monthly">Month</option> </select> </li> <li><label for="APR">APR</label><input type="text" name="APR" id="APR" class="rate" size="6" value="19.00"></li> </ul> </fieldset> '; } elseif ($_GET['dealType'] == "CAC") { $bank = ' Credit Acceptance stuff goes here '; } else { $bank = 'You must choose a bank before continuing'; } ?> change-content.js Code: [Select] window.onload = init; // finds all <select> tags will class="select-content" and activates function function init() { var sel = document.getElementsByTagName("select"); for (var i=0; i<sel.length; i++){ if (sel[i].className == "select-content") { sel[i].onchange = getFile; } sel[i].selectedIndex = 0; } } function getFile (url) { var url = "AJAX/get_Bank.php?dealType="+ this.value; if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();} else {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} xmlhttp.open("GET",url,false); xmlhttp.send(); // a loop that looks through all <div>s on the page // and then replaces the id with the value and gets that file var divs = document.getElementsByTagName("div"); for (var i=0; i<divs.length; i++) { if(divs[i].id == "bank") { divs[i].id = this.value; divs[i].innerHTML=xmlhttp.responseText; } } } Hi guys, I am after some simple code/tutorial that shows how to make an AJAX/jQuery function to fetch data from a PHP MySQL Database on a timed interval. So far I have not been able to find a simple example of this so if anyone can help out that would be very much appreciated. Cheers in advance. i have a select box and need to change the data with the selection.it is working correctly , my problem is that in the data i have a paging .when we going to next page no data showing . ie select box will not have any value. how to solve this problem. thanks in advance Just thought I would ask as I see that the AJAX help board is something of a ghost town (much like the MS SQL board). Since my post there doas also have some php in it, and I am in no way certain my problem is not in the php could anyone that knows a bit of both please have a look at it he http://www.phpfreaks.com/forums/index.php?topic=343419.0 cheers, just hope this circumvents the double posting rule How should I structure XMLHTTPRequests? Should I create a controller called Ajax and post/get all ajax calls through the methods of that controller? What have other people done in the past? What worked best for you? Hi folks, i am trying to impliment a ajax php search function to my site, but just stuck on how to prevent a undefined variable Here is thee ofending code: <?php $con = mysql_connect("localhost", "root", ""); if (!$con) { die('<p>There seems to be a problem, please try again soon.</p>'); } $db_selected = mysql_select_db("database",$con); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 $sql="SELECT * FROM simp_search WHERE `sbody` LIKE '%{$q}%' OR `varia` LIKE '%{$q}%' OR `stitle` LIKE '%{$q}%' ORDER BY `stitle`"; $result = mysql_query($sql); if (mysql_num_rows($result) < 1) { $error[] = "<p>Please try another search..."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($result)) { $results[] = "{$i}:<a href=\"http://www.mysite/{$row['url']}\">{$row['stitle']}</a><br />{$row['sbody']}<br /><br />"; $i++; } } function removeEmpty($var) { return (!empty($var)); } if ($results > 0){$output = "<p>Your search term: " . $q . " returned:<br><br>" . implode("", $results); } else {$output= "No results found!";} echo "$output"; ?> At the moment its a mishmash of code from other applications. Works fine if you insert a search term that is in the database, however if you enter something that doesnt match, the output is: Notice: undefined variable: results in C:\www\website\livesearch.php on line 35 No results found! Any ideas on what to change to prevent this? Also i know there is some code in there that is not needed. Ok, so I am new to Ajax and am making a forma that will check the user etc. Seems easy, but wow, I'm just lost with all the different things I'm reading, but I know exactly what I want and can easily do it in PHP but of course that is slower and reloads the page. But I am trying to really secure my page so I am stripping everything before it gets to anywhere on my site, even the ajax. So this is what I am doing. My form on index.php Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="js/runonload.js"></script> <script type="text/javascript" src="js/checkcreateuser.js"></script> <link href="css/check.css" media="all" type="text/css" rel="stylesheet"> </head> <body id="mysite"> <form method="post" id="registerForm" name="create_form" action="index.php"> <input type="hidden" name="action" value="create" /> <table width="290px"> <tr> <td align="right"> User Name: </td><td> <input name="usernamecreate" id="usernamecreate" class="sign_up_input_area" type=text value=""> </td> </tr><tr> <td align="right"> Password: </td><td> <input name="passwordcreate" id="passwordcreate" class="sign_up_input_area" type=password value=""> </td> </tr> </table> <input type="submit" class="submitButton2" name="Login" value="Create Account"> <div id="error_log"> <label class="error" for="usernamecreate" id="username_error">Username is required.</label> <label class="error" for="usernamecreate" id="username_error2">Username is already in use.</label> <label class="error" for="passwordcreate" id="password_error">Password is required.</label> </div> Then I want my javascript to work, which does work right now, but only for empty values. I want to be able to compare if the user is in the database and for other PHP functions. Like Would I put this in a seperate checkcreate.php file? Code: [Select] $usernamemain1 = trim($_POST['username']); $usernamemain = stripslashes(strip_tags($usernamemain1)); $usernamecheck = mssql_real_escape_string($usernamemain, $link); $username_lower = strtolower($usernamecheck); $sql = "SELECT LoweredUserName FROM Users where LoweredUserName = '$username_lower'"; $sql_result = mssql_query($sql); $login_row = mssql_fetch_assoc($sql_result); $username = $login_row['LoweredUserName']; $passwordmain1 = trim($_POST['password']); $passwordmain = stripslashes(strip_tags($passwordmain1)); $passwordcheck = mssql_real_escape_string($passwordmain, $link); so I want to be able to use thos evariables in my checkcreateuser.js which is settup like Code: [Select] $(function() { $('.error').hide(); $('input.sign_up_input_area').css({backgroundColor:"#FFFFFF"}); $('input.sign_up_input_area').focus(function(){ $(this).css({backgroundColor:"#FFDDAA"}); }); $('input.sign_up_input_area').blur(function(){ $(this).css({backgroundColor:"#FFFFFF"}); }); $(".submitButton2").click(function() { // validate and process form // first hide any error messages $('.error').hide(); var username = $("input#usernamecreate").val(); if (username == "") { $("label#username_error").show(); $("input#usernamecreate").focus(); return false; } if (<?echo $username_lower?> == "<?echo $username?>") { $("label#username_error2").show(); $("input#usernamecreate").focus(); return false; } var password = $("input#passwordcreate").val(); if (password == "") { $("label#password_error").show(); $("input#passwordcreate").focus(); return false; } var dataString = 'username='+ username + '&password=' + password; //alert (dataString);return false; $.ajax({ type: "POST", url: "", data: dataString, success: function() { $('#contact_form').html("<div id='message'></div>"); $('#message').html("<h2>Form Submitted!</h2>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); return false; }); }); runOnLoad(function(){ $("input#username").select().focus(); }); I can't get the if (<?echo $username_lower?> == "<?echo $username?>") to use variables, of course they aren't seeing any of the variables because I don't know if I put this into a different file, then point my form action to that file and the ajax then sees it run or what? I'm really confused on it all, if anyone can help out that would be great. All the tutorials I keep finding are the same things over and over and don't really help because they always leave out various parts they are using or doing. I understand this much so far tho, but how do I do the variables in ajax when it posts type thing? Thanks!!! Please help me in this guys....... I am using MVC model for my application . I am stuck with the ajax call. this is my controller application/controller/admin/index.php function getCity() { $city=$this->model->getCity(); foreach($this->city as $key => $value) { echo '<option>'.$value['name'].'</option>' ; } } this is my model application/model/admin_model.php public function getCity() { if($_POST['id']) { $cid=$_POST['id']; $sth = $this->db->prepare('SELECT id, name FROM unit WHERE cid= :cid'); $sth->execute(array(':cid' => $cid)); return $sth->fetchAll(); } } this is my view <form id="city" action="<../application/admin/regstr/" method="post"> Country <select name="country" class="country"> <option value="" selected="selected">--Select Taluka--</option> <option value="1">India</option> <option value="2">USA</option> <option value="3">China</option> </select> City <select name="city" class="city"> <option selected="selected">--Select City--</option> </select> <input type="submit" /> </form> and this is my javascript for Ajax $(document).ready(function() { $(".country").change(function() { var id=$(this).val(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "admin/getCity", data: dataString, cache: false, success: function(html) { $(".city").html(html); } }); }); }); But I am not getting the output. I have tested it with firebug in response tab. Instead of getting only option values html code as output I am getting the whole HTML page content (i.e. content of view page admin/index.php. Please help me out. Pardon my noobness, but I'm learning to wrap AJAX into my work and use it to get XML instead of "static" PHP that generates the HTML. The login/security portion has my head spinning, but it's probably not as difficult as I think and I'm probably just confusing myself. In the past, for each PHP page in my site, I would perform a quick salted login check based on the username/password stored in the $_SESSION variables. Perhaps it was a bit overboard to check on each page, but, well, I did it. With AJAX, I *NEED* to ensure that the php resulting from an AJAX POST request won't run if the user isn't authenticated, and I need to ensure that they didn't just somehow force a $_SESSION variable to reflect an authenticated session. I also need to ensure that someone can't just load up the PHP page on it's own, somehow send a POST to it and run it without being authenticated. I suppose that beyond the larger picture of "How do I ensure that the user is authenticated, the POST request is authentic, and nobody has forced a change in the $_SESSION stored on the server, I have a few specific questions. I know that in part I'm confused about the whole cookie/SESSION process. In my old PHP site, the SESSION number was stored on the cookie on the user's machine. If the info is sent via AJAX, does the PHP get the SESSION info from the cookie or does it have to be explicitly sent? With potentially several users sending AJAX requests at the same time, how will my PHP know which SESSION to use for each request? Is is secure enough to set an "Autheticated" flag in $_SESSION once the user is authenticated the first time? Is it really just as simple as sending a username/salted password hash as AJAX/POST and setting an authenticated flag in the SESSION to ensure that the rest of the AJAX application runs without allowing someone to back-door the PHP? i'm not sure whether this should be in this section or the ajax section. i'm trying to echo out an ajax script so that a page loads in a div tag after a link is clicked in the menu. Without the "echo", it works fine, but as soon as i include it within the "echo", it stops working. Any help would be great else echo" <div id='fcontrol'> <table border='1' class ='tstyle'> <tr height ='700'><td valign='top' class='ssbg' width='120'><div id='menu'> <a href='javascript:ajaxpage(''new_section.php'', ''contentarea'');'>Add new section</a><br/><br/> <a href='javascript:ajaxpage('new_sub_section.php', 'contentarea');'>Add new section to forum</a><br/><br/><a href='index.php'>Back to forum</a><br/><br/></div></td><td class='tcontrol' width='700' valign='top'> <center><div id='contentarea'>Control Panel</div></center></td></tr> </table></div> </div> "; ?> Evening fellow freaks I am having a major problem with what I think is quite a simple script, its basically just a ajax same page registration script that is throwing up some php errors. I am not sure if the error lies in the php or js, or both! Ill post the scripts and then explain the problem login.php <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function() { //if submit button is clicked $('#signin_submit').click(function () { //Get the data from all the fields var username = $('input[name=username]'); var email = $('input[name=email]'); var password = $('input[name=password]'); //Simple validation to make sure user entered something //If error found, add hightlight class to the text field if (username.val()=='') { name.addClass('hightlight'); return false; } else name.removeClass('hightlight'); if (email.val()=='') { email.addClass('hightlight'); return false; } else email.removeClass('hightlight'); if (password.val()=='') { comment.addClass('hightlight'); return false; } else password.removeClass('hightlight'); //organize the data properly var data = 'username=' + username.val() + '&email=' + email.val() + '&password=' + password.val(); //disabled all the text fields $('.text').attr('disabled','true'); //show the loading sign $('.loading').show(); //start the ajax $.ajax({ //this is the php file that processes the data and send mail url: "processreg.php", //GET method is used type: "GET", //pass the data data: data, //Do not cache the page cache: false, //success success: function (html) { //if process.php returned 1/true (send mail success) if (html==1) { //hide the form $('.form').fadeOut('slow'); //show the success message $('.done').fadeIn('slow'); //if process.php returned 0/false (send mail failed) } else alert('Sorry, unexpected error. Please try again later.'); } }); //cancel the submit button default behaviours return false; }); }); </script> <div id="logincontainer"> <div id="topnav" class="topnav"> <a href="login" class="login"><span>Register</span></a> <a href="login" class="signin"><span>Log In</span></a> </div> <fieldset id="signin_menu"> <form method="post" id="signin" action=""> <label for="username">Username</label> <input id="username" name="username" value="" title="username" tabindex="4" type="text"> <br> <label for="password">Password</label> <input id="password" name="password" value="" title="password" tabindex="5" type="password"> <p class="remember"> <input id="signin_submit" value="Sign in" tabindex="6" type="submit"> <input id="remember" name="remember_me" value="1" tabindex="7" type="checkbox"> <label for="remember">Remember me</label> </p> <p class="forgot"> <a href="#" id="resend_password_link">Forgot your password?</a> </p> <p class="forgot-username"> <A id=forgot_username_link title="If you remember your password, try logging in with your email" href="#">Forgot your username?</A> </p> </form> </fieldset> <fieldset id="login_menu"> <form method="post" id="login" action="processreg.php"> <label for="username">Username</label> <input id="username" name="username" title="username" type="text"> <br> <label for="email">Email</label> <input id="email" name="email" title="email" type="text"><br> <label for="password">Password</label> <input id="password" name="password" title="password" type="password"> <input id="submit" value="Register" type="submit"> </p> </form> </fieldset> <div class="loading"></div> <div class="done"> <b>Thank you for joining!</b> You can now login. </div> </div> <script type="text/javascript"> $(document).ready(function() { $(".signin").click(function(e) { e.preventDefault(); $("fieldset#signin_menu").toggle(); $(".signin").toggleClass("menu-open"); }); $("fieldset#signin_menu").mouseup(function() { return false }); $(document).mouseup(function(e) { if($(e.target).parent("a.signin").length==0) { $(".signin").removeClass("menu-open"); $("fieldset#signin_menu").hide(); } }); }); $(document).ready(function() { $(".login").click(function(e) { e.preventDefault(); $("fieldset#login_menu").toggle(); $(".login").toggleClass("menu-open"); }); $("fieldset#login_menu").mouseup(function() { return false }); $(document).mouseup(function(e) { if($(e.target).parent("a.login").length==0) { $(".login").removeClass("menu-open"); $("fieldset#login_menu").hide(); } }); }); </script> <script src="javascripts/jquery.tipsy.js" type="text/javascript"></script> <script type='text/javascript'> $(function() { $('#forgot_username_link').tipsy({gravity: 'w'}); }); </script> and processreg.php <?php include('connect.php'); //Retrieve form data. //GET - user submitted data using AJAX //POST - in case user does not support javascript, we'll use POST instead $username = ($_GET['username']) ? $_GET['username'] : $_POST['username']; $email = ($_GET['email']) ?$_GET['email'] : $_POST['email']; $password = ($_GET['password']) ?$_GET['password'] : $_POST['password']; //flag to indicate which method it uses. If POST set it to 1 if ($_POST) $post=1; //Simple server side validation for POST data, of course, you should validate the email if (!$username) $errors[count($errors)] = 'Please enter your name.'; if (!$email) $errors[count($errors)] = 'Please enter your email.'; if (!$password) $errors[count($errors)] = 'Please enter your required password.'; //if the errors array is empty, send the mail if (!$errors) { $newpassword= md5($password); $result="INSERT INTO userbase (username, email, password) VALUES ('$username','$email','$newpassword')"; //if POST was used, display the message straight away if ($_POST) { if (!mysql_query($result)) echo 'Thank you! We have received your message.'; else echo 'Sorry, unexpected error. Please try again later'; //else if GET was used, return the boolean value so that //ajax script can react accordingly //1 means success, 0 means failed } else { echo $result; } //if the errors array has values } else { //display the errors message for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>'; exit; } ?> The output errors Quote Notice: Undefined index: username in C:\wamp\www\buy2earn\processreg.php on line 7 Notice: Undefined index: email in C:\wamp\www\buy2earn\processreg.php on line 8 Notice: Undefined index: password in C:\wamp\www\buy2earn\processreg.php on line 9 Notice: Undefined variable: errors in C:\wamp\www\buy2earn\processreg.php on line 21 Thank you! We have received your message. Now this is basic basic errors, which I know normally means I have named my form inputs different to the processing script, but in this case they are correct. I am using the second form in the login script which is this one: Code: [Select] <form method="post" id="login" action="processreg.php"> <label for="username">Username</label> <input id="username" name="username" title="username" type="text"> <br> <label for="email">Email</label> <input id="email" name="email" title="email" type="text"><br> <label for="password">Password</label> <input id="password" name="password" title="password" type="password"> <input id="submit" value="Register" type="submit"> Can anyone explain what's the problem? My js skills are non existent so this came from my collection of saved rar files with no explanations and some very basic editing! Many Thanks The Ajax Code: Code: [Select] <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("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } var pic = document.getElementById('pic').value; var queryString = "?pic=" + pic; ajaxRequest.open("GET", "ajax-example.php" + queryString, true); ajaxRequest.send(null); } //--> </script> The PHP code: Code: [Select] <?php require_once("configure.php"); mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database" . mysql_error()); @mysql_select_db("$DBName") or die("Unable to select database $DBName" . mysql_error() ); $user_sqla = "select * from $emaila " ; while($user_array = mysql_fetch_array($user_resulta)) { $pictures = $user_array[picture]; ?> <form name='myForm'> <?php echo "<div align='left' style='padding-left:25px'><table border='1'><tr><td><img src=".$pictures." width='65' height='65'><input type='hidden' name='pic' id='pic' value=".$pictures.">". $pictures;?></td> <td><div style="padding-left:5px; padding-top:15px"><?php echo "<a href='#' onclick='ajaxFunction()' >Remove</a></td></tr></table></div>"; ?></div> </form><?php } ?> the ajax-example.php code: Code: [Select] <?php // Retrieve data from Query String $age = $_GET['pic']; echo $age; ?> Now the Php code gives the following result: "image1" "Remove" "image2" "Remove" "image3" "Remove" when I click the "Remove" the result I keep getting is "image1" even if I click the remove beside image3 I still get the Image1 Name transffered from my ajax code to the ajax-example.php page This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=351379.0 Me and one other person have just started developing a forum package, it's the first time that either of us have really used AJAX, but we're both pretty good with PHP. We're trying to work out the whole submitting a registration form using AJAX, we have the page http://www.example.com/account/register When the user visiter goes to this site they're presented with the registration form, as you'd expect. When the form is submitted, AJAX does a POST request thing (Whatever you call it) to the same page, the script on this page checks to see if there's any post data and if there is, it validates it and sends it to the database etc. The problem is, what is there to stop anyone from sending post data to this site and adding random users? The same problem would occur if we were to add functions to delete and change users. Any hackers could send post data and delete users. Are we doing something wrong, or is there something obvious we've missed? This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=312841.0 |