Jump to content

Search the Community

Showing results for tags 'javascript'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Hi guys, I have this issue. It works fine in another piece of php code as in where I ban a user, it will show sweetalert to confirm and when I click unban this user, it will ask me in a nice sweetalert if I am sure. When I click Yes, the user ban gets lifted and then disaster strikes. It shows a normal js alert with html code inside. Here is the code that is used to lift the ban: <?php include_once('config.php'); // Function to unban a user function unbanUser($userId) { global $conn; // Prepare the SQL statement securely $stmt = $conn->prepare("UPDATE users SET status = ? WHERE user_id = ?"); $status = 'Active'; $stmt->bind_param("si", $status, $userId); // Execute the statement and handle the result if ($stmt->execute()) { echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'; } else { echo '<script>Swal.fire("Error", "Error removing user ban: ' . htmlspecialchars($stmt->error) . '", "error");</script>'; } $stmt->close(); } // Check if the request is made via POST and validate user input if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userId'])) { $userId = filter_input(INPUT_POST, 'userId', FILTER_VALIDATE_INT); if ($userId !== false) { unbanUser($userId); } else { echo '<script>Swal.fire("Invalid Input", "Invalid user ID.", "warning");</script>'; } } ?> Just confirming, I do have Sweetalert script included in the header (because it needs to be before any execution). <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> If anyone can work this out I would appreciate it. Thank you
  2. I have just begun dabbling with javascript as a hobby and have a very crude understanding of php so please bare with me, I am a noob! I am using a javascript onclick button to reference the function shown below. function deleteReply(fpid) { $.post("ajax_forumdelete.php", {'reply': fpid}, function (d) { }); location.reload(); } When the button is pressed and the function executes it does as it should. It deletes the forum reply post as its told and the page reloads and the post is gone! But without some sort of explanation, success message or something telling me that it did what its intended is very unsatisfying. I read around and found that an additional function is needed to give me a little message. success : function() { var x="Success"; alert(x); } Looks simple enough and one would think should be easy to incorporate but when I add it in every way shape or form I cannot get it to work. The original function wont even work after adding this. Below is basically what I am wanting to do but not quite sure how to go about it. function deleteReply(fpid) { $.post("ajax_forumdelete.php", {'reply': fpid}, function (d) { }); success : function() { var x="<?php $mtg->success("Reply has been deleted."); ?>"; alert(x); location.reload(); } } I want to use the php $mtg->success() function to echo the message in the pre defined output location and format and want to output the message after the reload... Any ideas on how to go about this?
  3. I am trying to develop an PHP MySQL database application where edit details is not working.I am new to PHP and doing this with the help of various web resources such as youtube videos, tutorials, similar programs etc .I am able to fetch the data from the database, but when it comes to edit, the data remains the same even after changing.Can anyone suggest the solution of this problem. manage-profile.php <?php session_start(); require('connection.php'); //If your session isn't valid, it returns you to the login screen for protection if(empty($_SESSION['sl_no'])){ header("location:access-denied.php"); } //retrive student details from the student table $result=mysqli_query($con, "SELECT * FROM student WHERE sl_no = '$_SESSION[sl_no]'"); if (mysqli_num_rows($result)<1){ $result = null; } $row = mysqli_fetch_array($result); if($row) { // get data from db $stdId = $row['sl_no']; $stdRoll = $row['roll_no']; $stdName = $row['name']; $stdClass = $row['class']; $stdSex= $row['sex']; } ?> <?php // updating sql query if (isset($_POST['update'])){ $myId = addslashes( $_GET[$id]); $myRoll = addslashes( $_POST['roll_no'] ); $myName = addslashes( $_POST['name'] ); $myClass = addslashes( $_POST['class'] ); $myGender = $_POST['sex']; $sql = mysqli_query($con,"UPDATE student SET roll_no='$myRoll', name='$myName', class='$myClass', sex='$myGender' WHERE sl_no = '$myId'" ); // redirect back to profile header("Location: manage-profile.php"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Student Profile Management</title> <link href="css/student_styles.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/user.js"> </script> </head> <body bgcolor="#e6e6e6"> <center><b><font color = "black" size="6">Online Voting System</font></b></center><br><br> <div id="page"> <div id="header"> <h2>Manage Profile</h2> <a href="student.php">Home</a> | <a href="vote.php">Current Polls</a> | <a href="manage-profile.php">Manage My Profile</a> | <a href="changepassword.php">Change Password</a>| <a href="logout.php">Logout</a> </div> <div id="container"> <table border="0" width="620" align="center"> <CAPTION><h3>Update Profile</h3></CAPTION> <form action="manage-profile.php?$id=<?php echo $_SESSION['sl_no']; ?>" method="post" onsubmit="return updateProfile(this)"> <table align="center"> <tr><td>Roll Number:</td><td><input type="text" style="background-color:#e8daef; font-weight:regular;" name="roll_no" maxlength="50" value="<?php echo $row["roll_no"]; ?>"></td></tr> <tr><td>Name:</td><td><input type="text" style="background-color:#e8daef; font-weight:regular;" name="Name" maxlength="30" value="<?php echo $row["name"]; ?>"></td></tr> <tr><td>Class:</td><td><select name='sclass' style='background-color:#e8daef; font-weight:regular;' maxlength='10' id='class' required='true'> <option value='HS-1st Year' <?php if($row["class"]=='HS-1st Year') { echo "selected"; } ?> >HS-1st Year</option> <option value='HS-2nd Year' <?php if($row["class"]=='HS-2nd Year') { echo "selected"; } ?> >HS-2nd Year</option> <option value='BA-1st Sem' <?php if($row["class"]=='BA-1st Sem') { echo "selected"; } ?> >BA-1st Sem</option> <option value='BA-3rd Sem' <?php if($row["class"]=='BA-3rd Sem') { echo "selected"; } ?> >BA-3rd Sem</option> <option value='BA-5th Sem' <?php if($row["class"]=='BA-5th Sem') { echo "selected"; } ?> >BA-5th Sem</option> <option value='BCom-1st Sem' <?php if($row["class"]=='BCom-1st Sem') { echo "selected"; } ?> >BCom-1st Sem</option> <option value='BCom-3rd Sem' <?php if($row["class"]=='BCom-3rd Sem') { echo "selected"; } ?> >BCom-3rd Sem</option> <option value='BCom-5th Sem' <?php if($row["class"]=='BCom-5th Sem') { echo "selected"; } ?> >BCom-5th Sem</option> </select> </td></tr> <tr><td>Sex:</td><td> <input type='radio' style='background-color:#e8daef; font-weight:regular;' name='gender' id='male' value='Male' <?php if($row["sex"]=='Male') { echo "checked"; } ?> >Male<br> <input type='radio' style='background-color:#e8daef; font-weight:regular;' name='gender' id='female' value='Female' <?php if($row["sex"]=='Female') { echo "checked"; } ?> >Female<br></td></tr> <tr><td>&nbsp;</td></tr><tr><td><input type="submit" name="update" value="Update Profile"></td></tr> </table> </form> </div> <div id="footer"> <div class="bottom_addr">Student Union Election,Anonymous College</div> </div> </body> </html>
  4. hey basically my code is something like taxi meter but with time i have made functions that calculates money by minute whenever it reaches a minute the money will add by far i made a confirm button which when i click on it i want to send money and time values to data base how ever i had no errors in all my codes but still the values don't want to be sent to my db help me <form id ="data" method ="post" > <h2 id ="done"></h2> <div class="jumbotron jumbotron-single d-flex align-items-center" style="background-image: url(img/billard.jpg)"> <div class="col-md-3 col-sm-10 text-center mt-2"> <div class="shadow rounded feature-item align-items-center p-2 mb-2" data-aos="fade-up"> <div class="my-4"> <i class="lnr lnr-cog fs-40"></i> </div> <h4>Post 1 </h4> <div id="timer"> <span id="hours">00:</span> <span id="mins">00:</span> <span id="seconds">00</span> <br><span id="money">0TND</span> </div> <div id="controls"> <button id="start">Start</button> <button id="stop">Stop</button> <button id="reset">Reset</button> <button id="confirm" >confirm</button><br> <button id="tarifA">TarifA</button> <button id="tarifB">TarifB</button> <button id="tarifC">TarifC</button> </div> <p>Post de PS5</p> </div> </form> $('#confirm').click(function(e) { e.preventDefault(); clearTimeout(timex); $.ajax({ method: "post", url : "collect.php", data: $('#data').serialize(), datatype: "text", success : function (response){ $('#done').html('done'),1000;} })}); <?php if (isset($_POST['money'])) { sleep(4); $servername='localhost'; $username='root'; $password=''; $dbname = "khalil"; $conn=mysqli_connect($servername,$username,$password,"$dbname"); if($conn){print_r("connected ");} $money=$_POST['money']; $hours=$_POST['hours']; $mins=$_POST['mins']; $seconds=$_POST['seconds']; $sql = "INSERT INTO `history` (`prix`,`time1`,`date1`) VALUES (`$money`,`mins`,`wassim`)"; // insert in database $rs = mysqli_query($conn, $sql); if($rs) { $success= "done"; } } ?>
  5. Hello Phreaks and Geeks, I hope the week has seen you all well and you're all gearing up for a great weekend. I've had to take up relearning of js and new learning of ajax recently and have a simple question I can't seem to resolve. Take this sample form here -> <form action="", method="post", onsubmit="return submitData(this)"> First Name: <br> <input type="text" name="firstname"> <br> Last Name: <br> <input type="text" name="lastname"> <br> Age: <br> <input type="text" name="age"> <br> <input type="submit" id="buttonOne" value="Submit"> </form> I've been passing the morning familiarizing myself with XMLHttpRequest() and FormData() classes and have the following super simple snippets function submitData(fdata) { var formData = new FormData(fdata); for (var pair of formData.entries()) { console.log( pair[0] + ' - ' + pair[1] ); } } AND var formData = new FormData(); formData.append('key_1', 'First value'); formData.append('key_2', 'Second value'); formData.append('key_3', 'Third value'); for (var pair of formData.entries()) { console.log( pair[0] + ' - ' + pair[1] ); } The bottom one, where I create the form data programatically displays the data in console properly. The top one where I try to pull the data from the form does not work. Could someone break down what is happening here and point out the errors in my thinking please. Thank you
  6. I have an index.php file which includes my form and code to move the user's uploaded file to s3. My HTML form calls a js function sendEmails() which makes an AJAX request to another php script dbSystem() to validate the emails input and add it to a database. Everything is working except that the php code in my index.php file (at the very bottom) does not execute. It's supposed to execute when the user uploads a file and presses submit but it doesn't go into the if statement. I tried putting the $fileName = basename($_FILES["fileName"]["name"]) statement before the if statement but I get an undefined index error. I put my a comment in my code to show which if statement I am talking about. This is my HTML code in index.php: <form action="javascript:void(0)" method="POST" id="files" enctype="multipart/form-data"> <label class="col-md-4 col-form-label text-md-right">Select File: <span class="text-danger">*</span></label> <input type="file" id="userFile" name="fileName" style="cursor: pointer; max-width: 170px;" onchange="enableBtn()"> <label class="col-md-4 col-form-label text-md-right">Authorized Users: <span class="text-danger">*</span></label> <input placeholder="Enter e-mail(s) here..." id="req" autocomplete="off"/> <button id="submitBtn" name="submitBtn" class="<?php echo SUBMIT_BUTTON_STYLE; ?>" onclick="return sendEmails()" disabled>Submit</button> </form> This is my php code in index.php: <?php $conn = new mysqli($servername, $username, $password, $db); $sql = "SELECT sender_id, sender_email, receiver_emails, receiver_ids, file_name from filedrop_logs"; $result = mysqli_query($conn, $sql); if ($result) { echo "<div class='outputDiv'>"; echo "<table id='sharedOthers'>"; echo "<thead><tr class='headings'>"; echo "<th class='files'>Files</th>"; echo "<th class='users'>Users</th>"; echo "</tr></thead>"; while ($row = mysqli_fetch_assoc($result)) { $receiverEmails = $row['receiver_emails']; $fileName = $row['file_name']; echo "<tbody id='bodyOthers'>"; echo "<tr id='rowOthers'>"; echo "<td>$fileName<br>"; $objects = getListofObjects('FileDrop'); foreach ($objects as $object) { $file = $object['Key']; $splits = explode('/', $file); if (end($splits) !== '') { $presignedUrl = getPresignedUrlForPrivateFile($object['Key'], '+20 minutes'); $link = '<a href="'.$presignedUrl.'">Download</a>'; echo $link; } } echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=''>Delete</a></td>"; echo "<td>$receiverEmails</td>"; echo "</tr></tbody>"; } echo "</table></div>"; } ?> <?php //the if statement below doesn't execute if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES["fileName"])) { $fileName = basename($_FILES["fileName"]["name"]); $error = $_FILES["fileName"]["error"]; $tmpName = $_FILES["fileName"]["tmp_name"]; if (isset(fileName) && $fileName != '' && $tmpName != '' && sys_get_temp_dir()) { $separator = DIRECTORY_SEPARATOR; $newDir = sys_get_temp_dir() . $separator . "FileDrop" . microtime(true); if (!file_exists($newDir)) { mkdir($newDir, 0777, true); // creates temp FileDrop directory $tempFilePath = $newDir . $separator . $fileName; // creates temp file inside FileDrop directory if (move_uploaded_file($tmpName, $tempFilePath)) { // moves file to tmp folder $s3FileName = "FileDrop" . substr($newDir, 4) . $separator . $fileName; $result = putFileToS3($s3FileName, $tempFilePath, 'public-read'); deleteDir($newDir); } } } } ?> This is my js code in case you want to see it: function sendEmails() { var fileData = $('#userFile').prop('files')[0]; var formData = new FormData(); formData.append('tags', JSON.stringify(tags)); formData.append('fileName', fileData); $.ajax({ type: "POST", url: "../FileDrop/dbSystem.php", processData: false, contentType: false, data: formData, success: function(result) { result = JSON.parse(result); if (result.validity === "valid emails") { location.reload(); resetInputs(); //IMPORTANT $(".outputDiv").show(); } else { var tagsBrackets = result.emails.toString().replace(/[\[\]']+/g,''); var tagsQuotes = tagsBrackets.replace(/['"]+/g, ''); var tagsInvalid = tagsQuotes.replace(/,/g, ", "); $('#alertModal').modal({show:true}); document.getElementById('invalid').textContent = tagsInvalid; } } }); return false; } I've been stuck on this for so long, so I'd really appreciate the help!!
  7. I'm currently trying to building a websocket widget, using node package manager(NPM),WAMPserver and electronjs. the package was well installed because when i start it it works. It log into the console But i dont know how i can handle with html. it seems electronjs is not working fow wamp and websocket
  8. I have this code. The players works and scales to the left side 0-23 but online scales to left side 0-23 instead of right side 0-1. What am I doing wrong? //arrays used in javascript //$labelsdb = array('2018-12-20 00:11', '2018-12-20 00:37', '2018-12-20 00:43', '2018-12-20 03:15', '2018-12-20 03:42', '2018-12-20 03:56', '2018-12-20 04:17', '2018-12-20 04:33', '2018-12-20 07:23', '2018-12-20 10:00', '2018-12-20 12:23', '2018-12-20 14:00', '2018-12-20 18:42', '2018-12-20 19:17', '2018-12-20 23:53'); //$datadb = array(2,12,2,7,23,5,8,2,0,4,0,8,1,0,3); //$datadon = array(1,0,1,1,1,1,1,0,1,1,0,1,1,0,1); //$datadoff = array(0,1,0,0,0,0,0,1,0,0,1,0,0,1,0); var labelsdb = <?php echo json_encode($labelsdb); ?>; //array from database for dates and times var datadb = <?php echo json_encode($datadb); ?>; // array from database for number of players var datadon = <?php echo json_encode($datadon); ?>; // array from database for number of players var datadoff = <?php echo json_encode($datadoff); ?>; // array from database for number of players var todays_date = "20Dec2018"; // todays date //var ctx = document.getElementById("myChart").getContext('2d'); // points to canvas var ctx = document.getElementById("myChart"); // points to canvas ctx.style.backgroundColor = "#2F3136"; //canvas background color var myChart = new Chart(ctx, { type: 'line', data: { labels: labelsdb, //data from database for dates and times datasets: [{ backgroundColor: '#593A45', // color for active players bars in graph label: 'Players', // label for legend yAxisId: 'y-axis-players', data: datadb, //data from database for number of players borderWidth: 1, // border for active players bars in graph borderColor: '#F45E7F', steppedLine: true, //true keeps even line horizontal until change, false displays curved line }, { yAxisId: 'y-axis-online', backgroundColor: '#E5E5E5', // color for active players bars in graph label: 'Online', // label for legend data: datadon, //data from database for number of players borderWidth: 1, // border for active players bars in graph borderColor: '#CECECE', steppedLine: true, //true keeps even line horizontal until change, false displays curved line },] }, options: { responsive: true, //wheteher graph is responsive when zoom in or out maintainAspectRatio: false, legend: { labels: { fontColor: '#FFFFFF' // color of legend label } }, scales: { xAxes: [{ scaleLabel: { display: true, //labelString: updated, //displays date at very bottom of graph fontColor: '#FFFFFF', fontStyle: 'bold', fontSize: 14, }, ticks: { autoSkip: false, maxTicksLimit: 24, maxRotation: 45, //rotate text for hours at bottom of graph minRotation: 45, //rotate text for hours at bottom of graph fontColor: '#FFFFFF', // color of hours at bottom of graph major: { enabled: true, // <-- This is the key line fontStyle: 'bold', //You can also style these values differently fontSize: 14 //You can also style these values differently } }, type: 'time', //to show time at bottom of graph time: { unit: 'hour', displayFormats: { hour: 'hA', //example displays 9AM or 6PM stepSize: 1 //1 for each hour to display at bottom of graph, 2 to show every 2 hrs. } }, display: true, gridLines: { display: true, // display vertical gridline color: '#686868', //color of vertical gridlines zeroLineColor: '#686868' //colors first vertical grid line } }], yAxes: [{ scaleLabel: { display: true, //display label at left vertical side of graph labelString: 'Players', //text to be displayed at left vertical side of graph fontColor: '#FFFFFF', fontStyle: 'bold', fontSize: 14, position: 'left', id: 'y-axis-players', }, ticks: { fontColor: '#FFFFFF', // color of numbers at left side of graph for number of players stepSize: 1 // 1 is to display 0, 1, 2, 3 or 2 will display 0, 2, 4, 6 }, gridLines: { display: true, //display horizontal gridlines color: "#686868" //color of horizontal gridlines } },{ scaleLabel: { display: true, labelString: 'Online', fontColor: '#E5E5E5', fontStyle: 'bold', fontSize: 14 }, position: 'right', id: 'y-axis-online', //type: 'linear', ticks: { min: 0, beginAtZero: true, stepSize: 1, max: 1, fontColor: '#E5E5E5', fontStyle: 'bold', fontSize: 14 }, ticks: { fontColor: '#FFFFFF', // color of numbers at right side of graph for online stepSize: 1 }, gridLines: { display: true, //display horizontal gridlines color: "#686868" //color of horizontal gridlines } }], } } });
  9. Hi all, I am hopeless with Javascript etc but want to do updates, add, delete etc via a Bootstrap Modal. Everything works fine except for Update. No errors etc, just nothing happens. Here is the JS for the Update: $(document).on('click','.update',function(e) { var id=$(this).attr("data-id"); var name=$(this).attr("data-name"); var email=$(this).attr("data-email"); var phone=$(this).attr("data-phone"); var address=$(this).attr("data-address"); $('#id_u').val(id); $('#name_u').val(name); $('#email_u').val(email); $('#phone_u').val(phone); $('#address_u').val(address); }); $(document).on('click','#update',function(e) { var data = $("#update_form").serialize(); $.ajax({ data: data, type: "post", url: "includes/functions.php", success: function(dataResult){ var dataResult = JSON.parse(dataResult); if(dataResult.statusCode==200){ $('#editDriverModal').modal('hide'); alert('Data updated successfully !'); location.reload(); } else if(dataResult.statusCode==201){ alert(dataResult); } } }); }); Here is the php for the Update: if(count($_POST)>0){ if($_POST['type']==2){ $id=$_POST['id']; $name=mysqli_real_escape_string($con, $_POST['name']); $email=$_POST['email']; $phone=$_POST['phone']; $address=$_POST['address']; $query = "UPDATE `drivers` SET `name`='$name',`email`='$email',`phone`='$phone',`address`='$address' WHERE id=$id"; if (mysqli_query($con, $query)) { echo json_encode(array("statusCode"=>200)); } else { echo "Error: " . $query . "<br>" . mysqli_error($con); } mysqli_close($con); } } And finally the Bootstrap form: <!-- Edit Modal HTML --> <div id="editDriverModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <form id="update_form"> <div class="modal-header"> <h4 class="modal-title">Edit User</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <input type="hidden" id="id_u" name="id" class="form-control" required> <div class="form-group"> <label>Name</label> <input type="text" id="name_u" name="name" class="form-control" required> </div> <div class="form-group"> <label>Email</label> <input type="email" id="email_u" name="email" class="form-control" required> </div> <div class="form-group"> <label>PHONE</label> <input type="phone" id="phone_u" name="phone" class="form-control" required> </div> <div class="form-group"> <label>Address</label> <input type="city" id="address_u" name="address" class="form-control" required> </div> </div> <div class="modal-footer"> <input type="hidden" value="2" name="type"> <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel"> <button type="button" class="btn btn-info" id="update">Update</button> </div> </form> </div> </div> </div> Data displays fine inside the Modal so it is communicating with the Database. But just when I click on Update nothing happens. Any help or guidance would really be appreciated. Thanks in advance...
  10. I've been working on JSON and have found a way to send variables from the PHP to the JavaScript using AJAX and no JQuery. For an ecommerce site does it make more sense to send the variables : description, title, cost, etc. to the JavaScript page, or would it make more sense to echo the html on the PHP page? The idea, right now, is a product page for editing and deleting product. Thanks, Josh
  11. Hi Not even sure if this is possible, but well here goes: We have a wholesale site where companies, organisations, clubs etc can buy products. We are setting it up so that these organisations can pick their items then our system will set up a webshop for them, they can then send the link to their employees, members to order the items that the company has chosen ahead of time. our site would be http://www.ourcompanyname.com/productpage.php?companyName=ourClient we would like if poss : http://www.ourcompanyname.com/ClientOrganisationName(either with or without the PHP extension). ClientOrganisationName would be taken from their record in mysql. If this is possible could someone please just tell me what i need to look up. I think wordpress has something similar which is prob where i thought about using on our site. thanks very much, MsKazza.
  12. I have two functions that execute an exe program (personal project for a minecraft back end.) Windows only. First one will execute the sending of commands (THIS ONE WORKS) /* check to see if admin is sending commands to terminal via web */ if(isset($_POST['command'])) { $content = $_POST['command']; writeMCCommandTxt($content); try { exec(SERVER_DIR.'mcCommand.exe',$output); } catch ( Exception $e ) { die ($e->getMessage()); } }// END COMMAND ENTRY This has been a head scratcher for most the week - any help or suggestions would be great!! thanks!! HTML <div id="commands"> <div id="command_input"> <form method="post" id="commandForm" action="index.php"> <label for="command" >Console Command:</label><br/> <input type="text" name="command" autofocuS/> <input type="submit" name="submit_command" value=" >> " /> &nbsp; <input type="button" value="Refresh page" onclick="location.reload(true);" /> </form> </div> </div> This is used to start the server // STARTING SERVER if(isset($_POST['startServerBtn'])){ try { exec(SERVER_DIR.'startServer.bat 2>&1' ,$output); } catch( Exception $e ) { die ($e->getMessage()); } } HTML <div id="server_control"> <ul> <li> <form action="index.php" method="post"> <input type="submit" value="START" id="startServerBtn" name="startServerBtn"/> </form> </li> </ul> </div> MCCOMMANDS.EXE will work from both browser(php) and file manager(tested) the STARTSERVER.EXE will NOT work from browser(php), but will work from file manager The function IS being accessed - debug is showing it going there, and it seems to be running Both exe's are in the same folder
  13. I have made an ajax call (using file activedirectory.php) to active directory to retrieve information such as name,thumbnail photo,mail etc. the ajax call is made on click of a name in a leaderboard ,to fetch only that person's info by matching the post['id']. The problem is that I am unable to retrieve any information and the console gives me an error saying : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data the error type makes it clear that it is unable to pull any data whatsoever. .php file that has been used here :(activedirectory.php) -- <?php /** * Get a list of users from Active Directory. */ $ad_users = ''; $message = ''; $ldap_password = 'Qwerty@33xxxxxx'; $ldap_username = 'maxxxxxxxxxxxx'; $server = 'ldap://xxxxxxxxxx'; $domain = '@asia.xxxxxx.com'; $port = 389; $ldap_connection = ldap_connect($server, $port); if (FALSE === $ldap_connection){ // Uh-oh, something is wrong... } // We have to set this option for the version of Active Directory we are using. ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version'); ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search. if (TRUE === ldap_bind($ldap_connection, $ldap_username.$domain, $ldap_password)){ $base_dn = "OU=Employees,OU=Accounts,OU=xxxxx,DC=xxxxx,DC=xxxxxx,DC=com"; $kid = 'NonExistingAccount'; if (preg_match('#SAM_NAME_MATCHING_REGEX#', $_POST['id'])) { $kid = $_POST['id']; } $search_filter = "(&(objectCategory=person)(samaccountname={$kid}))"; $attributes = array(); $attributes[] = 'givenname'; $attributes[] = 'mail'; $attributes[] = 'samaccountname'; $attributes[] = 'sn'; $result = ldap_search($ldap_connection, $base_dn, $search_filter, $attributes); $maxPageSize = 1000; if (FALSE !== $result){ $entries = ldap_get_entries($ldap_connection, $result); for ($x=0; $x<$entries['count']; $x++){ if (!empty($entries[$x]['givenname'][0]) && !empty($entries[$x]['mail'][0]) && !empty($entries[$x]['samaccountname'][0]) && !empty($entries[$x]['sn'][0]) && 'Shop' !== $entries[$x]['sn'][0] && 'Account' !== $entries[$x]['sn'][0]){ $ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0])); } } } ldap_unbind($ldap_connection); // Clean up after ourselves. } $message .= "Retrieved ". count($ad_users) ." Active Directory users\n"; ?> the javascript that has been used here : $('.leaderboard li').on('click', function () { $.ajax({ url: "../popupData/activedirectory.php", // your script above a little adjusted type: "POST", data: {id:$(this).find('.parent-div').data('id')}, success: function(data){ console.log(data); data = JSON.parse(data); $('#popup').fadeIn(); //whatever you want to fetch ...... // etc .. }, error: function(){ alert('failed, possible script does not exist'); } }); });
  14. Hello, Im hoping to get help from here, i have arrays of text fields that i need to get sums,.. <div class='fldgroup'> <input type="text" name="fld[0]"> <input type="text" name="fld[0]"> <input type="text" name="fld[0]"> <input type="text" name="sumfld[0]"> <button>Add Another Field</button> <input type="text" name="fld[1]"> <input type="text" name="fld[1]"> <input type="text" name="fld[1]"> <input type="text" name="sumfld[1]"> <button>Add Another Field</button> </div> <button>Add Another Group</button> how can i get the sum of all fld[0] and put it to sumfld[0] same as the fld[1] to sumfld[1],.. every text field is dynamically added using clone., i hope somebody can help me with this.... Thank you in advance...
  15. I have a single Form which allows user to create a new Gift Voucher record. It is split into 3 input areas Voucher Details, Payment Details and Delivery Details. ​ I want to add a button on the Payment details section which when activated will copy some of the entered fields from the Payment section to some of the fields in the Delivery section as follows: - FROM PAYMENT SECTION TO DELIVERY SECTION PurchaserName DeliveryName PAddressLine1 DAddressLine1 PAddressLine2 DAddressLine2 PCounty DCounty PPostCode DPostCode I am using a Code Building product called PHP Runner which when you add a button gives you a properties widget as per attachment in which to place your bespoke code.
  16. So I have a code that is suppose to save form sessions and then redirect to another website. It does redirect but the sessions are never saved when I go back to my site. And yes, I do have session_start() at the very top of the page. And also, the sessions do get saved on locahost server but not live server. Do you know why this is happening? Here's the code example. if(isset($_POST['submit'])) { $name = trim($_POST['name']); $email = trim($_POST['email']); $_SESSION['name'] = $name; $_SESSION['email'] = $email; $errors = array(); $db->beginTransaction(); if(empty($name)) { $errors[] = 'Name is required.'; } if(empty($email)) { $errors[] = 'Email is required.'; } if(empty($errors)) { $db->commit(); $new_url = 'https://www.google.ca/'; ?> <script> window.location.href = '<?php echo $new_url; ?>'; </script> <?php exit(); } else { $db->rollBack(); } }
  17. Hi Mate, I need help on using the jquery clone method. i have this html script that i clone <div class="col-md-2 col-sm-3 col-lg-1 nopadding"> <input id="length" class="form-control input-sm nopadding" type="text" onchange="compute('floor','length','width','sqft');" placeholder="Length" maxlength="4" name="length"> </div> Then when i cloned, it outputs this with id appending an incremented number at the end of the original id. example (length to length1) which is correct. <div class="col-md-2 col-sm-3 col-lg-1 nopadding"><input id="length1" class="form-control input-sm nopadding" type="text" onchange="compute('floor','length','width','sqft');" placeholder="Length" maxlength="4" name="length"> </div> Now how can i pass the same ids to the onchange event so it should output compute('floor1','length1','width1','sqft1'). at the moment it did not pass the incremented id to the method. here is my javascript: function addrow(){ var template = $('#rowsec').clone(); rCount++; var attendee = template.clone().find(':input').val(0).each(function(){ var newId = this.id.substring(0, this.id.length) + rCount; this.id = newId; }).end() .attr('id', 'rowsec' + rCount) .appendTo('#rows'); } Thank you in advance.
  18. Guys recently i finished a infinite scroll to one of my projects using jquery, php and mysql. After creating that i face the problem of tinymce editor not binding to the dynamically generated textarea. What should i do? here is the code for tinymce editor: tinymce.init({ menubar:false, forced_root_block : "", selector: "textarea#wall_edit_1", entities : '160,nbsp,162,cent,8364,euro,163,pound', theme: "modern", resize: false, height: 200, plugins: [ " autolink link image preview hr anchor pagebreak spellchecker", "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking", "save table contextmenu directionality emoticons paste textcolor" ], content_css: "css/content.css", toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | l ink image | print preview media fullpage | emoticons", style_formats: [ {title: 'Bold text', inline: 'b'}, // {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}}, {title: 'Header', block: 'h1'}, {title: 'Example 1', inline: 'span', classes: 'example1'}, {title: 'Example 2', inline: 'span', classes: 'example2'}, {title: 'Table styles'}, {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'} ] }); here is the php code that dynamically generates the textarea while using the infinite scroll feature in jquery: if ($author==$_SESSION['uname'] || $account_name==$_SESSION['uname']) { $statusdeletebutton='<li>' . '<a type="'.$updateid.'" class="btn delete_4_session hidden_text_delete_'.$updateid.' glyphicon glyphicon-trash delete_status_btn" title="Delete this status and its replies">Remove</a></li>'; $edit_btn='<li>' . '<a attr="'.$updateid.'" type="'.$updateid.'" class="btn edit_4_session hidden_text_edit glyphicon glyphicon-pencil" title="Edit this status" >Edit</a></li>'; $statusui_edit="<div type='".$updateid."' class='hidden_edit_4_session session_editor".$updateid." jumbotron'>" . "<a type='".$updateid."' class='btn pull-right close_edit' title='Close without editing'>Close X</a>" . "<input type='text' class='form-control title_s_edit title_s_".$updateid."' name='status_title' value='".html_entity_decode($title)."' placeholder='Title' >" . "<span> </span>" . "<textarea id='wall_edit_1' type='".$updateid."' rows='5' cols='50' class='session_edit text_value_".$updateid."' wrap='hard' placeholder='whats up ".$session_uname."'> ".html_entity_decode($data1)."</textarea><br>" . "<button style='float:right;' value='".$updateid."' type='a' class='btn btn-warning btn btn-large btn-lg post-s-edit'>Update</button></div>" ; }else{ $statusdeletebutton=""; $edit_btn="<li class='posted'>You are not the owner of this Post</li>"; $statusui_edit=""; } echo $statusui_edit.''. $hidden_text.'<div attr="'.$updateid.'" type="'.$updateid.'" class="statusboxes status_'.$updateid.' jumbotron">' . '<h3 class="pull-left title">' . '<div id="'.$updateid.'" class="title_s_2copy posted" value="'.html_entity_decode($title).'">'.html_entity_decode($title).'</div></h3>' . '<span class="pull-right">' . '<div class="dropdown">' . '<button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown" >' . '<span class="glyphicon glyphicon-edit"></span></button>' . '<ul class="dropdown-menu">' .$edit_btn .' '. $statusdeletebutton .'</ul></div></span><br><hr>' . '<legend><span style="font-size: 13.5px;" class=" data_s_2copy" type="'.$updateid.'" >' . html_entity_decode($data1).'</span></legend><b class="posted"><small>Posted by:- <a href="home.php?u='.$author.'"><img src="'.$feed_pic.'" height="20px" width="20px"> '.$author. '</a> '.$datemade.'</small></b>' . '<br><legend>'.$like.' | '.$unlike. ' | '.$share_button.'<h4><a id="'.$updateid.'" class="btn collap-btn">Comments</a></h4></legend>';
  19. I can't figure out how to make this script (twitch(dot)tv) to show only online/live channels not all... Here is Javascript (function () { 'use strict'; angular .module('twitch', []) .controller('TwitchCtrl', TwitchCtrl); function TwitchCtrl($http, $scope) { $scope.streams=[]; var apiEndPoint = 'https://api.twitch.tv/kraken/streams/'; var streamers = ['Chizijs','tornis', 'elveeftw', 'piecits', 'lobosjr', 'fattypillow']; var apiSuccess = function(response, streamer){ console.log(response); var stream = response.data; stream.Name = streamer; var offline = stream.stream === null if(offline){ stream.stream = {game: 'offlines', channel:{ 'logo': '' }}; $scope.streams.push(stream); } else{ $scope.streams.unshift(stream); } console.log(stream); }; var apiError = function(response, streamer){ console.log(response); if(response.status === 422){ var stream = response.data; stream.Name = streamer; stream.stream = {game: 'Account Closed', channel:{ 'logo': ''}}; console.log(stream); $scope.streams.push(stream); } }; var setupSuccess = function(streamer){ return function(response){ return apiSuccess(response, streamer); }; }; var setupError = function(streamer){ return function(response){ return apiError(response, streamer); }; }; for(var i = 0; i < streamers.length; i++){ var onSuccess = setupSuccess(streamers[i]); var onError = setupError(streamers[i]); $http({url: apiEndPoint + streamers[i], method:'GET'}) .then(onSuccess, onError); } } })();
  20. Can some one help to generate a unique Doctor Appointment ID when some one save the registration form, I am trying to make online doctor appoint booking system, I want something like for each doctor, each date, it will generate a unique id, that may be something like following Dr_ID-Date-Auto increment number( DR001-03-23-2016-0001 ) If any one have better idea to generate a short and unique id, please suggest me. I am a beginner in PHP, please help me guys
  21. Hi guys, I have a video into a bootstrap modal form that is opened on click. Now when i close the modal i want that video to stop playing. I've manage to do some javascript to do that but instead of stopping the the video i want it stops all the video from that page. How can i target in the script below only the ID of the modal that i want to be stoped from playing? <script> $('body').on('hidden.bs.modal', '.modal', function () { $('video').trigger('pause'); }); </script>
  22. Hi guys. I have a Bootstrap modal that opens on click. Inside is a form with 4 fields. Now i want after the form is submited to show below the submit button a thank yo message, but instead of that the form closes and the page is beeing refreshed. I've manage to do some javascript to stop the form of beeing refreshed but now i want to know how can i make the thank you div to get showed below the submit button. <script> $(function () { var frm = $('#participa-modal'); frm.submit(function (ev) { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { $(".alert-success").html(data); location.reload(); } }); ev.preventDefault(); }); }); </script>
  23. Edit: upload blob not blog I would like to use the following code to crop images that will be uploaded to mySql with PHP. I just cannot figure out how to call the blob so I can use it. Can someone help me with this? Using the code from here: http://hongkhanh.github.io/cropbox/ HTML <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Crop Box</title> <link rel="stylesheet" href="style.css" type="text/css" /> <style> .container { position: absolute; top: 10%; left: 10%; right: 0; bottom: 0; } .action { width: 400px; height: 30px; margin: 10px 0; } .cropped>img { margin-right: 10px; border:1px solid green: } </style> </head> <body> <script src="../cropbox.js"></script> <div class="container"> <div class="imageBox"> <div class="thumbBox"></div> <div class="spinner" style="display: none">Loading...</div> </div> <div class="action"> <input type="file" id="file" style="float:left; width: 250px"> <input type="button" id="btnCrop" value="Crop" style="float: right"> <input type="button" id="btnZoomIn" value="+" style="float: right"> <input type="button" id="btnZoomOut" value="-" style="float: right"> </div> <div class="cropped"></div> <script type="text/javascript"> window.onload = function() { var options = { imageBox: '.imageBox', thumbBox: '.thumbBox', spinner: '.spinner', imgSrc: 'avatar.png' } var cropper = new cropbox(options); document.querySelector('#file').addEventListener('change', function(){ var reader = new FileReader(); reader.onload = function(e) { options.imgSrc = e.target.result; cropper = new cropbox(options); } reader.readAsDataURL(this.files[0]); this.files = []; }) document.querySelector('#btnCrop').addEventListener('click', function(){ var img = cropper.getDataURL(); document.querySelector('.cropped').innerHTML += '<img src="'+img+'">'; }) document.querySelector('#btnZoomIn').addEventListener('click', function(){ cropper.zoomIn(); }) document.querySelector('#btnZoomOut').addEventListener('click', function(){ cropper.zoomOut(); }) }; </script> </body> </html> /** * Created by ezgoing on 14/9/2014. */ 'use strict'; var cropbox = function(options){ var el = document.querySelector(options.imageBox), obj = { state : {}, ratio : 1, options : options, imageBox : el, thumbBox : el.querySelector(options.thumbBox), spinner : el.querySelector(options.spinner), image : new Image(), getDataURL: function () { var width = this.thumbBox.clientWidth, height = this.thumbBox.clientHeight, canvas = document.createElement("canvas"), dim = el.style.backgroundPosition.split(' '), size = el.style.backgroundSize.split(' '), dx = parseInt(dim[0]) - el.clientWidth/2 + width/2, dy = parseInt(dim[1]) - el.clientHeight/2 + height/2, dw = parseInt(size[0]), dh = parseInt(size[1]), sh = parseInt(this.image.height), sw = parseInt(this.image.width); canvas.width = width; canvas.height = height; var context = canvas.getContext("2d"); context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh); var imageData = canvas.toDataURL('image/png'); return imageData; }, getBlob: function() { var imageData = this.getDataURL(); var b64 = imageData.replace('data:image/png;base64,',''); var binary = atob(b64); var array = []; for (var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type: 'image/png'}); }, zoomIn: function () { this.ratio*=1.1; setBackground(); }, zoomOut: function () { this.ratio*=0.9; setBackground(); } }, attachEvent = function(node, event, cb) { if (node.attachEvent) node.attachEvent('on'+event, cb); else if (node.addEventListener) node.addEventListener(event, cb); }, detachEvent = function(node, event, cb) { if(node.detachEvent) { node.detachEvent('on'+event, cb); } else if(node.removeEventListener) { node.removeEventListener(event, render); } }, stopEvent = function (e) { if(window.event) e.cancelBubble = true; else e.stopImmediatePropagation(); }, setBackground = function() { var w = parseInt(obj.image.width)*obj.ratio; var h = parseInt(obj.image.height)*obj.ratio; var pw = (el.clientWidth - w) / 2; var ph = (el.clientHeight - h) / 2; el.setAttribute('style', 'background-image: url(' + obj.image.src + '); ' + 'background-size: ' + w +'px ' + h + 'px; ' + 'background-position: ' + pw + 'px ' + ph + 'px; ' + 'background-repeat: no-repeat'); }, imgMouseDown = function(e) { stopEvent(e); obj.state.dragable = true; obj.state.mouseX = e.clientX; obj.state.mouseY = e.clientY; }, imgMouseMove = function(e) { stopEvent(e); if (obj.state.dragable) { var x = e.clientX - obj.state.mouseX; var y = e.clientY - obj.state.mouseY; var bg = el.style.backgroundPosition.split(' '); var bgX = x + parseInt(bg[0]); var bgY = y + parseInt(bg[1]); el.style.backgroundPosition = bgX +'px ' + bgY + 'px'; obj.state.mouseX = e.clientX; obj.state.mouseY = e.clientY; } }, imgMouseUp = function(e) { stopEvent(e); obj.state.dragable = false; }, zoomImage = function(e) { var evt=window.event || e; var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta; delta > -120 ? obj.ratio*=1.1 : obj.ratio*=0.9; setBackground(); } obj.spinner.style.display = 'block'; obj.image.onload = function() { obj.spinner.style.display = 'none'; setBackground(); attachEvent(el, 'mousedown', imgMouseDown); attachEvent(el, 'mousemove', imgMouseMove); attachEvent(document.body, 'mouseup', imgMouseUp); var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel'; attachEvent(el, mousewheel, zoomImage); }; obj.image.src = options.imgSrc; attachEvent(el, 'DOMNodeRemoved', function(){detachEvent(document.body, 'DOMNodeRemoved', imgMouseUp)}); return obj; };
  24. I am new to Javascript, so please forgive me if this is a dumb question See attached screen shot. My JS code computes the value of "cost" and it sets it into the input of a a form using row.val(cost). When it has calculated all the costs for all the products, adding, subtracting and multiplying, I want to find the total. So, I now scan through all the cost inputs using an "each" method and create a sum total. Problem: the calculated cost inputs are visible on the screen. If a user changes their mind about the quantity required on a particular line item, the grand total must be recalculated. However the line totals are calculated. Therefore, they do not appear in the source code, so, I can not grab them using the selector $("input.cost") Question: How do I grab the values of the computed cost values which are visible in the input fields? row.data('price') // THIS IS DECLARED IN AN EARLIER FUNCTION. var runningTotal = 0; // THIS IS DECLARED AS A GLOBAL $("input.quantity").on('change', function() { var row = $(this).parents(':eq(1)').find('input').filter(".cost"); var price = row.data('price'); if (price) { var quantity = parseFloat($(this).val()); var cost = (price * quantity); row.val(cost); // COST INSERTED HERE!! $("input.cost").each(function(){ var ic = $(this).val(); // TRIED USING HTML AND TEXT METHODS. var inputCost = Number(ic); runningTotal += inputCost; }); $("#total").val(runningTotal); } HTML for a typical row: ( I am using Laravel Blade, however this is the rendered HTML) <div class="well form-group "> <div class="col-sm-2 col-md-2"><label for="underlay2">Underlayments:</label></div> <div class="col-sm-4 col-md-4"><select class="form-control product_id" name="product_code[4]"><option selected="selected" value="">None</option><option value="789">BP #15 Plain Felt 36" | $10.00</option><option value="790">BP #30 Plain Felt 36" | $10.00</option></select></div> <div class="col-sm-1 col-md-1"><label for="underlay2_req">Quantity:</label></div> <div class="col-sm-2 col-md-2"><input class="form-control quantity" name="quantity[4]" type="text"></div> <div class="col-sm-1 col-md-1"><label for="cost">Cost:</label></div> <div class="col-sm-2 col-md-2"><input class="form-control cost" readonly="readonly" name="cost[0]" type="text" value=""></div> </div>
  25. Hello Mate, I would like to seek help... i have this json script which gets the names of the users from my database: $sql=mysql_query("SELECT firstname FROM tblusers WHERE usertype=1"); $u = array(); while($rs=mysql_fetch_array($sql)){ $u[] = $rs['firstname']; } print json_encode($u); And getting this to javascript function through ajax: function uList(){ $.ajax({ type: "POST", url: "techs.php", success: function(data) { console.log(data); return data; } }); } my console.log shows the correct format i want to get, but it doesn't display on my calendar page.... ["user1","user2","user3","user4","user5"]... im using this code to send data to my calendar script. users:uList, Any help is very much appreciated. Thank you
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.