PHP - Moved: Ajax/jquery
This topic has been moved to Ajax Help.
http://www.phpfreaks.com/forums/index.php?topic=314220.0 Similar TutorialsHello, 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) 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); ?> 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); }, 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. 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 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? 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: 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"]; }
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=325858.0 This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=333348.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=351379.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=312841.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=309753.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=348693.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=332473.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=323434.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=320161.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=350592.0 This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=308756.0 This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=314117.0 |