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, I have a php script that generates a select dropdown box <option value="1"> Bob </option> <option value="2"> Tim </option> <option value="3"> Sam </option> <option value="4"> Phil </option> I then have the following javascript to produce my google api graph: <script type="text/javascript"> google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart); function drawChart() { var jsonData = $.ajax({ url: "test1.php", dataType:"json", async: false, }).responseText; var data = new google.visualization.DataTable(jsonData); var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data); } </script> This then runs a php script that returns the data back in Json format. How can I pass the <option value=""> through the to the test1.php script to generate the json data based on the the value selected i.e 1, 2, 3 etc. i an new at javascript and the google api can anyone let me know how I can get this variable sent through by the google api script. and for the graph to refresh every time another option is chosen. Thanks kris
  2. After image is drop into container , I want to move copy of the original image to be move when original image dragend within container. I tried but it display copy image each time when original image dragend. can anyone help me? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Prototype</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script> <style> body{padding:20px;} #container{ border:solid 1px #ccc; margin-top: 10px; width:350px; height:350px; } #toolbar{ width:350px; height:35px; border:solid 1px blue; } </style> <script> $(function(){ var $house=$("#house"); $house.hide(); var $stageContainer=$("#container"); var stageOffset=$stageContainer.offset(); var offsetX=stageOffset.left; var offsetY=stageOffset.top; var stage = new Kinetic.Stage({ container: 'container', width: 350, height: 350 }); var layer = new Kinetic.Layer(); stage.add(layer); var image1=new Image(); image1.onload=function(){ $house.show(); } image1.src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"; $house.draggable({ helper:'clone', }); $house.data("url","house.png"); // key-value pair $house.data("width","32"); // key-value pair $house.data("height","33"); // key-value pair $house.data("image",image1); // key-value pair $stageContainer.droppable({ drop:dragDrop, }); function dragDrop(e,ui){ var x=parseInt(ui.offset.left-offsetX); var y=parseInt(ui.offset.top-offsetY); var element=ui.draggable; var data=element.data("url"); var theImage=element.data("image"); var image = new Kinetic.Image({ name:data, x:x, y:y, image:theImage, draggable: true, dragBoundFunc: function(pos) { return { x: pos.x, y: this.getAbsolutePosition().y } } }); image.on("dragend", function(e) { var points = image.getPosition(); var image1 = new Kinetic.Image({ name: data, id: "imageantry", x: points.x+65, y: points.y, image: theImage, draggable: false }); layer.add(image1); layer.draw(); }); image.on('dblclick', function() { image.remove(); layer.draw(); }); layer.add(image); layer.draw(); } }); // end $(function(){}); </script> </head> <body> <div id="toolbar"> <img id="house" width=32 height=32 src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"><br> </div> <div id="container"></div> </body> </html>
  3. In the following code only one image is draggable.How can i make multible image in toolbar to be draggable dynamically?Anyone help me? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Prototype</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script> <style> body{padding:20px;} #container{ border:solid 1px #ccc; margin-top: 10px; width:350px; height:350px; } #toolbar{ width:350px; height:35px; border:solid 1px blue; } </style> <script> $(function(){ // get a reference to the house icon in the toolbar // hide the icon until its image has loaded var $house=$("#house"); $house.hide(); // get the offset position of the kinetic container var $stageContainer=$("#container"); var stageOffset=$stageContainer.offset(); var offsetX=stageOffset.left; var offsetY=stageOffset.top; // create the Kinetic.Stage and layer var stage = new Kinetic.Stage({ container: 'container', width: 350, height: 350 }); var layer = new Kinetic.Layer(); stage.add(layer); // start loading the image used in the draggable toolbar element // this image will be used in a new Kinetic.Image var image1=new Image(); image1.onload=function(){ $house.show(); } image1.src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"; // make the toolbar image draggable $house.draggable({ helper:'clone', }); // set the data payload $house.data("url","house.png"); // key-value pair $house.data("width","32"); // key-value pair $house.data("height","33"); // key-value pair $house.data("image",image1); // key-value pair // make the Kinetic Container a dropzone $stageContainer.droppable({ drop:dragDrop, }); // handle a drop into the Kinetic container function dragDrop(e,ui){ // get the drop point var x=parseInt(ui.offset.left-offsetX); var y=parseInt(ui.offset.top-offsetY); // get the drop payload (here the payload is the image) var element=ui.draggable; var data=element.data("url"); var theImage=element.data("image"); // create a new Kinetic.Image at the drop point // be sure to adjust for any border width (here border==1) var image = new Kinetic.Image({ name:data, x:x, y:y, image:theImage, draggable: true, // restrict to allow horizontal dragging only dragBoundFunc: function(pos) { // if(pos.x<this.minX){ pos.x=this.minX; } // this.minX=pos.x; return { x: pos.x, y: this.getAbsolutePosition().y } } }); layer.add(image); layer.draw(); } }); // end $(function(){}); </script> </head> <body> <div id="toolbar"> <img id="house" width=32 height=32 src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"><br> </div> <div id="container"></div> </body> </html>
  4. For eg. I have a page with a query that retrives records from the database and I want to have options of filtering out the shown records by date, time, likes, views..etc; how would I go about doing that? The way I am thinking is having a html form with those filter inputs and using a relative query based on the filter selection to retrive the results. What you think?
  5. Code works when... <script type="text/javascript"> var currenttime = '<?php print gmdate('F d, Y H:i:s', time() + (1 * 60 * 60))?>' var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December") var serverdate=new Date(currenttime) function padlength(what){ return (what.toString().length==1)? "0"+what : what } function displaytime(){ serverdate.setSeconds(serverdate.getSeconds()+1) var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear() var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds()) document.getElementById("servertime").innerHTML=datestring+" "+timestring } window.onload=function(){ setInterval("displaytime()", 1000) } </script> Code not works when... <script type="text/javascript" src="clock.js"> I want to use second option. Any help?
  6. Below is my code that is suppose to insert and show records from database using ajax. Retrieving the records from the database works. However it won't insert a record. I do not get any errors. The page simply refreshes when I hit submit button. Can you see what might be wrong in my code? index.php <script> $(document).ready(function(){ function showComment(){ $.ajax({ type:"post", url:"process.php", data:"action=showcomment", success:function(data){ $(".wrapper").html(data); } }); } showComment(); $("#submit").click(function(){ var name=$("#name").val(); var message=$("#details").val(); $.ajax({ type:"post", url:"process.php", data:"name="+name+"&details="+message+"&action=addcomment", success:function(data){ showComment(); } }); }); }); </script> $id = $_GET['id']; $title = $_GET['title']; $_SESSION['id'] = $id; $_SESSION['title'] = $title; <div class="wrapper"></div> <form action="" method="post" enctype="multipart/form-data"> <div class="newfield"> <label for="title">Name <span class="highlight">*</span></label> <input id="name" type="text" name="name"> </div> <div class="newfield"> <label for="details">Details <span class="highlight">*</span></label> <textarea id="details" name="details""></textarea> </div> <input type="submit" name="submit" id="submit" value="Submit Tale"> </form> process.php <?php require_once '/core/init.php'; $id = $_SESSION['id']; $action = $_POST['action']; if($action == 'showcomment') { try { $get = $db->prepare("SELECT * FROM sub_posts WHERE id = :id"); $get->bindParam('id', $id); $get->execute(); $getStmt = $get->fetchAll(PDO::FETCH_ASSOC); if(count($getStmt) > 0) { foreach($getStmt as $row) { $new_name = $row['name']; $new_details = $row['details']; ?> <ul> <li> <?php echo $new_name; ?> </li> <li> <?php echo $new_details; ?> </li> </ul> <?php } } else { // no records found. } } catch(Exception $e) { die($e->getMessage()); } } else if($action == 'addcomment') { $name = $_GET['name']; $details = $_GET['details']; try { $insert = $db->prepare("INSERT INTO sub_posts(id, name, details) VALUES(:id, :name, :details)"); $insert->bindParam('id', $id); $insert->bindParam('name', $name); $insert->bindParam('details', $details); $insert->execute(); if($insert == false){ echo 'record could not be inserted.'; } else { echo 'record has been inserted.'; } } catch(Exception $e) { die($e->getMessage()); } } else { echo 'no results.'; }
  7. I have seen a couple of other threads relatively similar but I still find my problem unique so I hope you guys give me a chance. What I want to do: use proxy to bypass same origin policy and to save these values (that changes and need to be checked by timer) into variables that can be modified. A server contains data.asp which looks something like this and updates from time to time (although with a bit more data): { "Title":"Tile of song" ,"Artist":"The artist" ,"Album":"The album" ,"CDCover":"/covers/randomcover.jpg" } The method I have tried is like the one on http://qnimate.com/same-origin-policy-in-nutshell/#Same_Origin_Policy_for_AJAX. In case you guys don't want to follow the link I've posted the data here as well. <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","http://www.qnimate.com/ajaxdata.php",true); xmlhttp.send(); } </script> </head> <body> <button type="button" onclick="loadXMLDoc()">Request data</button> <div id="myDiv"></div> And the proxy file: <?php echo file_get_contents('http://www.qscutter.com/ajaxdata.txt'); ?> So what I want to do is store the data into variables that I can alter, not show it inside a div using innerHTML. Preferably check this ever so often for changes as well. Suggestions? I can add that I have the permission from the server owner to retrieve the information and to use it but no possibility to add script to their server, hence the proxy bypass attempt.
  8. I have short urls on the same page that this javascript code is on. the problem is that the code now can't find the poll.php. I have tried the full path and full url to the poll.php, but the code still outputs file not found. how to get this code working? $.post('poll.php', $(this).serialize(), function(data, status){
  9. Can anyone help by shedding some light with a little problem I encounter using JSON endpoint requests. I'm not very good with PHP. When the endpoint is called and finds no data, I want to replace it with a local image source. In this case, I am calling brewery->logo_url. Most entries have endpoints, but some don't. When an image link is found at the endpoint, it throws off my layout. You can see the ones that look off. They align to the left. I want to replace with a logo default image each time this happens, with hopes to set the layout adjust back to normal. Here's my working document http://graintoglass.com/fb/tap-menu-test.php and here's the JSON. http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short Code Effort <?php $url = 'http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short&servingtype=bottlecan'; $curl_session = curl_init($url); curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($curl_session, CURLOPT_TIMEOUT, 10); $data = curl_exec($curl_session); curl_close($curl_session); $beer_list = json_decode($data); echo '<p class="last-updated">Last Updated: ' . date("m/d/Y") . '</p>'; echo '<h1 class="page-title">Bottle List</h1>'; echo '<p class="page-intro">Not only do we serve a hefty list of brews on tap, we also offer an exclusive list of beers in bottle. Our bottle list is constantly changing so the occasional return visits to browse this list is the best way to stay up to date. Take a look!</p>'; foreach ($beer_list as $beer) { echo '<article class="beer-entry"> <div class="beer-image"><img src="'.$beer->brewery->logo_url.'" /></div> <div class="beer-info"> <p class="brewery-name">'.$beer->brewery->name.' — '.$beer->brewery->origin.'</p> <h2 class="beer-name">'.$beer->beer->name.'</h2> <p class="beer-style">Beer Style: '.$beer->beer->style.'</p> <p class="beer-description">'.$beer->descriptions->short_description.'</p> <p class="beer-abv">ABV: '.$beer->beer->abv.' / IBU: '.$beer->beer->ibu.'</p> <p class="beer-ibu"></p> </div> <div class="clearfix"></div> </article> '; } echo '<p class="page-bottom">If you would like to see more of our food and beer options, <a href="https://www.graintoglass.com" target="_blank">visit our website</a>.</p>'; ?>
  10. I want to fetch items from a database and be able to update their quantity by selecting a number from a drop down selection and press the button "Update quantity" to perform the action. I have the following php code: echo '<table border="4"> <tr> <th>ID</th> <th>Item Name</th> <th>Current Quantity</th> <th>New Quantity</th> <th>Update</th> </tr>'; for($i=0 ;$i<$k; $i++) $z = $i+1; //fetch data from database $id = the id of the row that the entry/item is at $item_name = the name of the item $current_quantity = the current quantity of the item //create a table of entries echo '<tr'> <td>'.$z.'</td> <td>'.$item_name.'</td> <td>'.$current_quantity.'</td> <td> <select id="quantity" name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> . . . </select> </td>'; echo '<td> <button type="button" value="'.$id.'" name="updatebtn" id="updatebtn">Update Quantity</button> </td>'; echo '</tr>'; Where k = number or matches in database The result is something like this: //////////////////////////////////////////////////////////////////////////// ///ID // Item Name // Current Quantity // New Quantity // Update /// //////////////////////////////////////////////////////////////////////////// // 1 // Shoes // 10 // 12 // Update Quantity // //////////////////////////////////////////////////////////////////////////// // 2 // T-shirts // 5 // 8 // Update Quantity // //////////////////////////////////////////////////////////////////////////// // 3 // Watches // 4 // 2 // Update Quantity // //////////////////////////////////////////////////////////////////////////// The first 3 columns are populated by the database and New Quantity by the user. As soon as the user is done with the new quantity he/she presses "Update Quantity" to update the database. Below is the jQuery code i use: $(document).ready(function(){ $('#updatebtn').click(function(){ //i use this value to find the exact entry in the database var id = $('#updatebtn').attr('value'); var quantity_selected = $('select#quantity option:selected').attr('value'); $.ajax({ type: "POST", url: "js/ajax/updatequantity.php", data: {id: id, new_quantity: quantity_selected} }); //this is for testing alert('ok'); }); }); The updatequantity.php script just takes the new quantity and the row of the entry and updates the value. My problem is: If i press the "Update Quantity" of the item "Shoes", i see the pop-up "ok" and the quantity is updated. But when i try to do the same for the 2 other items (T-shirts and watches), i get nothing. Does my js script has trouble to differentiate between the "Update Quantity" buttons? Is there another approach? ps: i am doing this using wamp on my localhost Thanks in advance.
  11. Here goes. I am trying to retrieve info. from mySql database and update 3 textfields. I also have 4 selects on the form that need populating during the running of the program. My problem is using console I can see the info - Customer name - but it does not appear in the text field. The onchange request in the DIV container seems to be where it fails. Here are the files I am using: 1. add_an_order.php <html> <head> <title>Add an Order</title> <link href = "css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="include/jquery-1.11.1.min.js"></script> </head> <body> <div id="header"><img src="images/logo.png" /></div> <div id="nav"> <div id="nav_wrapper"> <ul> <li><a href="index.php">Orders</a></li><li> <a href="customers.php">Customers</a></li><li> <a href="contacts.php">Contacts</a></li><li> <a href="batteries.php">Batteries</a></li><li> <a href="#">Queries</a> </li> </ul> </div> </div> <div id="main"> <?php echo '<h3 id="menOpt">Add an Order</h3><hr>'; // Check for a form submission. /* if ($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = array(); $required_fields = array('customer_name', 'customer_address', 'city', 'telephone'); foreach ($required_fields as $fieldname) { if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) { $errors[] = strtoupper($fieldname); } } if (empty($errors)) { include ('include/dbconnect.php'); $name = mysqli_real_escape_string($con, trim(strip_tags($_POST['customer_name']))); $contact = mysqli_real_escape_string($con, trim(strip_tags($_POST['contact']))); $address = mysqli_real_escape_string($con, trim(strip_tags($_POST['customer_address']))); $city = mysqli_real_escape_string($con, trim(strip_tags($_POST['city']))); $telephone = mysqli_real_escape_string($con, trim(strip_tags($_POST['telephone']))); $telephone = preg_replace('/[^0-9]/', '', $telephone); if (isset($_POST['deepc'])) { $deepc = 1; } else { $deepc = 0; } if (isset($_POST['problemc'])) { $problemc = 1; } else { $problemc = 0; } $problem = mysqli_real_escape_string($con, trim(strip_tags($_POST['problem']))); if (isset($_POST['blacklist'])) { $blacklist = 1; } else { $blacklist = 0; } if (isset($_POST['pickup'])) { $pickup = 1; } else { $pickup = 0; } $query = "INSERT INTO customers ( customer_name, contact, customer_address, city, telephone, deep_cycle, problem_customer, problem, blacklist, pickup) VALUES ('$name', '$contact', '$address', '$city', '$telephone', $deepc, $problemc, '$problem', $blacklist, $pickup)"; $r = mysqli_query($con, $query); if (mysqli_affected_rows($con) == 1) { echo '<p class="success">Customer has been successfully added.</p>'; } else { $message = "Could not add customer."; $message .= "<br />" . mysqli_error($con); } mysqli_close($con); } else { // We have errors. $message = count($errors) . " error(s) on the form."; } } // End: if ($_SERVER['REQUEST_METHOD'] == 'POST'). */ // Leave PHP and display the form. ?> <?php if (!empty($message)) { echo '<p class="error">' . $message . '</p>'; } ?> <?php // Output list of fields that have errors. if (!empty($errors)) { echo '<p class="error">'; foreach ($errors as $error) { echo $error . '<br />'; } echo '</p>'; } ?> <div class="container"> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <fieldset> <label>Business: <span class="important"> *</span><select name="customer_name" id="customer_name" onchange="request_fill(this.value)" value="<?php if (isset($_POST['customer_name'])) echo $_POST['customer_name']; ?>" ></select></label> <label>Address: <input type="text" name="address" id="add_a" value="<?php if (isset($_POST['customer_address'])) echo $_POST['customer_address']; ?>" /></label> <label>City: <input type="text" name="city" id="city" value="<?php if (isset($_POST['city'])) echo $_POST['city']; ?>" /></label> <label>Phone: <input type="text" name="telephone" value="<?php if (isset($_POST['telephone'])) echo $_POST['telephone']; ?>" /></label> <label>Manufacturer: <span class="important"> *</span><select name="manufacturer" id="manufacturer" onchange="request_mod(this.value)" value="<?php if (isset($_POST['manufacturer'])) echo $_POST['manufacturer']; ?>" ></select></label> <label>Model: <span class="important"> *</span><select name="model" id="model" onchange="form_yr(this.value)" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" ></select></label> <label>Year: <span class="important"> *</span><select name="battery" id="bat_disp" value="<?php if (isset($_POST['battery'])) echo $_POST['year'] ?>" ></select></label> <label>Quantity: <span class="important"> *</span><input type="text" name="quantity" id="quantity" value="<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></label> <label>Warranty ? <input type="checkbox" name="warranty" <?php if ($_POST['warranty']) echo " checked"; ?> /></label> <label>Exchange ? <input type="checkbox" name="exchange" <?php if ($_POST['exchange']) echo " checked"; ?> /></label> <input type="submit" name="submit" value="Add Order" /> or <a href="index.php">Cancel</a> </fieldset> </form> </div> <script type="text/javascript" src="include/functions.js"></script> <script> $(document).ready(function() { $('.container').hide(); $('.container').fadeIn(1000); request_cust(); request_man(); }); </script> <?php include ('include/footer.php'); 2. request_fill function request_fill() { var cust2 = 'customer'; var ad = document.getElementById("add_a"); var hr = new XMLHttpRequest(); hr.open("POST", "battery_parser.php", true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var dataArray = hr.responseText; ad.innerHTML = dataArray[1]; } } hr.send("&cust2="+cust2); } 3. battery_parser.php <?php include_once("include/dbconnect.php"); if (isset($_POST['cust2'])) { $cust2 = $_POST['cust2']; $sql = "SELECT customer_address FROM customers WHERE customer_id = 2"; $query = mysqli_query($con, $sql); $dataString = ''; while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ $add = $row["customer_address"]; $dataString = $add; } mysqli_close($con); echo $dataString; exit(); } else { exit(); } ?>
  12. Good evening, I have a jQuery datepicker that I am trying to insert different date values into different textboxes based on the user's selection. The original box displays the standard date format, input box 2 displays the date format suited for mysql, input box 3 needs to display the Month based on user selection, input box 4 displays the Year, and input box 5 needs to display the Month and the Year. The problem I am having is when I try to add multiple altField, it will only update the last id indicated. Here's my code. Thanks in advanced, Demeritrious HTML <input type="text" id="Goal" name="Goal" value="<?php echo $Goal; ?>"> <input type="text" id="GoalDate" name="GoalDate" value="<?php echo $GoalDate; ?>"> <input type="text" id="MyBillsMonth" name="Month" value="<?php echo $Month; ?>"> <input type="text" id="MyBillsYear" name="Year" value="<?php echo $Year; ?>"> <input type="text" id="MyBillsMonthYear" name="MonthYear" value="<?php echo $MonthYear; ?>"> JQUERY I've tried this $( "#Goal" ).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'mm-dd-yy', altField: "#GoalDate, #MyBillsMonth, #MyBillsYear, #MyBillsMonthYear", altFormat: "yy-mm-dd, MM, yy, MM yy" }); AND This $( "#Goal" ).datepicker({ changeMonth: true, changeYear: true, dateFormat: 'mm-dd-yy', altField: "#GoalDate", altFormat: "yy-mm-dd", altField: "#MyBillsMonth", altFormat: "MM", altField: "#MyBillsYear", altFormat: "yy", altField: "#MyBillsMonthYear", altFormat: "MM yy" });
  13. Hello everyone. It seems like my code is not working properly. i have tried both mysqli and PDO to insert data into database,but it only takes me back to same page again,without doing nothing in the database (been checking this a few times to be sure). both php and html code are on the same page. Could anyone point me to the missing link in my code? here's my code (HTML & PHP) : <form action="" id="SignUpForm" autocomplete="on" style="display:none" method="post"> <!-- Form is Hidden until the user is clicking the "Sign Up" button. --> <input type="hidden" name="Language" value="English"> Fill up the following fields:<br><br> First name:<input type="text" name="fname" required><br><br> Last name: <input type="text" name="lname" required><br><br> Age: <input type="number" name="UserAge" min="1" max="120" required><br><br> Gender: <input type="radio" name="Gender" value="male">Male<br> <input type="radio" name="Gender" value="Female">Female<br> E-mail Address: <input type="email" name="email" autocomplete="off" required><br><br> Pick your new password: <input type="password" maxlength=”40” name="Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"> Add password strength checker here.<br><br> <!-- Uses regular expression. --> Confirm Password: <input type="password" maxlength=”40” name="ConfirmPassword" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,40}"><br><br> <!-- A better way is to use onblur to check user's type match. --> <hr> <script> (function(){ $("#submit").click(function(){ $(".error").hide(); //Bind an event handler to the "error" JavaScript event. var hasError = false; var passwordVal = $("#Password").val(); var checkVal = $("#ConfirmPassword").val(); if (passwordVal == '') { $("#Password").after('<span class="error">Please enter a password.</span>'); hasError = true; } else if (checkVal == '') { $("#ConfirmPassword").after('<span class="error">Please re-enter your password.</span>'); hasError = true; } else if (passwordVal != checkVal ) { $("#ConfirmPassword").after('<span class="error">Passwords do not match.</span>'); hasError = true; } if(hasError == true) {return false;} }); }); </script> <script> //The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is checked and fails. document.getElementById("name").validationMessage; document.getElementById("lname").validationMessage; document.getElementById("UserAge").validationMessage; document.getElementById("Gender").validationMessage; document.getElementById("email").validationMessage; document.getElementById("Password").validationMessage; document.getElementById("ConfirmPassword").validationMessage; </script> Now let's go through your prefered food. Check the appropriate boxed beyond.<br><br> This will help us to better understand your food discipline:<br> <p style="text-align:center"><b> Meat And Poultry:</b></p> <div id="MeatCheckBox"> <input type="checkbox" name="FoodTypes[]" value="Hamburger">Hamburger<br> <input type="checkbox" name="FoodTypes[]" value="Steak">Steak<br> <input type="checkbox" name="FoodTypes[]" value="GroundBeef">Ground Beef<br> <input type="checkbox" name="FoodTypes[]" value="Bacon">Bacon<br> <input type="checkbox" name="FoodTypes[]" value="Beef">Beef<br> <input type="checkbox" name="FoodTypes[]" value="Salami">Salami<br> <input type="checkbox" name="FoodTypes[]" value="Chicken">Chicken (In all its forms)<br> <input type="checkbox" name="FoodTypes[]" value="NoMeat">I don't eat meat at all (Vegeterian/Vegan)<br> </div> <p style="text-align:center"><b> Fish And Seafood:</b></p> <div id="FishAndSeaFood"> <input type="checkbox" name="FoodTypes[]" value="Fish">Fish<br> <input type="checkbox" name="FoodTypes[]" value="Sushi">Sushi<br> <input type="checkbox" name="FoodTypes[]" value="CannedFish">Canned Fish<br> <input type="checkbox" name="FoodTypes[]" value="Oysters">Seafood<br> <input type="checkbox" name="FoodTypes[]" value="SmokedSalmon">Smoked Salmon<br> </div> <div id="Vegetables"> <p style="text-align:center"><b> Do you eat vegtables?</b></p><br> <input type="radio" name="YesOrNo" value="Yes">Yes <!-- Give both options the same name,Because they are related. --> <input type="radio" name="YesOrNo" value="No">No<br> </div> <hr> <p>Do you workout as part of your lifestyle?</p><br> <input type="radio" name='workout_options' value='valuable' data-id="DoWorkout" class="workout_options" /> I do workout occasionally <input type="radio" name='workout_options' value='valuable' data-id="DoNotWorkout" class="workout_options" /> I am not working out<br><br><br> <section> <div id=DoWorkout class="workout_options"><p>We see you're not having any exercise at the moment.<br><br>Did you know that doing some kind of activity like running or cardio 3 times a week improve your life quality?<br><br>We'll help you go straight from zero to hero!</p></div> <div id=DoNotWorkout class="workout_options">What type of workout you're working on at the moment? Please choose from the options beyond:<br><br><br> <input type="checkbox" name="Cardio" value="Cardio" data-id="Cardio"/>Cardio/Aerobics<br><br> <input type="checkbox" name=" Weight_Lifting" value=" Weight_Lifting" data-id="Weight_Lifting"/>Weight Lifting/ Anaerobics</div><br> </section> <input type="submit" value="Sign Up!" id="submit"> </div> </form> PHP/PDO: <?php // connnecting to MYSQL with PDO. // Connection data (server_address, database, username, password) $hostdb = 'localhost'; $namedb = 'caf_users'; $userdb = 'root'; $passdb = 'mypassword'; if (isset($_POST['SignUpButton'])) { $yesOrNo=$_POST["YesOrNo"]; $firstName=$_POST["fname"]; $lastName=$_POST["lname"]; $userGender=$_POST["Gender"]; $emailAddress=$_POST["email"]; //check if user entered the exact password twice. if ($_POST["password"] === $_POST["confirm_password"]) { $password=$_POST["password"]; $hash = password_hash($passwod, PASSWORD_DEFAULT);} // The first parameter is the password string that needs to be hashed, //and the second parameter specifies the algorithm that should be used for generating the hash. //encrypted by bcrypt algorithm. else { echo "Passwords are mismatched. Please try again."; }; $userAge=$_POST["UserAge"]; // Display message if successfully connect, otherwise retains and outputs the potential error try { $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); //Initiate connection witht the PDO object instance. $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 echo 'Connected to database'; // Define an insert query $sql = "INSERT INTO `users` ('Workout','first_name','last_name','gender','Email_Address','Password','User_Age') VALUES ($YesOrno,$fname,$lname,$Gender,$email,$password,$UserAge)"; $count = $conn->exec($sql); $conn = null; // Disconnect if($count !== false) echo 'Number of rows added: '. $count; } catch(PDOException $e) { echo $e->getMessage(); } } ?> Thank you in advance, Osher.
  14. Good afternoon, I am working on a project that gives the user a data table and a google chart (using the api) based on what the user selects for a <select> <option>. Index.PHP code: <form> <select name="users" onchange="showUser(this.value);drawChart();"> <option value=""> Select a Metal: </option> <?php //connection details $query = "SELECT TOP(31) tblMetalPrice.MetalSourceID, tblMetalSource.MetalSourceName from tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID=tblMetalSource.MetalSourceID ORDER BY tblMetalPrice.DateCreated DESC "; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_object ($result)) { echo "<option value='".$row->MetalSourceID ."'>". $row->MetalSourceName ."</option>"; } sqlsrv_close( $conn); ?> </select> </form> <div id="chart_div"></div> <div id="txtHint"><b>Past metal information will be generated below.</b></div> this works fine and generates the list in the select option dropdown Script to get table contents: <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } 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 (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","scripts/gettabledata001.php?q="+str,true); xmlhttp.send(); } </script> this also works fine and generates the table contents based on 'q' value from the select dropdown. Google API script: <script type="text/javascript"> // Load the Visualization API and the piechart,table package. google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart()); function drawChart() { var jsonData = $.ajax({ url: "scripts/getgraphdata.php", dataType:"json", data: "q="+num, async: false }).responseText; // Instantiate and draw our pie chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, {width: 400, height: 240}); } </script> getgraphdata.php script: $q = intval($_GET['q']); ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); $query ="SELECT TOP(30) tblMetalPrice.MetalSourceID, tblMetalPrice.DateCreated, tblMetalPrice.UnitPrice, tblMetalPrice.HighUnitPrice, tblMetalSource.MetalSourceName FROM tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID WHERE tblMetalPrice.MetalSourceID = '".$q."' ORDER BY tblMetalPrice.DateCreated DESC"; $result = sqlsrv_query($conn, $query); echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"Unit Price\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ "; $total_rows = sqlsrv_num_rows($result); $row_num = 0; while($row = sqlsrv_fetch_object($result)){ $row_num++; if ($row_num == $total_rows){ echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}"; } else { echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}, "; } } echo " ] }"; sqlsrv_close( $conn); When ever i try these they don't work the getgraphdata.php scripts runs fine the issue I believe but may be totally wrong may be done to the google api script that should generate the chart but doesn't. Can anyone help here I've been trying to sort this for a few days now and losing confidence in myself rapidly. Thanks Kris
  15. In my shopping cart i want an alert message when the maximum number of 5 for the item has been reached or ask them to delete the item if the press - when the item quantity is at 1. i have it working in php: //add to quantity of item if (isset($_POST['itemadd'])){ $additem = $_POST['additem']; $sqladd = "SELECT quantity FROM orders WHERE id = '$additem'"; $query_add = mysqli_query($db_conx, $sqladd); while($row = mysqli_fetch_array($query_add, MYSQLI_ASSOC)){ $itemqty = $row['quantity']; if ($itemqty < 5){ $addqty = $itemqty + 1; $adding = "UPDATE orders SET quantity = '$addqty' WHERE id = '$additem'"; $add_query = mysqli_query($db_conx, $adding); header('Location: http://www.quichlicious.co.uk/cart.php'); //print $additem; exit(); } else { $usemes = "You have reached maximum quantity"; } } But rather than display the message in a div i would like a javascript alert box to pop up, i tried the following code: <script type="text/javascript"> function CheckQtyPlus(){ var qty = '<?php echo $qty; ?>'; alert("message here"+qty); } </script> but i get the same quantity number for every item in the cart, i had this error with the php update but i got round that by querying sql to give me the quantity of an item by the items id. can the same thing be done in javascript / ajax? $qty by the way is referenced earlier in the script to get information for the cart table to display items. thanks Michael
  16. Hi everyone, I am having trouble passing/displaying the values inside of a selected list. I created a add/remove list using Jquery and I tried to display the values passed using foreach and for loops but it is still not working. The values I am trying to get are $existing_mID[$j], which is inside of the option value attribute. Please kindly let me know what should I do in order to get the values and I really appreciate your help. <?php $selected = $_POST['selectto']; if(isset($selected)) { echo "something in selected<br />"; for ($i=0;$i<count($selected);$i++) echo "selected #1 : $selected[$i]"; foreach ($selected as $item) echo "selected: item: $item"; } ?> This is the form <form> <select name="selectfrom[]" id="select-from" multiple="" size="10"> <?php $j=0; foreach($existing_mTitle as $item) { ;?> <option value="<?php $existing_mID[$j];?>" > <?php echo "$existing_mID[$j] & $item";$j++;?> </option> <?php }?> </select> <a href="JavaScript:void(0);" id="btn-add">Add »</a> <a href="JavaScript:void(0);" id="btn-remove">« Remove</a> <select name="selectto[]" id="select-to" multiple="" size="10"></label> </select> <input type="submit" name="addArticle" value="Add" /> </form> Below is my Jquery code that I implemented. $(document).ready(function() { $('#btn-add').click(function(){ $('#select-from option:selected').each( function() { $('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>"); $('#select-to option').attr('selected',true); $(this).remove(); }); }); $('#btn-remove').click(function(){ $('#select-to option:selected').each( function() { $('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>"); $('#select-to option[value=' +$(this).val()+ ']').attr('selected',true); $(this).remove(); }); }); });
  17. Good Day guys I need some help with something that I am busy with. I have a wallpaper that need to get weather effects on it but it has to be according to the current weather status and time. The wallpaper is in the attached. I have searched the net the whole day now and cant find what I am looking for. Let me give an example: If it rains the background wallpaper must have the rainy look and be wet, when its sunny there need to be a sun and the background must be brighter. Please help me with this.
  18. I have a page that functions like this: The user begins by loading ajaxtest.php, then using a drop-down menu, selects a user, after which a DIV on ajaxtest.php is populated with the user's selction to getuser.php?q=John%Doe Here's a visual representation of what is currently happening, along with the part I don't understand. getuser.php consists largely of a a large HTML table which interacts through PHP with my SQL database. Several of the fields in this table are editable, and after the user changes one of these fields, he can press an "update" button, which calls an AJAX script in update.js and runs update.php, which contains all my SQL queries to update the database, without the user being redirected to this update.php page. All of this is processing perfectly - the user makes some sort of edit, hits "update", and the database gets updated without any redirection or refresh. Here's what I can't figure out though. Once the user makes a change, and hits "update," the database updates, but the end user doesn't see those changes that he made. I can't just do a simple page refresh, because the action is taking place on getuser.php, but getuser.php is loaded inside of a #DIV on ajaxtest.php. If I use something like window.location.reload(), this just refreshes ajaxtest.php and puts the user back to the starting point of having to select a user. This is not what I want. I don't want to refresh ajaxtest.php, I want to "refresh" ajaxtest.php with getuser.php?q=John%Doe insidethe DIV on ajaxtest.php. It seems like this is very common - several forums have this capability, where a user has a page loaded, adds a comment, and sees that comment immediately without a full page refresh. I just don't know how to do it, and I've tried at lengths to search the web for an answer with no luck. Can someone walk me through how to do this?
  19. I have posted this problem in the PHP section but someone suggested I take it here because the hangup is likely in the JS. I have tried removing the JS validator with varying results; sometimes the form still requires double-clicking and sometimes it works fine. Please see my original post below:
  20. I am trying to build a website, where: 1) User logs in (UserA) 2) Inserting a name in the search box and pressing "Search", a list of all users matching that name is shown 3) The user selects a user (UserB) from that list (among several results) 4) By selecting the user (UserB) , a message box appears to insert text 5) The user(UserA) types the message 6) The user(UserA) presses the SUBMIT button and sends the message to the other user(UserB) The problem i face is how to pass the variables from my PHP script to the JavaScript script. Its easy for me to get the values of input fiedls, select fields or any other DOM element value. But if the value i need to pass to Javascript file to perform an AJAX call isnt inside a DOM element, how do i do it? For example, for me to determine the user that will send the message (userA), i will need several data. This data, i have them inside the PHP script as variables, but dont know how to pass them to Javascript file. Getting the data from the URL, or from a hidden input field or any other DOM element, is a solution, but i want to know the way that is safer and better. To summarize: -->[pass necessary data from PHP to JavaScript file]-->[perform an AJAX call] --> [return data to PHP Script] How do i do it? Thanks in advance.
  21. Hello, I would like to create a window through JavaScript with PHP code that would insert data into a database, but I don't know if it's possible, because I tried everything I could so far and had no results at all. The code I am using is <script language="JavaScript"> <!-- top.consoleRef = new Object(); top.consoleRef.closed = true; function writeConsole(content) { top.consoleRef=window.open('em_branco.php','myconsole','width=350,height=250') top.consoleRef.document.writeln( '<html><head><title>página nova</title></head><body><?php $db = pg_connect("host=localhost dbname=dpf_db user=postgres password=asdasd"); $query = "INSERT INTO tbl_dummy(nome) VALUES(' + '´treco´' + ')"; $result = pg_query($query); if (!$result) { $errormessage = pg_last_error(); echo "Error with query: " . $errormessage; exit(); } printf ("These values were inserted into the database"); pg_close(); ?></body></html>' ) //top.consoleRef.document.close() } //--> </script> Note that line 13 has a sort of aberration, because I'd need three kinds of quotes, and not only two (the +'´treco´' stuff). And I don't know how to circumvent this, because escaping didn't work either. Any help is most welcome, and thank you in advance for your attention. Nicole
  22. i am new to web designing, i don't know much about javascript. <select id="plan" align="center" valign="center"> <option value="images/21.jpg">PHASE 1</option> <option value="images/22.jpg">PHASE 2</option> <option value="images/23.jpg">PHASE 3</option> <option value="images/24.jpg">PHASE 4</option> <option value="images/25.jpg">PHASE 5</option> <option value="images/200.jpg">PHASE 6</option> <option value="images/210.jpg">PHASE 7</option> </select> <img id="image" src="images/21.jpg" align="center" valign="center" Onclick="zoom"/> <script type="text/javascript"> function setplan() { var img = document.getElementById("image"); img.src = this.value; return false; } document.getElementById("plan").onchange = setplan; </script> above is the code given. the above codes changes the images when the values of the dropdown menu are selected, every dropdown menu has a specific image bind to it. when the image is displayed after selecting any item from dropdown, now i want to popup or zoom the image or open it itnto new widow when i click on the image, plz help me. http://gdcindia.co.in/SAI%20SHOBHAN.html plz visit this link, and go to 2nd tab floor plan. then u will know what i want plz help me.
  23. Hi, I have the 'onbeforeunload' event set on the 'body' tag to set a JS function to trigger ONLY if a conditionis set - two var's equaling one another. Note: that all works just fine - no issues with the default setup. However, This function should NOT trigger the event if the 'submit' button is click (therefore suppressing the 'process()' function set on 'body' tag. Reason: that means staff completed the transaction and data actually saved to the database. The 'cancel.html' required to inform them their action canceled the process and no record created as a result. ---- Here's what i have thus far - appreciate some insight to get this final piece to work ('process' function should NOT fire when 'submit' button click which triggers 'checkfire' function). That's my problem - not able to pass local var out of 'checkfire' function to update global var which then read by 'process' function. (Brain dead!) ===== Here's the code for review: * This is the snippet that sets the default var values and the 'checkfire' function that will be called from the 'submit' button <script type="text/javascript"> var viewer = "fire"; var jscheck = viewer; // if function called, then update var jscheck function checkFire() { jscheck = "nofire"; alert("jscheck value is now: " + jscheck); return jscheck; } </script> * Here's the part that fires the 'cancel.html' page if staff member clicks away from the page without submitting the form data. This is where we need to display the cancelation policy advising they did not complete the process by submitting info. <script type="text/javascript"> // Process to advise member by leaving page without clicking "Submit Record" button, canceled the entire process / update if (viewer == jscheck) { function process() { window.open('http://www.domain/canceled.html', '_blank'); self.blur(); } } </script> and finally, the Body tag showing 'process()' function and the 'submit' button showing onclick event calling 'checkfire()' func. <body onbeforeunload="process()"> <input name="sumbit" value="Submit Record" onclick="checkFire();" /> Again, If the 'submit' button is clicked, then the 'process()' should NOT trigger at that point. ISSUE: this is what's happening - process() function firing even when the form submitted (it should ONLY fire if staff leaves the page prior to submitting the form which is requirement to close out work order). ---- I'm not sure how to dynamically 'remove' the onbeforeunload event off the 'body' tag or pass the 'checkfire()' value of 'jscheck' out of that function to global jscheck var to cause the conditional logic in 'process()' to fail - resulting in no action. Any help with this appreciated - thx!
  24. Say there is a complex opt in process where people start to enter their data but certain questions stop them where they close out of the page. They already entered their data and I feel there is a way to grab it and post it to mysql even though they do not click submit. How would this be done? A super simple example (proof of concept) or a link to a tutorial would be very useful.
  25. Good Day PHP world, I am encountering a problem in php code meant to allow the user to update their profile picture. I am using jquery.min and jquery.js. The code below runs with no errors reported. The file has been successfully uploaded to upload path using this form. upload.php <form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'> <input type="file" name="photoimg" id="photoimg" class="stylesmall"/> </form> ajaximage.php $path = "uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) // Image size max 1 MB { $actual_image_name = $name.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { $query = "UPDATE users SET profile_image='$actual_image_name' WHERE student_id='{$_SESSION['user_id']}'"; $result = mysqli_query($link_id, $query); echo "<img src='uploads/".$actual_image_name."' class='preview'>"; } The problem is the image being uploaded does not display on the Student_home.php <div id="about-img"> <img class="profile-photo" align="middle" src='uploads/".$actual_image_name."' /> </div> But the image uploaded will display when i write directly its filename example <div id="about-img"> <img class="profile-photo" align="middle" src="uploads/107.jpg" /> </div> My problem is i wanted to display the uploaded picture of the specific student on Student_Home.php
×
×
  • 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.