Jump to content

Search the Community

Showing results for tags 'ajax'.

  • 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 been reading up on ajax using jquery, and theres something I can't seem to find, i have a form that gets the field values from mysql when the page loads, what is the best way to use ajax to edit this form? Obv the ajax request will execute the mysql update statement but how do i get the edited data back into the form, ready to be worked with again. thanks, hope i made sense, just looking for a little direction. MsKazza
  2. Here's what I'm trying to do. I retrieve results using php foreach loop. Within that loop results, I want to show a div(.show-details) on mouse over only. How do I do that? This is my code so far. <style> .show-details { display: none; } </style> $get_records = $db->prepare("SELECT * FROM records WHERE record_id = :record_id"); $get_records->bindParam(':record_id', $record_id); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0){ foreach($result_records as $row) { $get_record_title = $row['record_title']; $get_record_details = $row['record_details']; $get_record_price = $row['record_price']; ?> <div class="product"> <div class="product-title"> <?php echo $get_record_title; ?> </div> <div class="product-price"> <?php echo $get_record_price; ?> </div> </div> <div class="show-details"> <?php echo $get_record_details; ?> </div> <?php } } else { echo 'no results.'; } <script> $(document).ready(function() { $(".product").mouseover(function(){ $(".show-details").css("display", "block"); }); }); </script>
  3. Basically I have a very long form select option drop down list. What I would like to do is that for each option "value", I want to remove the spaces and instead add dash to it. Doing each option value by hand would take me a very long time, so I thought I might try jquery for short cut. If you have another method, let me know. Here's what I have so far. Doesn't seem to work. <script> $(document).ready(function () { $('#model').change(function(){ var str = $(this).val(); str = str.replace(/\s+/g, "-"); }); }); </script> // here's an example of select options <select id="model" name="model"> <option value="john doe" >John Doe</option> <option value="john smith lu" >John Smith Lu</option> </select>
  4. Hi, I am absolutly beginner in PHP, AJAX. In my Wordpress page I have following scene: 1. input box for name 2. combobox from country-> combo for cities depend of selected country Button for search in MySQL database After submit the database return result in a table (user, country, city, mobile, email, etc.) with 2 editable (mobile, email) input column and I put Update button in every row. My questions: 1) If I change one data on the editable column how can I know the number of row? 2) How can I run the update script without refresh page? Thanks for your answer. //UserInfo-modify.php <?php include_once('db.php'); $name = $_POST['nev']; $country = $_POST['megye']; $error = ""; $city = ""; $nodata = ""; $ID = 0; if (($country=="Bács-Kiskun")||($country=="Baranya")||($country=="Békés")||($country=="Borsod-Abaúj-Zemplén")||($country=="Csongrád")|| ($country=="Fejér")||($country=="Győr-Moson-Sopron")||($country=="Hajdú-Bihar")||($country=="Heves")||($country=="Jász-Nagykun-Szolnok")|| ($country=="Komárom-Esztergom")||($country=="Nógrád")||($country=="Pest")||($country=="Somogy")||($country=="Szabolcs-Szatmár-Bereg")|| ($country=="Tolna")||($country=="Vas")||($country=="Veszprém")||($country=="Zala")) { $city = $_POST['telepules']; if ($city=="---") $error = "-city"; } else { $error = "-country-city"; } mysqli_set_charset($conn,"utf8"); if (($city!="") AND ($name!="")) { $query = mysqli_query($conn,"SELECT nev,kor,megye,telepules,utca,mobil,email FROM `nrqadatr` WHERE nev='$name' AND telepules='$city'") or die("userinfo-modify-36 ".mysqli_error($conn));} else if (($city=="") AND ($name=="")) { $nodata = '1'; echo "Name and city = 0!"; } else if (($city!="") AND ($name=="")) { $query = mysqli_query($conn,"SELECT nev,kor,megye,telepules,utca,mobil,email FROM `nrqadatr` WHERE telepules='$city'") or die("userinfo-modify-45 ".mysqli_error($conn));} else if (($city=="") AND ($name!="")) {$query = mysqli_query($conn,"SELECT nev,kor,megye,telepules,utca,mobil,email FROM `nrqadatr` WHERE nev='$name'") or die("userinfo-modify-49 ".mysqli_error($conn));} if ($nodata!='1') { $rowcount=mysqli_num_rows($query); if ($rowcount>0) { echo '<table>'; $arrayofrows = array(); echo ' <table border=1> <tr style="background-color:#EFFBFB; font-weight:bold; border: 1px solid black;"> <td style="font-size:14px;">ID</td> <td style="font-size:14px;">Name</td> <td style="font-size:14px;">City</td> <td style="font-size:14px;">Age</td> <td style="font-size:14px;">Address</td> <td style="font-size:14px;">Mobil</td> <td style="font-size:14px;">E-mail</td> <td style="font-size:14px;">Operation</td> </tr>'; } else echo "\r\n<B><font color='red'>No data //my_script.js $("#sub").click( function() { $.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(), function(info) { $("#result").html(info); }); clearInput(); }); $("#myForm").submit( function() { return false; }); function clearInput() { $("#myForm :input").each( function() { $(this).val(''); }); } ."; while ($data = mysqli_fetch_array($query)) { $ID = $ID+1; $data_nev=$data["nev"]; echo ' <tr style="background-color:#EFFBFB; border: 1px solid black;"> <td><input type="radio" name="$kivalasztott_sor" value="AG"></td> <td style="font-size:14px;">'.$data["nev"].'</td> <td style="font-size:14px;">'.$data["telepules"].'</td> <td style="font-size:14px;">'.$data["kor"].'</td> <td style="font-size:14px;">'.$data["utca"].'</td> <td><input type="text" value='.$data["mobil"].'></td> <td><input type="text" value='.$data["email"].'></td> <td onclick="cellOnclick()"><a href="#" onclick="linkOnclick()" style="text-decoration: none;"> <input type=button value="UPDATE" myFunction(this); return false;"></button></td> </tr>'; } echo '</table>'; } unset($name); unset($kor); unset($country); unset($error); unset($city); unset($nodata); unset ($data_nev); ?> //Wordpress (main) page [insert_php] include '/select_list_cities.php'; [/insert_php] <html><head><meta charset="utf-8" /><script src="/ajax_select_cities.js" type="text/javascript"></script> </head><body><form id="myForm" action="/userInfo-modify.php" method="post"> Name*:<br><input type="text" name="nev"> <p> [insert_php] echo $re_html;[/insert_php]<br class="clear" /> <br class="clear" /> <button id="sub">Search</button> <br><br></form> <span id="result"></span> <div id="data"><?php echo $result; ?></div> <script type="text/javascript" src=" http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.1.min.js"></script> <script src="/my_script.js" type="text/javascript"></script> </body> </html>
  5. 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
  6. Hi Peeps So basically im creating a "customer page" i have 2 tabs, 1 is customer info which is the primary and the invoicing tab I have a date picker in the invoicing tab which im hoping will populate a table below. I tried having the form post to php but this resets the page which then goes to the customer info tab so im guessing this will have to be done with jquery and ajax. could someone please point me in the right direction to do this? here is the current page for better explanation: All help is greatly appreciated in advance Mooseh
  7. Hey guys, i am trying to create a contact form that by passes the page refresh and uses Jquery and Ajax to direct to a php file server side. So far i have everything work fine. until the final part where i pass the json data type into PHP and look to catch an error, success, or completion value. Currently i have an error coming back with the following: SyntaxError: Unexpected token < error due to a parsererror condition I do not see any errors in the console of of chrome, and i have no idea why i am getting this syntax error. These does not seem to be any conflicting data going into the json or out to php. really been stuck on this for a day now This is my .js file $(document).ready(function(){ $('form #alertMessage').hide(); $('#submit').click(function(e){ e.preventDefault(); var valid = ''; var name = $('form #name').val(); var email = $('form #email').val(); var subject = $('form #subject').val(); var message = $('form #message').val(); var honeypot = $('form #honeypot').val(); var humancheck = $('form #humancheck').val(); if(name = '' || name.length <= 5 ){ valid += '<p>Sorry, Your name is required!</p> '; } if(!email.match( /^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/ )){ valid += '<p>A Valid Email is required</p> '; } if(subject = '' || subject.length <= 2 ){ valid += '<p>A Valid name is required</p> '; } if(message = '' || message.length <= 5 ){ valid += '<p>A brief description of you is required.</p> '; } if(honeypot != 'http://'){ valid += '<p>Sorry spambots not allowed.</p> '; } if(humancheck != ''){ valid += '<p>Sorry only humans allowed past this point.</p> '; } if(valid != ""){ $('form #alertMessage').removeClass().addClass('error') .html('<br><br>' + valid).fadeIn('fast') }else{ $('form #alertMessage').removeClass().addClass('processing') .html('<br><br>We are processing your form now...').fadeIn('fast') var formData = $('form').serialize(); submitForm(formData); } }); }); function submitForm(formData){ $.ajax({ type: 'POST', url: 'feedback.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data){ $('form #alertMessage').removeClass().addClass((data.error === true) ? 'error' : 'success' ) .html(data.msg).fadeIn('fast'); if($('form #alertMessage').hasClass('success')){ setTimeout("$('form $alertMessage').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, testStatus, errorThrown){ $('form #alertMessage').removeClass().addClass('error') .html(' <p>There was an ' + errorThrown + ' error due to a ' + testStatus + ' condition.</p>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status){ $('form')[0].reset(); } }); }; Here is the php script. <? sleep(3); $name = trim($_POST['name']); $name = trim($_POST['email']); $name = trim($_POST['subject']); $name = trim($_POST['message']); $name = $_POST['honeypot']; $name = $_POST['humancheck']; if ($honeypot == 'http://' && empty($humancheck)){ $errorMsg = ''; $reg_exp = "/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$/ "; if(!preg_match($reg_exp, $email)){ $errorMsg .= "<p>A valid email is required</p>"; } if(empty($name)]){ $errorMsg .= '<p>Please provide your name</p>'; } if(empty($message)]){ $errorMsg .= '<p>Please provide a message</p>'; } if(!empty($errorMsg)){ $return['error'] = true; $return['msg'] = 'Sorry the request was successful but your form was not correctly filled.' . $errorMsg; echo json_encode($return); exit(); }else{ $return['error'] = false; $return['msg'] = 'Thank you for your feedback ' .$name . ' ' . $errorMsg; echo json_encode($return); } } else { $return['error'] = true; $return['msg'] = 'Oops...there was a problem with your submission. Please try again' ; echo json_encode($return); } ?> HTML side. <form id="contact_us" class="contact-form" action="feedback.php" enctype="multipart/form-data" method="post"> <div id="alertMessage"> </div> <div class="row"> <div class="col-md-6"> <input type="text" name='name' class="form-control" id="name" placeholder="Full Name"> <input type="email" name='email' class="form-control" id="email" placeholder="Your Email"> <input type="text" name='subject' class="form-control" id="subject" placeholder="Company or Project name"> </div> <div class="col-md-6"> <textarea class="form-control" name="text" id="message" rows="25" cols="10" placeholder=" Brief Description"></textarea> <input id='submit' name='submit' type="submit" class="btn btn-default submit-btn form_submit"> </div> <input type="hidden" name="honeypot" id="honeypot" value="http://" /> <input type="hidden" name="humancheck" id="humancheck" value="" /> </div> </form> Image of the error output
  8. Hi Guys, I have created a calendar view with this plug in. http://fullcalendar.io/ The calendar view will show calendar view by Start Date and End Date. So I have some problem with some of the event, the start date is from 01-January-2015 until 15-Jan-2015, but in between actually there is a break. For example, 01-January-2015 until 03-January-2015 13-January-2015 until 15-January-2015 So, because of the start date and the end date is so long, so in the calendar view, it block the calendar from 01/Jan until 15/Jan. Its look weird. Actually i have actual dates column in my database column in this format: 01-01-2015,02-01-2015,03-01-2015,13-01-2015,14-01-2015,15-01-2015Start Date column 01-01-2015 End Date column 15-01-2015So, i was wondering is there any script to detect each of date to separate the break in between the start date and end date. Thank You
  9. You know when you type text into a form input and it automatically types the same text in another div? Well I am trying to do the same thing but instead show the same text value from the div 1 to div 2. Here is my code. It works with the input text field but not with the textarea. Can you tell me why? <input type="text" name="title" id="title" value="" maxlength="55" /> <textarea name="details" id="details" value="" maxlength="160" ></textarea> <!-- Values show up in these inputs --> <input type="text" name="seo_page_title" id="seo_page_title" value="" maxlength="55" /> <textarea name="seo_page_description" id="seo_page_description" maxlength="160" ></textarea> <script> $('#title').on("input", function() { var dInput = this.value; console.log(dInput); $('#seo_page_title').val(dInput); }); $('#details').on("input", function() { var dInput = this.value; console.log(dInput); $('#seo_page_description').val(dInput); }); </script>
  10. I am trying out a new script for image upload and resize using ajax method. All the ones I've found so far process the php file through the form action="". Since I am inserting other data into the database and calling the other php code directly on the same page as a the html form, I would like to know if there is another way I can run that specific image upload php code through ajax. This is one the scripts I have looked at . http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php This is what their html form looks like. <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm"> <input name="image_file" id="imageInput" type="file" /> <input type="submit" id="submit-btn" value="Upload" /> <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/> </form> <div id="output"></div> I would like to process the "processupload.php" above through the ajax code below and leave the form action="" empty, as I am running other php code on the same page to insert other data as well. How would you do that? <script> $(document).ready(function() { var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforeSubmit, // pre-submit callback success: afterSuccess, // post-submit callback resetForm: true // reset the form after successful submit }; $('#MyUploadForm').submit(function() { $(this).ajaxSubmit(options); // always return false to prevent standard browser submit and page navigation return false; }); }); function afterSuccess() { $('#submit-btn').show(); //hide submit button $('#loading-img').hide(); //hide submit button } //function to check file size before uploading. function beforeSubmit(){ //check whether browser fully supports all File API if (window.File && window.FileReader && window.FileList && window.Blob) { if( !$('#imageInput').val()) //check empty input filed { $("#output").html("Are you kidding me?"); return false } var fsize = $('#imageInput')[0].files[0].size; //get file size var ftype = $('#imageInput')[0].files[0].type; // get file type //allow only valid image file types switch(ftype) { case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': break; default: $("#output").html("<b>"+ftype+"</b> Unsupported file type!"); return false } //Allowed file size is less than 1 MB (1048576) if(fsize>1048576) { $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor."); return false } $('#submit-btn').hide(); //hide submit button $('#loading-img').show(); //hide submit button $("#output").html(""); } else { //Output error to older browsers that do not support HTML5 File API $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!"); return false; } } //function to format bites bit.ly/19yoIPO function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } </script>
  11. Hello I have this Ajax code witch working good, but I'm not really good at javascript I just started 1 month ago, so I'm not sure if this code is perfect or not, or is there any way to improve this AJAX code. HTML/AJAX <input type="text" id="text_1" /> <button name="js_btn_func" id="js_btn_func" onclick="ajax()" > Execute JavaScript / AJAX Function </button> <div id="success_2"></div> <div id="result_2"></div> <div id="error_2"></div> <script> try { var results_area_2 = document.getElementById("result_2"); var error_area_2 = document.getElementById("error_2"); var success_area_2 = document.getElementById("success_2"); function ajax(str) { var xhttp; var str = document.getElementById("text_1").value; if (str == "") { document.getElementById("result_2").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { results_area_2.innerHTML = xhttp.responseText; success_area_2.innerHTML = ('Success: Script is <b>ON</b>'); } } xhttp.open("POST", "action.php?name="+str, true); xhttp.send(); } } catch(e){ alert('An error has occurred: '+e.message) error_area_2.innerHTML = ('Error: Script is <b>OFF</b>'); } </script> PHP <?php $random_query = mt_rand(1, 9999); if (isset($_REQUEST["name"])){ $q = $_REQUEST["name"]; echo "Hello <b>$q</b>! random number : $random_query "; } ?> Thanks in advance.
  12. I have the following code for my dropbox; <select name="Symptom" id="Symptomid" onchange="LSC(this.value)"> Its options are; <option value="<?php echo $row_RsSymptom['name']?>"><?php echo $row_RsSymptom['name']?></option> i have the script ; <script> function LSC(str) { if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { 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","LoadSymptomDetails.php?q="+str,true); xmlhttp.send(); } } </script> The LoadSymptomDetails.php has the following lines; $sql1 = mysql_query("SELECT name,description , comments FROM symptoms WHERE symptoms.name ='".$q."'") or die(mysql_error()); The q is not being picked. If i remove the where statement it runs and displays the table. Kindly assist. Azhar
  13. Wondering Am I doing the correct thing. Im using qtip2 plug in to show something from another page content. I have 2 pages of php. aa.php <html> <head> <title>My site</title> <!-- CSS file --> <link type="text/css" rel="stylesheet" href="http://cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.css" /> </head> <body> <!-- jQuery FIRST i.e. before qTip (and all other scripts too usually) --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <!-- Include either the minifed or production version, NOT both!! --> <script type="text/javascript" src="http://cdn.jsdelivr.net/qtip2/2.2.1/jquery.qtip.js"></script> <!-- Optional: imagesLoaded script to better support images inside your tooltips --> <script type="text/javascript" src="/path/to/jquery.imagesloaded.pkg.min.js"></script> <a href="#">Test</a> <script type="text/javascript"> $('a').qtip({ content: { text: function(event, api) { $.ajax({ url: 'aaCal.php', // URL to the JSON file dataType: 'json', // Tell it we're retrieving JSON }) .then(function(data) { /* Process the retrieved JSON object * Retrieve a specific attribute from our parsed * JSON string and set the tooltip content. */ var content = 'My name is ' + data.person.firstName; // Now we set the content manually (required!) api.set('content.text', content); }, function(xhr, status, error) { // Upon failure... set the tooltip content to the status and error value api.set('content.text', status + ': ' + error); }); return 'Loading...', // Set some initial loading text } } }); Another page aaCal.php $arr = array('person' =>array('firstname' => "Foo")); echo json_encode($arr); The output of aaCal.php is {"person":{"firstname":"Foo"}}. reference plug in guide: http://qtip2.com/guides
  14. loading image during ajax process not working properly: my code smthing like this... div to show content and loading image- <div id="adS" style="float: left; width: 70%"> <div id="loading-image" style="background-image: url('images/processing.gif'); display: none;"> </div> </div> jquery code- $(function() { $("#lets_search").bind('submit',function() { var gen = $("input[name='radGen']:checked").val(); var mt = $('#selMtQ').val(); var agf = $('#agf').val(); var agt = $('#agt').val(); var rel = $('#religQ').val(); var cast = $('#selCstQ').val(); $('#loading-image').show(); $.post('adSearch.php',{gen:gen,mt:mt,agf:agf,agt:agt,rel:rel,cast:cast}, function(data){ $("#adS").html(data); $('#loading-image').hide(); }); return false; }); }); The loading image show only one time on click event.. not every time when i click search li... Need help...
  15. I am stumped. I have a database similar to this: | Class Number | Class Name | Class Date | 0001 MATH 1/1/2016 0002 SCIENCE 2/1/2016 0003 HISTORY 3/1/2016 I am calling all classes where the date is > current date. All matching classes are then put into a html dropdown box. I would now like to populate two additional fields with the class number and class date based on the selection of the dropdown. I know I'll need to use AJAX, but I am a little stumped on how to get started. My first problem is that I have the beginning of the html select tag before: while($row = $result->fetch_assoc()){ and the end select tag after the }, so I can't put the two additional form fields in the loop. Any tips on where to go from here? Here's what I have so far: <?php // Get required login info include "/secret/path/to/login.php"; $db = new mysqli('localhost', $username, $password, $database); // Connect to DB using required login info if($db->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } unset($username);// put these variables back to null unset($password);// put these variables back to null unset($database);// put these variables back to null date_default_timezone_set('America/Los_Angeles'); // set default time zone PST $sql = "SELECT * FROM ft_form_7 WHERE class_full != 'Class Full' AND class_start_date > CURRENT_DATE()"; $result = $db->query($sql); if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']';} // show error if necessary if(mysqli_num_rows($result) < 1) { (include "/path/to/get-classes-for-registration-no-classes.php"); } echo '<select name="class_drop_down">'; // opens the dropdown box while($row = $result->fetch_assoc()){ echo '<option value="'.$row['class_name'].'">'.$row['class_name'].'</option>'; } echo '</select>'; $db->close(); $result->free(); ?>
  16. How do you solve an error where a soft refresh of data causes an accordion to fail, but on a hard refresh it works just fine? example: $(function() { $( "#accordion" ).accordion({ collapsible: true, active: false, heightStyle: "content" }); console.log('ran'); });
  17. Why does this source file seem to cause the ajax to crash after the first call to the function? function swapContent(href, url_data, target) { $.ajax({ type: 'GET', cache: false, url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request //load more data to "target" value div target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below } }) }
  18. Hi, I am building a website using PHP. By default the SESSION is kept active for 24(1440 seconds) minutes of inactivity. What i want is to refresh the SESSION as soon as the user interacts with the website (movement of the mouse, click on links inside the website, etc.) The way i am trying to refresh the session is by calling PHP script named refreshSession.php with AJAX as follow: $.ajax({ cache: false, type: "GET", url: "refreshSession.php" }); and the PHP script goes as follow: refreshSession.php <?php session_start(); echo 'test'; ?> But the session does not refresh. The only way to refresh the session is to reload the page. What am i doing wrong? Any suggestions? Regards, Christos
  19. I have some routines I use over and over Is there a way to put the error section in a file of its own For example I use a routine below <script type="text/javascript"> $('.MYTRIGGER').live('change', function() { var MyData=''; $("#jq_tab").val('0'); var NameData=$(this).attr('name'); var IdData=$(this).attr('id'); MyData=MyData+'CID='+NameData;; MyData=MyData+'&Field='+IdData; MyData=MyData+'&FieldValue='+$(this).val(); $.ajax( { cache:false, timeout:28000, url : 'MyPhp.php', type : 'post', data : MyData, success : function( resp ) { $("#jq_tab").val('1'); return(false); }, error: function(xhr, status, error) { var stat = $("#jq_tab").val(); $("#main_page_div").unmask_div(); if(stat!='1'){ if (xhr.status === 0) { alert('Unable to connect to Network'); } else if (xhr.status == 404) { alert('Requested page not found. [404]'); } else if (xhr.status == 500) { alert('Internal Server Error [500].'); } else if (exception === 'parsererror') { alert('Requested JSON parse failed.'); } else if (exception === 'timeout') { alert('System Timeout (Internet Congestion or server slow)'); } else if (exception === 'abort') { alert('Ajax request aborted.'); } else { alert('Unspecified Error #' + xhr.responseText); } } return false; } // eof error function }); }); </script> Since the below is common error: function(xhr, status, error) { var stat = $("#jq_tab").val(); $("#main_page_div").unmask_div(); if(stat!='1'){ if (xhr.status === 0) { alert('Unable to connect to Network'); } else if (xhr.status == 404) { alert('Requested page not found. [404]'); } else if (xhr.status == 500) { alert('Internal Server Error [500].'); } else if (exception === 'parsererror') { alert('Requested JSON parse failed.'); } else if (exception === 'timeout') { alert('System Timeout (Internet Congestion or server slow)'); } else if (exception === 'abort') { alert('Ajax request aborted.'); } else { alert('Unspecified Error #' + xhr.responseText); } } return false; } // eof error function Is there a way to store the error function in a common file?
  20. Hi all, I am new to PHP and a bit slow in understanding ajax, javascript. I want to ask on how to display the table after I select the 3rd dropdown. I don't know how to start. //this is ajax-dd3.php file <!doctype html public "-//w3c//dtd html 3.2//en"> <html> <head> <title></title> <META NAME="DESCRIPTION" CONTENT=""> <META NAME="KEYWORDS" CONTENT=""> <script type="text/javascript"> function ajaxFunction(choice) { var httpxml; try { // Firefox, Opera 8.0+, Safari httpxml=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { httpxml=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpxml=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } function stateChanged() { if(httpxml.readyState==4) { //alert(httpxml.responseText); var myObject = JSON.parse(httpxml.responseText); for(j=document.myForm.state.options.length-1;j>=0;j--) { document.myForm.state.remove(j); } var state1=myObject.value.state1; var optn = document.createElement("OPTION"); optn.text = 'Select State'; optn.value = ''; document.myForm.state.options.add(optn); for (i=0;i<myObject.state.length;i++) { var optn = document.createElement("OPTION"); optn.text = myObject.state[i]; optn.value = myObject.state[i]; document.myForm.state.options.add(optn); if(optn.value==state1){ var k= i+1; document.myForm.state.options[k].selected=true; } } ////////////////////////// for(j=document.myForm.city.options.length-1;j>=0;j--) { document.myForm.city.remove(j); } var city1=myObject.value.city1; //alert(city1); for (i=0;i<myObject.city.length;i++) { var optn = document.createElement("OPTION"); optn.text = myObject.city[i]; optn.value = myObject.city[i]; document.myForm.city.options.add(optn); if(optn.value==city1){ document.myForm.city.options[i].selected=true; } } /////////////////////////// document.getElementById("txtHint").style.background='#00f040'; document.getElementById("txtHint").innerHTML='done'; //setTimeout("document.getElementById('txtHint').style.display='none'",3000) } } var url="ajax-dd3ck.php"; var country=myForm.country.value; if(choice != 's1'){ var state=myForm.state.value; var city=myForm.city.value; }else{ var state=''; var city=''; } url=url+"?country="+country; url=url+"&state="+state; url=url+"&city="+city; url=url+"&id="+Math.random(); myForm.st.value=state; //alert(url); document.getElementById("txtHint2").innerHTML=url; httpxml.onreadystatechange=stateChanged; httpxml.open("GET",url,true); httpxml.send(null); document.getElementById("txtHint").innerHTML="Please Wait...."; document.getElementById("txtHint").style.background='#f1f1f1'; } </script> </head> <body > </head> <body> <div id="txtHint" style="width : 100px;background-color: #cccc33;">Message area</div> <br><br> <form name="myForm" action='ajax-dd3-details.php' method='post'"> <input type=hidden name=st value=0> <table width=500> <tr><td > Select Country<br><select name=country id='s1' onchange=ajaxFunction('s1');> <option value=''>Select One</option> <?Php //require "../include/z_db1.php"; require "config.php";// connection to database $sql="select distinct country from student5 "; foreach ($dbo->query($sql) as $row) { echo "<option value=$row[country]>$row[country]</option>"; } ?> </select> </td><td ><select name=state onchange=ajaxFunction('s2');> <option value=''>Select One</option></select></td> <td ><select name=city onchange=ajaxFunction('s3');> <option value=''>Select One</option></select></td> </tr></tr> <tr><td colspan=3><input type=submit value='Submit'></td></tr> </form> </table> <br><br> <div id="txtHint2"></div> </body> </html> //this is ajax-dd3ck.php file <?Php require "config.php"; // connection details error_reporting(0);// With this no error reporting will be there ////////// ///////////////////////////////////////////////////////////////////////////// $country=$_GET['country'];// //$country='IND'; // To check you can use this $state1=$_GET['state']; $city1=$_GET['city']; ///////////// Validate the inputs //////////// // Checking country variable /// if((strlen($country)) > 0 and (!ctype_alpha($country))){ echo "Data Error"; exit; } // Checking state variable (with space ) /// if ((strlen($state1)) > 0 and ctype_alpha(str_replace(' ', '', $state1)) === false) { echo "Data Error"; exit; } /////////// end of input validation ////// if(strlen($country) > 0){ $q_country="select distinct(state) from student5 where country = '$country'"; }else{ $q_country="select distinct(state) from student5"; } //echo $q_country; $sth = $dbo->prepare($q_country); $sth->execute(); $state = $sth->fetchAll(PDO::FETCH_COLUMN); $q_state="select distinct(city) from student5 where "; if(strlen($country) > 0){ $q_state= $q_state . " country = '$country' "; } if(strlen($state1) > 0){$q_state= $q_state . " and state='$state1'";} $sth = $dbo->prepare($q_state); $sth->execute(); $city = $sth->fetchAll(PDO::FETCH_COLUMN); $main = array('state'=>$state,'city'=>$city,'value'=>array("state1"=>"$state1","city1"=>"$city1")); echo json_encode($main); ////////////End of script ///////////////////////////////////////////////////////////////////////////////// ?> //this is ajax-dd3-details.php file <!doctype html public "-//w3c//dtd html 3.2//en"> <html> <head> <title></title> <META NAME="DESCRIPTION" CONTENT=""> <META NAME="KEYWORDS" CONTENT=""> </head> <body> <?Php echo "Country : $_POST[country]<br> State : $_POST[state]<br> City : $_POST[city]<br> <br><br><br> Return to <a href=ajax-dd3.php>Drop down list</a> "; ?> </body> </html>
  21. Hi all, I need some guidance on how I can build an AJAX/PHP chat application, sort of like an instant messaging thing like the one on Facebook. It doesn't have to be anything fancy as long as it works. I have some ideas as to how I can build it but I've never tried to do anything like this before so I'm a bit lost. I'm confident I can build the entire PHP side of things up until I have to use AJAX, then I'm stuck. The main concern I have is the affect it will have on the server, lets say I have a Javascript timer to check for new messages sent at certain intervals, wouldn't that have a massive affect on the server? I can only think of using a timer to get new messages for each user, I can't come up with any other way to get it to work. I just don't want to kill the server with AJAX requests if that's even possible. So really my question is, would it be okay to use a timer to get new messages of each user at certain intervals, or is there another way of doing it? Hope this makes sense Thanks, Adam
  22. I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax. when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div. I was following a tutorial from youtube, however it queried against a mysql database. I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code. The jquery is in the head section. the rest of the code is as follows: <?php $car = array() $car["vw"] = array( "name" => "volkswagen"); $car["tyta"] = array( "name => "toyota"); ?> the html code is as follows: <label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" /> <div id="carnamestatus"></div> the checkcar() function checkcar(){ var u = _("carname").value; if(u != ""){ _("carname").innerHTML = 'checking ...'; var B = new XMLHttpRequest(); B.open("POST","check.php",true); / B.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); B.onreadystatechange = function() { if(B.readyState==4 && B.status== 200) { _("carnamestatus").innerHTML = B.responseText; } } var v = "carnamecheck="+u; B.send(v); } } </script>
  23. Hello everyone, I have joined this forum just now hoping to find some help for my problem. I have a mysql query in my php file which i output to an array of html divs. The code is as follows: $result = mysql_query("SELECT * FROM numserved WHERE status = 'on'") or die(mysql_error()); while($row = mysql_fetch_array($result)) { ?> <div style="font-size:<?php echo $fontsize; ?>pt;" valign="middle" class="numberz" align="center" > <?php echo $row['number']; ?></div><?php } ?> I wanted to know if anyone could help me write the code to make this query be updated every 3 seconds without reloading the whole page. I know it is done by Ajax and tried to implement the Jquery solution , but I wasnt able to apply it. Anyone would be so kind to tell me the exact code i need and where to place it? Thank you
  24. Great site!, Im trying to understand a bit more pdo.. I have the following: I have a svg and when I click on the map the country name is loaded into a var on the click event by the code below: <script> function fill_contact(evt) //display click event { var country_id = evt.target.id document.getElementById('country_name').firstChild.data = country_id } </script> My php code is as follows: <?php //Define constants define('DB_DRIVER', "mysql"); define('DB_SERVER', "127.0.0.1"); define('DB_DATABASE', "aeea"); define('DB_USER', "root"); define('DB_PASSWORD', "root"); //Database connection try { $dbh = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ die("Sorry, we could not connect you to this database, please contact the Administrator to sort this out.". $e->getMessage()); } //Get data $query = "SELECT firstname, lastname, email, photo FROM reps WHERE country like ?"; $country = 'country_name'; //Create the statement $stmt = $dbh->prepare($query); $stmt->execute(array($country)); //Use data $row = $stmt->fetch(PDO::FETCH_ASSOC); echo '<pre>', print_r($row), '</pre>'; ?> My Html code is as follows: <div id="IndexPage"> <div id="IndexPage_Left"> <div id="IndexPage_Left_top"> <h3>Country: <span class="label" id="country_name"> </span></h3><!—This works fine--> <p></p> <h4>Regional Representative: <span class="label" id="firstname"> </span></h3></h4><!--get Rep ” firstname, lastname” from database based on country from svg to display--> <p></p> <h4>Photo</h4><!--get Rep “photo” from database based on country from svg to display--> <p></p> <input style='margin-top: 20px;' type="submit" value="Contact me." id='jqxSubmitButton' /><!-- if clicked, it opens a contact form below, the email address is hidden--> </div> <div id="IndexPage_Left_bottom"> <h4>email form here<h4><!-- if email is clicked, it opens a contact form here with “email” address from database --> </div> </div> <div id="IndexPage_Right"> <svg id="map" version="1.1" and rest of svg code. My database has a table called reps. It had dta of representatives in each country in Africa. It has a number of fields ie. rep_id(unique indexed), firstname, lastname, email, postal, city, state, country, contact_no, photo etc. I want to be able to get the fields in the database and display them in the html form on the click events. Ie. The database must also refresh the query every time a click event happens. Guests might click a few countries to look at reps. If they click off the map, it blanks out the details. How do I go about doing this? I’ve heard about XMLHttpRequest but don’t know how to go about doing it. Another question: Once I get the information, how do I display it correctly in the Html? I used <span>, but is it correct? Last question: Once I get the information email address, how do I show a contact form on "conact me" button? and then when guests click on another country, remove the contact form? This is my first website. Please help
  25. Hi, I have the following setup: A main-page.php that is consisted of: 1) A header 2) A nav bar 3) Content (is loaded inside a <div id="dynamic-content"></div>) 4) Footer Inside the nav bar you find several options (ex. About Us, Contact Us, etc..). Lets say that the script responsible for "About Us" is called about-us.php. What i want to achieve is to load the output of about-us.php page inside the content area (aka the dynamic-content div), as soon as i press the "About Us" button (#about-us div). In order to achieve this i use the following AJAX call: $("#about-us").on('click', function(){ $.ajax({ url: "about-us.php", success: function(output){ $("#dynamic-content").html(output); } }); }); Both main-page.php and about-us.php include their own CSS and JavaScript files: main-page.js and main-page.css included in main-page.php about-us.js and about-us.css included in about-us.php THE PROBLEM I FACE: Initially the tabs inside nav bar (About us, Contact Us, etc) were stand alone pages, meaning when you clicked on the link it redirected you to a new URL (for example http://www.domain.com/about-us.php). In this case about-us.php was consisted of a head where all CSS was included, a body where all JS was included, In other words it was a complete HTML/PHP page. The page was working properly. When i tried to load this page into a div inside main-page.php, i started facing some problems. Sometimes CSS was overwritten by the CSS of Contact Us causing problems (at this point i have to mention that since about-us.php and contact-us.php were stand alone pages, sometimes we used the same classes/ids to target DOM elements). Problems started to happen with JS as well. THE QUESTION: What is the correct way to use CSS and Javascript files of about-us.php? Should i include them inside the about-us.php script or include them inside the main-page.php? Do i have to create one big CSS and one big JS file that will include all previously created CSS and JS that will target each element of each imported page? Is there another way? Thanks in advance.
×
×
  • 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.