PHP - Ajax Login Validation Using Php And Jquery
Hi there, I am using the jQuery, Ajax PHP code which is given at http://roshanbh.com.np/2008/04/ajax-login-validation-php-jquery.html
The form I am using, which is in index.html, is: Code: [Select] <form method="post" action="" name="login" id="login_form"> <div class="field_row"> <div class="label_container"> <label>Email</label> </div> <div class="field_container"> <input type="text" placeholder="login with your email address..." name="email_address" id="email_address" value="" class="large" /> </div> <div class="clear"><span class="nodisp"> </span></div> </div> <div class="field_row"> <div class="label_container"> <label>Password</label> </div> <div class="field_container"> <input type="password" placeholder="...and password" name="password" id="password" value="" class="large" /> </div> <div class="clear"><span class="nodisp"> </span></div> </div> <div class="final_row"> <input type="image" src="images/login_blue.gif" id="user_login_button" name="user_login_button" value="login" id="submit" class="submit_button" /> <div class="final_row_text_container" > <a href="/login/forgot_password" style="color: #008ee8;" class="small_text">Forgot your Password?</a> <br /> <span id="msgbox" style="display:none"></span> </div> </div> <div class="clear"><span class="nodisp"> </span></div> </form> The Javascript, which is situated in the head of index.html. is: Code: [Select] <script language="javascript"> $(document).ready(function() { $("#login_form").submit(function() { //remove all the class add the messagebox classes and start fading $("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000); //check the email address exists or not from ajax $.post("login_ajax.php",{ email_address:$('#email_address').val(),password:$('#password').val(),rand:Math.random() } ,function(data) { if(data=='yes') //if correct login detail { $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox { //add message and change the class of the box and start fading $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1, function() { //redirect to secure page document.location='secure.php'; }); }); } else { $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox { //add message and change the class of the box and start fading $(this).html('Your login details are incorrect.').addClass('messageboxerror').fadeTo(900,1); }); } }); return false; //not to post the form physically }); //now call the ajax also focus move from $("#password").blur(function() { $("#login_form").trigger('submit'); }); }); </script> And the PHP, in login_ajax.php, is: <?php session_start(); $host = "localhost"; $user = "bford"; $pass = "bford"; $db = "bford"; $link = mysql_connect($host, $user, $pass); if (!link) { die('<strong>Error(s) occured:</strong> Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db($db, $link); if (!db_selected) { die ('<strong>Error(s) occured:</strong> Cant use bford: ' . mysql_error()); } //get the posted values $email_address=$_GET['emailaddress']; $pass=$_GET['password']; //now validating the username and password $sql="SELECT * FROM users WHERE email_address='".$email_address."'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); //if username exists if(mysql_num_rows($result)>0) { //compare the password if($row["password"],$pass)==1 { echo "yes"; //now set the session from here if needed $_SESSION["user_name"]=$userID; } else echo "no"; } else echo "no"; //Invalid Login ?> I have been working on this for days now, changing around the form names, database table names, php variables, allsorts! I still cannot get it functioning properly. When I input a correct email_address and password combination, the 'Your login details are incorrect.' message still appears. Help would be much appreciated. Ben. Similar TutorialsThis topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=314220.0 Hello, I decided I would make my websites load less by implementing ajax/jQuery.. I however stumbled upon a problem.. This is the code I use to direct myself to the registeration page... Code: [Select] function register(){ $.ajax({ type: "POST", url: "user/registerConfirm.php", data: "regUsername=" + document.getElementById("regUsername").value + "®Password=" + document.getElementById("regPassword").value + "&myPassCheck=" + document.getElementById("myPassCheck").value + "®Email=" + document.getElementById("regEmail").value, success: function(html){ $('#response').html(html); alert("success..."); }, complete: function(html){ $('#response').html(html); alert("completed.."); } }); } When running - it shows me the "alert("completed..");", and in fact- the code used to insert the user in my database is working. However, I never seem to get the 'html' variable that they use in tutorials I found. (meaning I can't show some sort of response) The php code used: Code: [Select] <?php session_start(); ob_start(); require("../widgets/functions.php"); connectToDB(); // Check email if (!filter_var(clean($_POST['regEmail']), FILTER_VALIDATE_EMAIL)) { $error = 'Invalid email!'; } else { if ( clean($_POST['regPassword']) == clean($_POST['myPassCheck']) && clean($_POST['regPassword']) != NULL && clean($_POST['regUsername']) != NULL && clean($_POST['regEmail']) != NULL ) // Register can be allowed { // Check if their already is a user with the same name.. $sql="SELECT * FROM `users` WHERE username='".clean(trim($_POST['regUsername']))."'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); if($count==1){ // Their was already a user with this name! $error = 'Registration failed - username already taken..'; } else if ( $count == 0 ){ // Registration allowed, no user found with the same name // Encrypt password $encryptPass = md5($_POST['regPassword']); $subject = "Confirmation registration"; $message = ' <html> <head> <title>Registration at codexplained</title> </head> <body> <p>Hello '.clean($_POST['regUsername']).',</p> <p>Thank you for registering at our website! </p> <p>If you wish, you can now edit your profile, to change your display options and/or to upload your own profile image!<br /> We hope to see you commenting on our articles soon!<br /> If you wish to receive more information - Please contact us, or message any of our moderators.</p> <hr /> <p>- Current moderators - <br /> Ruud<br /> Willem<br /> Quint </p> <hr /> </p> - Contact details - <br /> Codexplained.tk<br /> Codexplained@gmail.com </p> </body> </html> '; $from = "Codexplained@admin.com"; $headers = 'From: Codexplained'."\r\n"; $headers .= 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $to = clean($_POST['regEmail']); if ( mail($to,$subject,$message,$headers) ) { // Success } else { // Failed } // Insert data $query = "INSERT INTO `users` ( `Id` ,`Username` ,`Password` ,`Rank`,`E-mail` ,`PostAmount`, `ProfileImage`, `Ip`, `LastIP` ) VALUES ( NULL , '".clean(trim($_POST['regUsername']))."' , '".$encryptPass."' , 'member', '".clean($_POST['regEmail'])."' , '0', 'none', '".$_SERVER['REMOTE_ADDR']."','".$_SERVER['REMOTE_ADDR']."' ) "; mysql_query($query)or die(mysql_error()); $error = 'Registration completed!'; } } else { if ( clean($_POST['regPassword']) != clean($_POST['myPassCheck']) ) { $error = 'Passwords do not match...'; } else { $error = 'Registration failed - not enough data..'; } } } echo $error; exit; mysql_close(); //header("location:../index.php?page=register"); ?> And here is the form code: Code: [Select] <?php session_start(); ob_start(); connectToDB(); $query = "SELECT * FROM `users`"; $result = mysql_query($query); $num = mysql_num_rows($result); echo ' <div id="registerHolder"> <h1> <strong> Registration </strong> </h1> <em>Currently... we have '.$num.' registered members! Join them by filling in the form below!</em><br /> <p> Please fill in these boxes and press confirm to register: <br /> <form id="registerForm" method="post" action=""> <table> <tr> <td style="width:200px"> Username: </td> <td> <input name="regUsername" type="text" id="regUsername" style="width:300px" class="box" value="" /> </td> </tr> <tr> <td> Password: </td> <td> <input name="regPassword" type="password" id="regPassword" style="width:300px" class="box" value="" /> </td> </tr> <tr> <td> Confirm Password: </td> <td> <input name="myPassCheck" type="password" style="width:300px" id="myPassCheck" value="" /> </td> </tr> <tr> <td> E-mail: </td> <td> <input name="regEmail" type="text" id="regEmail" style="width:300px" class="box" value="" /> </td> </tr> <tr> <td> <input type="submit" name="Submit" class="btn" value="Confirm" onclick="register()" /> </td> </tr> </table> <br /> </form> </p> <div id="response"> </div> </div> '; ?> I am wondering what I missed, and hoped someone out here could assist me. Thanks in advance. Edit: Added register.php code (form) Hi Everyone,
I am struggling with a pdf.
On our server I get the pdf as a byte array from the database, which I then build up in a StreamingOutput object and return as a pdf file. This is done using java using JAX-RS service.
Now when I open the path/link in my browser(chrome/firefox) the pdf opens in the browser. So this means my backend is working.
On my webapp I want to use $.ajax to download the pdf and view it in an Iframe or embed it in an <embed> or <object> tag. I need to do this as the service call is actually under username and password, and we do not create a session between the browser and the server - there is a long explanation for this.
I saw the option to use http://[username]:[password]@www.myserver.com/... but this was dropped by most browsers. This is why I am trying ajax.
Now in my ajax call I do receive the pdf in the success function as:
%PDF-1.4....This open the browser's pdfviewer correctly and every thing, but the pdf only returns blank pages. The Base64 is a java object that I found on the internet. But I have tried it without the base64 but still now luck. Here is my success function from my ajax call. success: function(data, status, xhr) { var pdfText = Base64.encode(xhr.responseText); var url = "data:application/pdf;base64," + escape(pdfText); var html = '<embed width=100% height=600' + ' type="application/pdf"' + ' src="' + url + '">' + '</embed>'; $("div.inner").html(""); $("div.inner").append(html); }, I need some help adjust a search form that uses PHP/MySQL/AJAX/JQuery. I am not sure what area needs to be adjusted, but I think it's in the Query. The search from searches across the MySQL database of sports team info and works fine. the only problem is in the return of one key word when I needed the exact match of two or more words. For instance you type in 'Miami Heat' and the results returned are for 'Miami Heat' and 'Miami Dolphins', so anything with the key word Miami is returned. Here is the PHP code <?php $dbhost = "localhost"; $dbuser = "username"; $dbpass = "pw"; $dbname = "db_name"; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; } if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; } if($type == "count") { $sql = mysql_query("SELECT count(category_id) FROM players WHERE MATCH(sport,first_name,last_name,MVP,team) AGAINST('$query' IN BOOLEAN MODE)"); $total = mysql_fetch_array($sql); $num = $total[0]; echo $num; } if($type == "results") { $sql = mysql_query("SELECT sport,first_name,last_name,MVP,team FROM players WHERE MATCH(sport,first_name,last_name,MVP,team) AGAINST('$query' IN BOOLEAN MODE)"); echo "<table>"; echo "<tr>"; echo "<th>First Name</th><th>Last Name</th><th>Team</th><th>MVP</th>"; while($array = mysql_fetch_array($sql)) { $sport = $array['sport']; $first_name = $array['first_name']; $last_name = $array['last_name']; $team = $array['team']; $MVP = $array['MVP']; echo "<tr><td>" . $first_name . "</td>\n<td>". $last_name ."</td>\n<td>" .$team."</td>\n<td> . $MVP .</td>\n</tr>\n"; } echo "</table>";=\ } mysql_close($conn); ?> This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=350592.0 This little bit of code fires a database insert and gets the keyfield ID number back. Everything works, except the last part: assigning the returned number to the ID attribute of the table cell that was clicked. Looks like $.ajax knows what $(this) is, but forgets before getting to .complete.
How do I get the "this" variable to be recognized inside the .complete function?
$('table td').click(function() { //user clicks a table cell alert($(this).index()); //test case returns '9' $.ajax({ url: "update.php", type: "POST", data: { action: 'clicked', clicked: $(this).index(), //the column that was clicked row: $(this).parent().attr('id').substr(4) //the row that was clicked (tr has an ID attribute like "row22") } }) .complete(function(data) { alert($(this).index()); //test case should return '9', but returns '-1' instead. console.log(data.responseText); //console gets the assigned id from a database insert -- works fine. $(this).attr('id','ros'+data.responseText); //doesn't work. did .complete forget what $(this) is? }); }I thought about making a hidden element, or global variable to assign $(this) to, but that seems like the long way around. Any other ideas? Hello, everyone. I have code that effectively calls a PHP page with AJAX (no JQuery). The PHP responds fine with an echo. Here is the javaScript that calls the PHP so refreshing the page doesn't need to be done.
function deleteCategory() { var e= document.getElementById("dropDown1"); var var1 = e.options[e.selectedIndex].text; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = alerta() { if (this.readyState == 4 && this.status == 200) { document.getElementById("insert").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "deleteRow.php?q=" + var1 , true); xmlhttp.send(); } How do I call a PHP function on the same page while preserving the above AJAX.
Sincerely, Joshua I am having a problem making this work. It adds and deletes but it does it by passing the date directly to the PHP files and refreshing the screen. I want it to do it through the jquery Ajax script. This should work according to what I have read but no mater what I try the jquery script does not work.
<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function(){ $('MySignform').submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: $('MySignform').prop('action'), data: $('MySignform').serialize(), success: function() { alert("It worked!"); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function(){ $('DelForm').submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: $('DelForm').prop('action'), data: $('DelForm').serialize(), success: function() { alert("It worked!"); } }); }); }); </script> <br /> <br /> <br /> <center> <form name="MySignform" action="addsigningfee.php" method="post"> <label>Signing fee</label> <input name="signingfee" type="text" id="signingfee"/> <input name="pid" type="hidden" value="7"/> <p></p> <button id="form-submit" type="submit">Save</button> </form> <br /> <div id="result"></div> <br /> <form name="DelForm" action="delsigningfee.php" method="post"> <select name="signingfee"> <?php require_once("connect.php"); foreach ($db->query("SELECT signingfee,id FROM options WHERE signingfee <> '' AND pid = '7'") as $row) { echo "<option value=" . $row['id'] . ">" . $row['signingfee'] . "</option>"; } ?> </select> <p></p> <button type="submit" >Delete</button> </form> </center> </body> </html> Adding and Deleteing mysql date using jquery Ajax I am having a problem making this work. It adds and deletes but it does it by passing the date directly to the PHP files and refreshing the screen. I want it to do it through the jquery Ajax script. This should work according to what I have read but no mater what I try the jquery script does not work. Some help getting me In the right direction would be great. Code:
I'm trying to login and scrape a page 4 pages deep. I can get to the fourth page...but that page only returns AJAX ERROR:0. I know NOTHING about AJAX calls via Curl. Can someone please help me with what to look for in the source code of the 4th page (when using a browser) to what I'm supposed to pass along via CURL? Hi y'all. It's been forever and a day since I've dealt with cookies, and I can't get through the cobwebs in my brain about them. I know that cookies have to be set before any output goes to the browser, but if I'm not mistaken, it's the same with sessions and sessions work in this situation. Unfortunately, the client needs cookies for integration with an existing piece of software.
Basically, what's happening is this: You load a page, click the 'login' button, which uses JQuery to change the display on the login screen from 'none' to 'block'. Use the newly-visible login form to enter username and password, which are passed via ajax to my login function. If the login is successful, I set the cookie variable and redirect the user to the protected page. However, despite the ajax reporting a successful login and redirecting the browser as expected, the check on the protected page is kicking the user back to the beginning because the cookie was never actually set.
FunctionsClass.php:
/** * Logs in the requesting user with the agent and email values supplied via AJAX. * @return string JSON-encoded array */ public function agentLogin(){ $ret['success'] = $this->_site->login($_POST['username'],$_POST['password']); $ret['location'] = '/protected-page'; print(json_encode($ret)); die(); }Site.php (that's $_site in FunctionsClass): /** * Logs in the agent. * Checks to see if the user is already logged in, if not, attempts to do so. * @param string $un username * @param string $pw password * @return boolean */ public function logIn($un, $pw){ if($this->isLoggedIn()){ return true; } return $this->logAgentIn($un,$pw); } /** * Check to see if the cookie set so we know if the user has logged in. * @return boolean */ public function isLoggedIn(){ // return !empty($_SESSION['mycheckvariable']); return !empty($_COOKIE['mycheckvariable']); } /** * Log the user in. * @param string $un username * @param string $pw password * @return boolean */ private function logAgentIn($un,$pw){ // $_SESSION['mycheckvariable']['email'] = 'me@notmyemail.com'; setcookie('mycheckvariable','me@notmyrealemail.com',time()+60*60*8,'/'); return true; }It's not as though I'm even actually checking a database - just trying to stub this out for client presentation. And, if I uncomment the two lines using sessions and comment out the cookies, it all works perfectly. I'm not at all sure what I'm missing and would very much appreciate some other eyes on this - any takers? I'm using WordPress, if that matters at all... Thanks in advance! This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=342898.0 Hello all I have a php and jquery/ajax call I am using to create a file/send an email. I get all the contents from my textboxes but I want a message to display on the screen afterwards being success or fail. In my .ajax call My call is exiting right before the ‘success:’ part. Why is my call not succeeding? Any tips/help will be appreciated Thank you Html page just a form with a submit button $(document).ready(function () { var form = $("#formData"); $(form).on("submit", function (event) { event.preventDefault(); $.ajax({ type: "post", url: "file.php", data: $(this).serialize(), beforeSend: function () { $("#status").html('<span style="color:red;">Loading everything actually creating a .TXT file of contents...</span>') //--works }, success: function (data) { var responseMsgType = "alert-" + data.type; var responseMsgText = data.message; // message below var alertBox = '<div class="alert ' + responseMsgType + ' alert-dismissable"><button type="button" class="close" ' + 'data-dismiss="alert" aria-hidden="true">×</button>' + responseMsgText + '</div>'; if (responseMsgType && responseMsgText) { $(form).find(".successArea").html(alertBox); $(form)[0].reset(); } } }); return false; }); <?php $controls = array('txtName' => 'Name', 'txtEmail' => 'Email', 'txtSubject' => 'Subject', 'txtMessage' => 'Message'); try { if(count($_POST)==0) { throw new \Exception ('Contact Form Message is empty'); } $headers = array('Content-Type: text/plain; charset="UTF-8";', 'From: ' . $email, 'Reply-To: ' . $email, 'Return-Path: ' .$email); $emailMessage = "You have a new message from your contact form" . PHP_EOL; $emailMessage .= "-------------------------------------------------------" . PHP_EOL; foreach($_POST as $key => $value){ if(isset($controls[$key])) { $emailMessage .= "$controls[$key]: $value". PHP_EOL; } } $mailMsg = "email6.txt"; if(file_exists($filename) == false) { $fh = fopen($mailMsg, "w"); fwrite($fh, $headers); fwrite($fh, $emailMessage); fclose($fh); } else { $fhexists = fopen($filename, "a"); fwrite($fhexists, $content); fclose($fhexists); } $responseMessage = array("type" => "success", "message" => $successMessage); } catch (\Exception $ex) { $responseMessage = array("type" => "errorM", "message" => $errorMessage); } if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $encodedJSON = json_encode($responseMessage); header("Content-Type: application/json"); echo $encodedJSON; } else { echo $responseMessage["message"]; }
Hello Guys... I need help about my validate scripts... $(document).ready(function(){ //Validation jQuery.validator.addMethod('validIPurl', function(value) { var ip = '^([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]).([01]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])$'; var URL = /^(http|https)?:\/\/[a-zA-Z0-9-\.]+\.[a-z]{2,4}/; //HOW TO JOIN AND VALIDATE BOTH VARIABLE IP AND URL???? } }, 'Invalid Address'); //if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i) $(".myfirstform").validate( { rules: { ip: { validIPurl: true } }, ); },I use jquery.validate javascripts to validate user input.. I also try to create if..else to join IP and URL but the control statement not working Hope you guys can help for the solution... This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=359169.0 Hi my code below checks for Username and password from a form and if they match those in database, it redirects to main.php However, I would like some help setting up error page?! at the moment if the username or password are incorrect and teh form is submitted, the pages just goes white and blank?! <?php session_start(); include_once("config.php"); checkLoggedIn("no"); if(isset($_POST["submit"])) { field_validator("rsUser", $_POST["rsUser"], "alphanumeric", 3, 15); // password must be between 4 and 15 chars - any characters can be used: field_validator("rsPass", $_POST["rsPass"], "string", 3, 15); if($messages){ doIndex(); exit; } if( !($row = checkPass($_POST["rsUser"], $_POST["rsPass"])) ) { $messages[]="Incorrect login/password, try again"; } if($messages){ doIndex(); exit; } cleanMemberSession($row["rsUser"], $row["rsPass"], $row["UserID"]); if ($user = checkPass($_REQUEST['rsUser'], $_REQUEST['rsPass'])) { cleanMemberSession($user['rsUser'], $user['rsPass'], $user['UserID']); } else { echo('Login failed'); } header("Location: main.php"); } else { doIndex(); } function doIndex() { global $messages; global $title; } ?> Login failed does not get shown if a username is entered wrong?! Hi Guys, just been writing this script up but for some reason the validation is messing up creating account, apparently nothing is valid that i put in Any ideas? the .phps are below and the .inc ar all below. Also when i try to log in with an existing user it says i cant because the username or password is incorrect which is isn't. Any help will be much appreciated. Enlighten Code: [Select] <?php /* File: login_reg_form.inc * Desc: Contains the code for a web page that displays two html forms, side by side. One is a login form, and the second is a registration form. */ include("functions.inc"); ?> <head><title>Customer Login page</title> <style type='text/css'> <!-- label { font-weight: bold; float: left; width: 27%; margin-right: .5em; text-align: right; } legend { font-weight: bold; font-size: 1.2em; margin-bottom: .5em; } #wrapper { margin: 0; padding: 0; } #login { position: absolute; left: 0; width: 40%; padding: 1em 0; } #reg { position: absolute; left: 40%; width: 60%; padding: 1em 0; } #field { padding-bottom: .5em; } .errors { font-weight: bold; font-style: italic; font-size: 90% color: red; margin-top: 0; } --> </style> </head> <body style="margin: 0"> <?php $fields_1 = array("fusername" => "User Name", "fpassword" => "Password"); $fields_2 = array("user_name" => "User Name", "password" => "Password", "email" => "Email", "first_name" => "First Name", "last_name" => "Last Name", "street" => "Street", "city" => "City", "county" => "County", "post_code" => "Post Code", "phone" => "Phone", "fax" => "Fax"); ?> <div id="wrapper"> <div id="login"> <form action=<?php echo $_SERVER['PHP_SELF']?> method="POST"> <fieldset style='border: 2px solid #000000'> <legend>Login Form</legend> <?php if (isset($message_1)) { echo "<p class='errors'>$message_1</p>\n"; } foreach ($fields_1 as $field => $value) { if(preg_match("/pass/i", $field)) $type = "password"; else $type = "text"; echo "<div id ='field'> <label for='$field'>$value</label> <input id='$field' name='$field' type= '$type' value='".@$$field."' size='20' maxlength='50' /> </div>\n"; } ?> <input type="submit" name="Button" style='margin-left: 45%; margin-bottom: .5em' value="Login" /> </fieldset> </form> <p style='text-align: center; margin: 1em'> If you already have an account, log in.</p> <p style='text-align: center; margin: 1em'> If you do not have an account, register now.</p> </div> <div id='reg'> <form action=<?php echo $_SERVER['PHP_SELF']?> method="POST"> <fieldset style='border: 2px solid #000000'> <legend>Registration form</legend> <?php if(isset($message_2)) { echo "<p class='errors'>$message_2</p>\n"; } foreach($fields_2 as $field => $value) { if (preg_match("/pass/i", $field)) $type="password"; else $type="text"; echo "<div id='field'> <label for='$field'>$value</label> <input id='$field' name='$field' type='$type' value='".@$$field."' size='40' maxlength='65' /> </div>\n"; } // end foreach field ?> <input type="submit" name="Button" style='margin-left: 45%; margin-bottom: .5em' value="Register"> </fieldset> </form> </div> </div> </body></html> Dear all, Please help me. I have two sites and both run on separate DB, both have separate signup and login process, Now i want if any user login from any site can access both sites. There are separate session for both sites now i want to use any of the session for user authentication. Please give suggestions. Thanks, I have a form with dropdown list that is populated with values from Sql Server table. Now i would like to use this selected item in SQL query. The results of this query should be shown in label or text field. So when a user selects item from dropdown menu, results from SQL query are shown at the same time. I have two dropdown list at the moment in my form. First one gets all values from a column in table in SQL Server. And the second one should get a value from the same table based on a selection in first dropdown list.
When i load ajax.php i get 2 error mesages: This is my code so far. I have tried to do it with this Ajax script. But i can only get first dropdown to work. The second dropdown(sub_machinery) does not show values, when first dropdown item is selected. The second dropdown should show values from databse table with this query( *$machineryID* is first dropdown selected item): SELECT MachineID FROM T013 WHERE Machinery=".$machineryID. Index.php <!doctype html> <?PHP $server = "server"; $options = array( "UID" => "user", "PWD" => "pass", "Database" => "database"); $conn2 = sqlsrv_connect($server, $options); if ($conn2 === false) die("<pre>".print_r(sqlsrv_errors(), true)); echo " "; ?> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body> <section id="formaT2" class="formaT2 formContent"> <div class="row"> <div class="col-md-2 col-3 row-color remove-mob"></div> <div class="col-md-5 col-9 bg-img" style="padding-left: 0; padding-right: 0;"> <h1>Form</h1> <div class="rest-text"> <div class="contactFrm"> <p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p> <form action="connection.php" method="post"> <div>machinery</div> <select id="machinery"> <option value="0">--Please Select Machinery--</option> <?php // Fetch Department $sql = "SELECT Machinery FROM T013"; $machanery_data = sqlsrv_query($conn2,$sql); while($row = sqlsrv_fetch_array($machanery_data) ){ $id = $row['Id']; $machinery = $row['Machinery']; // Option echo "<option value='".$id."' >".$machinery."</option>"; } ?> </select> <div class="clear"></div> <div>Sub Machinery</div> <select id="sub_machinery"> <option value="0">- Select -</option> </select> <input type="submit" name="submit" id="submit" class="strelka-send" value="Insert"> <div class="clear"> </div> </form> </div> </div> </div> </div> </section> </script> <script type="text/javascript"> $(document).ready(function(){ $("#machinery").change(function(){ var machinery_id = $(this).val(); $.ajax({ url:'ajaxfile.php', type: 'post', data: {machinery:machinery_id}, dataType: 'json', success:function(response){ var len = response.length; $("#sub_machinery").empty(); for( var i = 0; i<len; i++){ var machinery_id = response[i]['machinery_id']; var machinery = response[i]['machinery']; $("#sub_machinery").append("<option value='"+machinery_id+"'>"+machinery+"</option>"); } } }); }); }); </script> </body> </html> Ajaxfile.php <?php $server = "server"; $options = array( "UID" => "user", "PWD" => "pass", "Database" => "database"); $conn2 = sqlsrv_connect($server, $options); if ($conn2 === false) die("<pre>".print_r(sqlsrv_errors(), true)); echo " "; $machineryID = $_POST['machinery']; // department id $sql = "SELECT MachineID FROM T013 WHERE Machinery=".$machineryID; $result = sqlsrv_query($conn2,$sql); $machinery_arr = array(); while( $row = sqlsrv_fetch_array($result) ){ $machinery_id = $row['ID']; $machinery = $row['MachineID']; $machinery_arr[] = array("ID" => $machinery_id, "MachineID" => $machinery); } // encoding array to json format echo json_encode($machinery_arr); ?>Edited May 6, 2019 by davidd 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.
Background:
Question:
My experience: Code Examples:
function getInfo(ProductNumber){ $.ajax({ url:'Ajax-PHP-Page.php?ProductNumber='+ProductNumber, success: function(html) { document.getElementById("my_div").value = ''; document.getElementById("my_div").value = html; } }); }
function getInfo(ProductNumber) { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("my_div").value = this.responseText; } }; xmlhttp.open("GET","Ajax-PHP-Page.php?ProductNumber="+ProductNumber,true); xmlhttp.send(); } Thank you!! Edited May 5, 2020 by StevenOliver |