Jump to content

Search the Community

Showing results for tags 'Ajax'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • W3Schools
    • General
    • Suggestions
    • Critiques
  • HTML Forums
    • HTML/XHTML
    • CSS
  • Browser Scripting
    • JavaScript
    • VBScript
  • Server Scripting
    • Web Servers
    • Version Control
    • SQL
    • ASP
    • PHP
    • .NET
    • ColdFusion
    • Java/JSP/J2EE
    • CGI
  • XML Forums
    • XML
    • XSLT/XSL-FO
    • Schema
    • Web Services
  • Multimedia
    • Multimedia
    • FLASH

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


Languages

Found 120 results

  1. Shinori

    Ajax inside of Ajax?

    Hello potential helpers, im currently having issues with firing an ajax request inside of another ajax request. Heres my code: Im not getting "alert(content)" Condition if(shop[1] == "gserver") and if(name.includes(shopname) == true) are definetly true. The function is correctly called as well. No Im not using jquery for reasons. Anyone has an idea why the 2nd requests isnt fired? Is it not waiting for the first one to finish? function initiate_shop_game(shopname) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { var obj = this.responseText; var array = eval("[" + obj + "]"); var r = 1; for(var i = 0; i < array.length; i++) { for(var x = 0; x < array[i].length; x++) { var shop = array[i][x] + ''; shop = shop.split(","); if(shop[1] == "gserver") { var name = shop[2]; var imgname = shop[7] var shopvalues = shop[3].split("{%TEND%}"); var minslots = parseInt(shopvalues[1]); var maxslots = parseInt(shopvalues[2]); var minram= parseInt(shopvalues[3]); var maxram = parseInt(shopvalues[4]); var pricea = (parseFloat(shop[5]) / 30); var priceb = (parseFloat(shop[6] / 30)); var content = [name,imgname,minslots,maxslots,minram,maxram,pricea,priceb]; if(name.includes(shopname) == true) { var div = document.createElement('div'); div.id = name; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { alert(content); }; xmlhttp.open('POST',"/template_shop.php", true); xmlhttp.send(); } } } } } } }; xmlhttp.open('POST',"/get_shop_data.php", true); xmlhttp.send(); }
  2. s_avinash_s

    submit with xhttp

    Hi Am trying to submit the data to server, nothing is received on server. I mean "dismissed students" and "failed students " am filling and sending but not receiving on server side. How to get the data on server side. <div id="Examination" class="tabcontent"> <html> <body> <p id="exam"></p> dismissed students: <input type="text" name="index1" size="10"> <br><br> failed students: <input type="text" name="index2" size="10"> <button type="button" onclick="entry()">submit</button> <script> function entry() { var formData = new FormData(); var valid = new XMLHttpRequest(); valid.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("exam").innerHTML = this.responseText; } }; valid.open("POST", "exam.txt", true); xhttp.send(formData); } </script> I just added "formData" and i get just some junk characters not original data.How to fill the data in "formData" How to get the data, anything else is required to make it work. Thanks Avinash
  3. iwato

    A Matter of Scope

    GENERAL QUESTION: Can variables created outside of a function be used within a function without having to read them first as arguments of the function? If so, can a function created within a function use a variable created outside of both functions? CODE var dataString = 'search_input=' + search_letter_input; $.ajax({ type: "POST", url: './...', data: dataString, dataType: 'JSON', statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(jsonData) {...} }); SPECIFIC QUESTION: I would like to use the value of the variable search_letter_input in the success function of the $.ajax( ) method. Is this possible? Roddy
  4. BACKGROUND: I have now tried a number of ways to make two cURL calls within the same Javascript (jQuery) routine. For each new way, I have discovered what I believe to be a reasonable explanation for my failure. For my most recent attempt, however, a good explanation is not forthcoming. To be sure, single AJAX calls with a single cURL call for each yield the desired results. Simply I cannot seem to combine these results simultaneously on the same page. The scenario given below, for example, returns the desired outcome for the second cURL call, but not the first. JAVASCRIPT: $.ajax({ url: '.../VisitsSummary.php', method: 'GET', data: {methodName : '_get', methodName : '_getSumVisitsLengthPretty'}, dataType: 'JSON', statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(visitsSummary_data) { console.log(visitsSummary_data); var tv = visitsSummary_data.nb_visits; var uv = visitsSummary_data.nb_uniq_visitors; var visits_per_unique_visitor = Math.round(tv/uv * 10)/10; $('#so_total_visits').html(visitsSummary_data.nb_visits); $('#so_unique_visitors').html(visitsSummary_data.nb_uniq_visitors); $('#visits_per_visitor').html(visits_per_unique_visitor); $('#so_average_time_spent').html(visitsSummary_data.avg_time_on_site); } }); PHP: if (isset($_GET['methodName'])) { $method_name = $_GET['methodName']; if ($_GET['methodName'] == '_get') { $url = 'https://.../index.php?module=API&action=index&method=VisitsSummary.get&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...'; $curl_request = curl_init(); curl_setopt($curl_request, CURLOPT_URL, $url); curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false); curl_exec($curl_request); if(curl_errno($curl_request)) { echo 'Curl error: ' . curl_error($curl_request); } curl_close($curl_request); } if ($_GET['methodName'] == '_getSumVisitsLengthPretty') { $url = 'https://.../index.php?module=API&action=index&method=VisitsSummary.getSumVisitsLengthPretty&idSite=1&period=year&date=today&format=json&token_auth=&token_auth=...'; $curl_request = curl_init(); curl_setopt($curl_request, CURLOPT_URL, $url); curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false); curl_exec($curl_request); if(curl_errno($curl_request)) { echo 'Curl error: ' . curl_error($curl_request); } curl_close($curl_request); } } QUESTION: Can you find anything wrong with the above strategy? If so, what would you recommend to replace it? Roddy
  5. BACKGROUND: I have a plain text file with an .html extension. In the file is a <p> element into which I would like to enter the current date. The file is called from its hostpage via a jQuery $.get() statement that is followed with an AJAX call to a PHP processing file that returns JSON that can be processed in the AJAX success function as an object. QUESTION: If I place the PHP necessary to create the date in the text file with the .html extension, will it appear in the hostpage when called by the $.get() method? NOTE: My server is programmed to accept PHP in files with a .html extension. Mind you, the text file has neither <head>, nor <body> element, let alone a <DOC> header. Roddy If I enter the data with PHP before the AJAX
  6. How i make a Real time comment-replay script system in a website ?
  7. GREETING: One more quick question before the weekend begins. BACKGROUND: Until now, it has been easy to see the results of AJAX calls in the files that produce them. Until now, cURL was never an explicit part of my web-application. I am now making a dual call, however, and am unable to see the final result. The first call stipulates no method as nothing is sent. The second call is based on the result of the first call and uses the POST method to make the request. Although I can see the contents of the first request, I cannot see the contents of the second. Both files use identical cURL routines and both perform exactly as expected, as AJAX returns everything that is requested. Only the query statements of the URL are different. Even the specified AJAX dataType is the same for both calls -- namely, JSON. Please find below the code that produces the output that I wish to see, but cannot. The PHP for the 2ND AJAX CALL ini_set('log_errors', 1); ini_set('error_log', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'error.log'); ini_set('html_errors', 0); ini_set('display_errors', 0); error_reporting(E_ALL); if (!empty($_POST['ip_addr'])) { $ip_addr = filter_var($_POST['ip_addr'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); $url = 'https://.../matomo/index.php?module=API&action=index&visitIp=' . $ip_addr . '&idSite=1&period=week&date=today&method=Live.getVisitorProfile&format=json&expanded=0&token_auth=...'; $curl_request = curl_init(); curl_setopt($curl_request, CURLOPT_URL, $url); curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, false); curl_exec($curl_request); curl_close($curl_request); } QUESTION; What must I do to make the output of the cURL call visible in the file that produces it without disrupting the AJAX call that retrieves the output that I cannot see. Or, am I missing the whole point of cURL and the data is tranferred directly to the AJAX? But, why would I be able to see it in the first request, but not the second. Roddy
  8. BACKGROUND: A visitor arrives on a website. While still on the site he triggers an AJAX call that fills a <div> element with new HTML. Once the page is filled another AJAX call is made that seeks to read the following value as encoded JSON: $_SERVER['REMOTE_REFERER']. Instead I receive a 500 internal server error. The AJAX (function() { $("#main").html(''); $("<link/>", { rel: "stylesheet", type: "text/css", href: "./_utilities/css/yourprofile_filler.css" }).appendTo("head"); $.get('./yourprofile_filler.html', function(data) { $('#main').html(data); }).done(function(){ $.ajax({ url: './_utilities/php/visitor_ip.php', dataType: 'JSON', statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(visitor_ip) { console.log(visitor_ip); } }); }); })(); The PHP <?php $referral_addr = $_SERVER['REMOTE_REFERER']; echo json_encode($referral_addr); ?> ERROR MESSAGE jquery.min.js:5 GET https://www.grammarcaptive.com/_utilities/php/visitor_ip.php 500 (Internal Server Error)send Is the $_SERVER variable not available in the moment of the AJAX? How do I otherwise make it available? Roddy
  9. BACKGROUND: I am querying a MySQL database with a Matomo GUI. The API is called imageGraph. The call to the API works, as I have produced the desired image by assigning the URL as the value of an href attribute of an HTML <a> element. When using this link to display the image the image appears on a new page with its own header. This is not the effect that I desire. My goal is to display the image within a <div> tag on a webpage. The code that is suppose to achieve this latter effect is provided below. The URL that fetches the data from the API is identical for both the link and the PHP processing page for the AJAX call provided below. The PHP (./practice.php) $url ='https://.../matomo/index.php ?module=API &method=ImageGraph.get &idSite=1 &apiModule=Referrers &apiAction=getReferrerType &token_auth= ... &period=day &date=2018-04-10,2018-05-09'; $curl_request = curl_init(); curl_setopt($curl_request, CURLOPT_URL, $url); curl_exec($curl_request); curl_close($curl_request); The HTML <div id='referral_types'> <img src='' alt='Line Chart of Referral Types' /> </div> The Javascript $(document).ready(function() { $.ajax({ method: 'GET', url: "./practice.php", cache: false, contentType: 'image/png', success: function(response) { console.log(response); var graphic_src = response; $('#referral_types').find('img').attr('src', graphic_src); } }); }); EXPERIMENTATION: The console indicates that practice.php has been read, as it is filled with the kind of character nonsense typical of an image file. As the API permits an optional &format parameter I experimented with several including the following: AJAX PHP dataType JSON, &format=json dataType XML &format=xml (omit) &format=original The result was invariably the same. The ALT message with no image. Please advise. Roddy
  10. i was trying to use a ajax returned value out of the ajax function but it didn't work. can anyone please guide me. here is the code i tried. var lat, lng; $.ajax({ url: url, dataType: "json", method: "get", success: function(res) { var lat = res[imei].lat; var lng = res[imei].lng; } }); $("#lng").text(lng); $("#lat").text(lat); thanks in advance.
  11. hello all, i am trying to run an ajax request inside a for loop. and when the response is true, i want to run another ajax only once. but the second ajax also runs multiple times. here is the code i tried .... var i; for (i=0; i< feeid.length; i++) { $.ajax({ url: "submitnewjournal.php", method: "POST", data: { m: m, fullvn: fullvn, vn: vn, }, }) .done (function(result) { var success = $(result).filter("#success").text(); $("#msg").text($(result).filter("#msg").text()); if (success == "NO") { $('#pwait').hide('clip', "fast"); $("#msg").css("color", "red").show("bounce", 100); $('#feelist, #studentlist').show('fade', 250); } else { $("#msg").css("color", "green").show("bounce", 100); $("#fullvn").text($(result).filter("#newfullvn").text()); $("#prefix").text($(result).filter("#newprefix").text()); $("#vn").text($(result).filter("#newvn").text()); /***********************************************************************************************/ /************************* this is the part i want to run onle one time*************************/ /***********************************************************************************************/ if (sendnotice == "Y") { $("#msg").text("Invoice saved successfully. Now sending notification!"); var target = "< PARENTS >"; var receipients = "INVOICE"; var clas = $('#clas :selected').val(); var sec = $('#sec').val(); $.ajax({ url: "noticeprocess.php", method: "POST", data: { target: target, targetid: target, receipient: receipients, token : receipients } }) .done(function(result) { $("#msg").hide("fade", 100).empty().text($(result).filter("#msg").text()); var success = $(result).filter("#success").text(); if (success == "YES") { $("#msg").css("color", "green").show("bounce", 100); $("#pwait").hide("clip", "fast"); // $('#mainarea').load('mnthsalary.php'); } else if (success == "NO") { $("#msg").css("color", "red").show("bounce", 100); } }) .fail(function(e) { $("#msg").hide("fade", 100).empty().text("Connection Error!").css("color", "red").show("bounce", 100); }) window.open("print.php?m=newmnthinvoice&invno=" + fullvn, "_new"); /*********************************************************/ } else { $("#msg").text("Invoice saved successfully."); $('#pwait').hide('clip', "fast"); } } }) .fail(function() { $('#pwait').hide('clip', "fast"); $('#msg').text('Connection problem!').css('color', 'red'); $('#feelist, #studentlist').show('fade', 250); }) } please guide me how can i achieve this. thank u in advance....
  12. I've built a static site with over 40,000 pages using Jekyll. I am trying to implement a live search into it without a database. I tried the w3schools live search example with a xml file I created from my site. It is very slow. Does anyone know of a faster way to parse xml files or am I wasting time. I enabled gzip compression on the entire site also, What would be the fastest way to search a lot of records and return a result? Thanks in advance.
  13. BACKGROUND: My objective is to replace the content of an existent <div> element with new content that depends on newly loaded javascript, css, and a JSON object retrieved from a PHP processing file by an AJAX call. To this end I have written the following brief piece of code. To be clear the script contained in wordcount.js depends on the value of wordmax. Further this same script is triggered when text is entered into a <textarea> form control found in newsletter.html. Please review the code and answer the questions that follow. .click(function() { $('#main').html(''); ajax_obj = $.ajax({ url: 'newsletter_filler.php', data: {name : 'personal, length : 200}, dataType: JSON, statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(jsonData) { $.getScript('wordcount.js', function(data) { var wordmax = jsonData; }); $.get('newsletter.css', function(data) { $('head style').append(data); } $.get('newsletter.html', function(data) { $('#main').html(data); } } }); } QUESTION ONE: Under the assumption that all of the code in the called files has been properly written and that the content of the .css and .html files is properly placed will the script contained in wordcount.js execute properly when triggered by the content of newsletter.html? QUESTION TWO: Will the content of the files newsletter.css and newsletter.html find their proper place and function as one might expect from such code, if it had been placed in the main document in the elements indicated by jQuery selector at the outset? Roddy
  14. BACKGROUND: I have learned to keep a log that increases incrementally with the generation of each new newsletter and podcast. 1) Read the Current Log Value $file = './episode_index.txt'; if (file_exists($file)) { $json_str = file_get_contents($file); $episode_no = json_decode($json_str, true); $number = $episode_no['episode_no']; $new_episode = $number + 1; } else { echo 'The desired file either does not exist, or does not exist in the indicated location.'; } 2) Take Some Action and Update the Log Value Incrementally if (!is_blank($_POST['letter_no'])) { $episode_no['episode_no'] = $number + 1; $json_str = json_encode($episode_no); file_put_contents($file, $json_str); } in effect, I perform a simple file_get_contents and file_put_contents on a single document whose only value is that of a single JSON object whose value increases incrementally with the creation of each new newsletter. In order to keep track of my podcasts I need something vastly more complex, for not only must I be able to automatically generate a new counter with each new podcast that I generate, but each counter thus created must keep track of each and every hit of any and all podcasts by each and every known and anonymous podcast user. Further, once this data is recorded it must be easily accessible for the purpose of analysis. In effect, I am loathe to generate a separate document for each new podcast. Although a workable tool for each individual podcast, i cannot imagine it as a very effective way to manage data for all of my podcasts in aggregate or any desired subset thereof. Perhaps I could create a single MySQL table with a set number of fields for all podcasts. Then, 1) With each new podcast insert a new row of data, and 2) with each new user hit of a particular podcast update the field values for the affected row. Might I receive some input in these regards? Roddy
  15. BACKGROUND: I have created a PHP routine that gathers data from a MySQL database. The data that it gathers depends on the value of an HTTP request that uses the $_GET superglobal as its transfer mechanism. The routine further organizes the retrieved information into a nested array such that each element of the array corresponds to a different table row, and each element of each nested array corresponds to a subset of the table fields. Once the nested array has been completed the json_encode() function converts the array into a JSON string and readies it for transport. The PHP <?php if(isset($_GET['podType']) { define('_HOST_NAME','...'); define('_DATABASE_NAME','...'); define('_DATABASE_USER_NAME','...'); define('_DATABASE_PASSWORD','...'); $mysqli_obj = new MySQLi(_HOST_NAME,_DATABASE_USER_NAME,_DATABASE_PASSWORD,_DATABASE_NAME); if($mysqli_obj->connect_errno) { die("ERROR : -> ".$mysqli_obj->connect_error); } $tbl_name = 'rss2_podcast_item'; $podcast_items = []; $result_obj = $mysqli_obj->query("SELECT * FROM " . $tbl_name); while($row = $result_obj->fetch_assoc()) { foreach($row as $key => $value) { $item_arr[$key] = $value; } $items[] = $item_arr; } //Creates a nested array whose subarrays consist of the four indicated elements. foreach ($items as $sub_arr => $element) { $podcast_item[] = $element['podcast_no_item']; $podcast_item[] = $element['item_title']; $podcast_item[] = $element['item_description']; $podcast_item[] = $element['item_pubdate']; $podcast_items[] = $podcast_item; $podcast_item = []; } echo json_encode($podcast_items, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_NUMERIC_CHECK); } ?> The Javascript <script> $(document).ready(function() { $('li.podDex').each(function(){ var podType = $(this).attr('id'); //Causes the weight of the font to change when the mouse passes over the text. $('#'+podType).mouseover(function() { $(this).css({"cursor": "pointer", "font-weight":"800"}); }) .mouseout(function() { $(this).css("font-weight", "normal"); }); //Causes the weight of the font to change, displays the hidden text to appear in the #main <div> element, and brings about a change in color. $('#'+podType).mouseover(function() { $(this).css({"cursor": "pointer", "font-weight":"800"}); }) .click(function() { $.getJSON({ url: "../exp1/ajax_data.php", data: podType, success: function(json_data){ var data_array = $.parseJSON(json_data); alert(data_array[0]['podcast_no_item']); } }); }) .mouseup(function() { $(this).css({"color": "#fadb9d","font-weight": "normal"}); $('body, html').animate({scrollTop: $('#main').offset().top},800); }); }); }); </script> The HTML <ul> <li id='linear' class='podDex'>Linear Analysis</li> <li id='clausal' class='podDex'>Clausal Analysis</li> <li id='inversion' class='podDex'>Socratic Inversion</li> <li id='chronology' class='podDex'>Chronology</li> </ul> The Console Error Message is You are welcome to try it yourself. Please go to Grammar Captive and click on any of the four designated <li> elements. QUESTION: What might be causing the $.getJSON() call to fail? NOTE: A similar, but not identical, result occurs on my local test server.
  16. Hi all, I'm just starting to get into website design, tho' I've been a programmer for many years. I've got a site going pretty well, but I really want to update the information on the site every day using tables. I am studying the AJAX/XML method and I think I must be missing something. After using the 'display CD collection' as a model, I couldn't get it to work. So then I tried copying & pasting the actual files from the example ( they list the xml file for your reference ) into a folder and Opened it with a google browser. I can get the button that says 'create my CD collection', but nothing happens when I click it. What am I missing; is there another article that might explain this in more detail and say exactly what's going on? Thanks
  17. iwato

    Executing PHP after window.open

    RECENT DISCOVERY: I recently discovered a handy PHP function called show_source( ) and would now like to apply it in a particular sort of way. GOAL: I would like to open a new tab in my current window that shows the source code of a page that I have opened in the window. DILEMMA: Since PHP operates before a page is opened I am a lot confused about how to make this happen. This is what I have accomplished so far. $( document ).ready(function() { console.log( "ready!" ); $('.show_src a').on('click', function(event) { event.preventDefault(); var address = $(this).attr('href'); window.open(address); ... }); }); <li class='show_src'>The <a href='./composer/php_rss_generator/RSSGenerator/ItemInterface.php' title='' target='_blank'>Interface</a></li> <li class='show_src'>The <a href='./composer/php_rss_generator/RSSGenerator/Item.php' title='' target='_blank'>Class</a></li> I have tried a variety of ways to replace the three dots above including .ajax( ) and window.write( ) but nothing seems to work. Any ideas? Roddy
  18. tea

    inside Ajax success

    Hi... I am inside Ajax success function... here is my code... I have accessed the client server url successfully, but also I have to execuet the query that i have to get the result inside the Ajax function to post in my jsp page..... can someone please assist on how we can acheive this? function Call() { var query='select * from employees'; var querystring = "joinType=3&userLocale=English&query="+query&maxrow="2; $.ajax({ url:'https://testurl', type:'POST', success: function(data, url, jqhxr) { $('#div').html(this.url); console.log('Am here nowww',this.url); } }); };
  19. I have a coded servlet already in HTTP url. I want to access and display the data from (http url) servlet to my new JSP within <div> here is the more details :https://gist.github.com/theakathir/f6fb390d35b451a57958aa0d3cf05330 about the servlet content. I am very new Ajax,. All i want to do in, In my new jsp page i will have a button to click which will access the data from the http url (servlet) using Ajax. Can someone direct me with some reference to start with.. It would be helpful Thanks.
  20. First off, thanks for letting me into the forums. Excuse a newbie but I have a question about fetching data from a database with PHP and AJAX. Let's say I wanted to fetch data from the database like in this example from W3Schools, but I had modified the dropdown to for example fetch all entries with last name Griffin, Swanson or Quagmire. I made the q variable take a string instead of an integer. $q = strval($_GET['q']); Now I want to expand the SQL query to also take another condition. "SELECT * FROM user WHERE LastName = '".$q."' AND Hometown = '".$q2."'"; I understand how to build the query and that I need to declare another variable (q2), but how do I modify the AJAX request? xmlhttp.open("GET","getuser.php?q="+str,true); Also, would I need to have a submit button now that there are two conditions? Thanks!
  21. I'm looking for a way to display the contents of an XML file on a web page with AJAX. I rely on the w3schools "simple CD catalog application", which shows a part of the XML (author and title) and, when you click on a title, displays the details of the CD. I need, however, to be able to add sorting and filtering when displaying artist and title - it could, for instance, be sorting the titles alphabetically or apply a filter based on the year of release. XSLT doesn't seem to work with AJAX so I hope JavaScript could be the answer: Is it possible to add such functions to the application example using JavaScript - and how could it be done? I'd really be glad if someone could help.
  22. I'm trying to select data from a MySQL database that is hosted on a webserver. I want to be able to retrieve the data from a table within the database and then illustrate it within a HTML table. There's an example on W3Schools that I've been following, but I'm unable to retrieve the data successfully. http://www.w3schools.com/php/php_ajax_database.asp Below is the source code: (HTML) <html> <head> //Javascript code <script> function showUser(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 (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Joseph Swanson</option> <option value="4">Glenn Quagmire</option> </select> PHP File: (getuser.phd) <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } table, td, th { border: 1px solid black; padding: 5px; } th {text-align: left;} </style> </head> <body> <?php $q = intval($_GET['q']); $con = mysqli_connect('www.example.com','user_Admin','12345-678','my_DB'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?> </body> </html> *MySQL table is attached I think the issue might exist from mysqli_select_db($con,"ajax_demo"); onwards inside the PHP file. Should I be referring to the table that contains the data inside the database? I have the PHP File hosted on my webserver, so I'm not sure why it won't retrieve that data when a person is selected from the list of options on the HTML page. Any help would be much appreciated.
  23. Is it possible to add a 1 vote per IP restriction for this poll without using php? If not with IP restriction, how could a repeated voting of the same person be avoided? How can a Results link be added? Where should it refer? Thank you!
  24. rich_web_development

    Display Everything on the same page

    Hi, I'm trying to get a form where you submit information about a home to a database and below the form it displays the homes with the information and a photo. Below the home information and photo I have a button to DELETE RECORD and a button to upload a photo. All of the php and forms are in one file so submitting the home info and deleting record are just have action="samefile.php". This is so that it stays on the same page and doesn't have to jump to another page. I cannot get the upload photo to stay on the same page. The only way I can get the upload photo to work is to send it to another file. This of course takes me to another page which I don't want. I want everything to stay on the same page. The code I have (in a file called "PicTest03.php) is as follows: <!DOCTYPE html> <head> </head> <html> <body> <form action="PicTest03.php" method="POST"><pre> Name <input type="" name="name"> Bedrooms <input type="text" name="bedrooms"> Length <input type="text" name="length"> Width <input type="text" name="width"> Serial Number <input type="text" name="serialno"> <input type="submit" value="ADD RECORD"> </pre> </form> <br><br><br> <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); if (isset($_POST['delete'])&& isset($_POST['serialno'])) { $serialno = get_post($conn, 'serialno'); $query = "DELETE FROM holidayhomes WHERE serialno='$serialno'"; $result = $conn->query($query); if (!$result) echo "DELETE failed: $query<br>" . $conn->error . "<br><br>"; } if (isset ($_POST['name']) && isset ($_POST['bedrooms']) && isset ($_POST['length']) && isset ($_POST['width']) && isset ($_POST['serialno'])) { $name = get_post ($conn, 'name'); $bedrooms = get_post ($conn, 'bedrooms'); $length = get_post ($conn, 'length'); $width = get_post ($conn, 'width'); $serialno = get_post ($conn, 'serialno'); $query = "INSERT INTO holidayhomes (name, bedrooms, length, width, serialno) VALUES ('$name','$bedrooms', '$length', '$width', '$serialno')"; $result = $conn->query($query); if (!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; } $query = "SELECT * FROM holidayhomes"; $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); $rows = $result->num_rows; for ($j = 0 ; $j < $rows ; ++$j) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_NUM); echo <<<_END <pre> name $row[0] Bedrooms $row[1] Length $row[2] Width $row[3] Serial No $row[10] MainPic $row[4] <img src="uploads/$row[4]" width=200 height=200> </pre> <pre> <form action="PicTest03.php" method="POST"> <input type="hidden" name="delete" value="yes"> <input type="hidden" name="serialno" value="$row[10]"> <input type="submit" value="DELETE RECORD"> </form> </pre> <pre> <form action="mainphoto01.php" method="post" enctype="multipart/form-data"> Select main photo: <input type="hidden" name="serialno" value="$row[10]"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </pre> <br><br> _END; } $result->close(); $conn->close(); function get_post($conn, $var) { return $conn->real_escape_string($_POST[$var]); } ?> </body> </html> The code for "mainphoto01.php is: <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false){ echo "FIle is an image - " . $check["mime"] . "." ; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } if ($uploadOk == 0){ echo "Sorry, your file was not uploaded."; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){ echo "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { echo "Hello!"; } } $mainpic = basename( $_FILES["fileToUpload"]["name"]); if(isset($_POST["serialno"])) $serialno = $_POST['serialno']; $query = "UPDATE holidayhomes SET mainpic='$mainpic' WHERE serialno='$serialno'"; $result = $conn->query($query); if(!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; ?> No matter what I try I cannot get the above code to work if I keep it in the "PicTest03.php" file. Can someone please show what the code should look like so I can get everything to show on the same page? I have had a look as the PHP and AJAX and DATABASE http://www.w3schools.com/php/php_ajax_database.asp which I got the example working but it uses a drop down list. Is there a way to convert the code used for the example on http://www.w3schools.com/php/php_ajax_database.asp and instead of drop down list just have the information from the database shown under the form for submitting the home information?
  25. mysteriousmonkey29

    Proof of concept Ajax MVC?

    Hello, I am trying to create a proof of concept webpage that changes text in response to a button press using an MVC pattern (or at least as I understand it), and Ajax to avoid reloading the page. (I would like to implement Ajax in a larger MVC program I am working on but thought I would try to get it to work small-scale first). From playing around with examples here and here: https://www.sitepoint.com/the-mvc-pattern-and-php-1/ http://www.w3schools.com/php/php_ajax_php.asp I have the program working with each component individually (it works with the MVC pattern if I don't mind reloading the page to update the text, or it works without reloading the page if I don't mind essentially scrapping the MVC pattern). However, I'm trying to get both to work at once. I have combined the two examples so that the view uses Ajax to call the appropriate controller function, which successfully modifies the model (I'm sure this part works from debugging the program). However, when I try to refresh the content of the page using the output function of the view, nothing happens without reloading the page. Here is my code so far: <html> <head> <meta charset="UTF-8"> <!--ajax attempt--> <script> function callTextChange () { var xmlhttp = new XMLHttpRequest(); //if uncommented, this changes the text, but it doesn't fit with my MVC pattern /*xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("text").innerHTML = "changed with purely Ajax, without using MVC"; } };*/ xmlhttp.open("GET", "index.php?action=changeText", true); xmlhttp.send(); } </script> </head> <body> <?php class Model { public $text; public function __construct() { $this->text = 'default'; } function changeText () { $this->text = 'changed'; } } class View { private $model; public function __construct(Model $model) { $this->model = $model; } public function output() { //regular MVC method using button as a link //return $this->model->text.'<a href="?action=changeText"><button>change text</button></a>'; //attempted ajax method using button on click attribute to make an Ajax call return '<p id="text">'.$this->model->text.'</p>'.'<button onclick="callTextChange()">change text</button>'; } } class Controller { private $model; public function __construct(Model $model) { $this->model = $model; } function changeText() { $this->model->changeText(); } } $model = new Model(); $controller = new Controller($model); $view = new View($model); if (isset($_GET['action'])) { $controller->{$_GET['action']}(); } echo $view->output(); ?> </body> Any idea how to do what I'm trying to do? Is this even possible? Help would be much appreciated
×