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. hello all. i dont know if to post this here or javascript/ajax section. if its not the right place, please let me know so i can ask in the right place. i am trying out saving to db via modal form. i learned the basics of using ajax to save data with the modal. so far, i can perform a CRUD via modal but the problem i am having is displaying duplicate entry error inside the modal. I have tried so many ways and the closest i come is displaying error only if a field is duplicate cos i use same trigger as my validation error notice. I'd be glad if i am shown the way to get it to display the error or a better way of getting it done. PS: I want the errors displayed inside the modal. I want the database query error to display where the success message is displayed (i.e on the modalMessage div) Thanks My Modal <div class="modal fade" id="armsModal" data-bs-backdrop="static" tabindex="-1" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header modal-bg"> <h5 class="modal-title w-100 text-center mb-3" id="exampleModalLabel4">Add School Arms</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form id="submitForm" class="myForm"> <div class="modal-body"> <div id="modalMessage"></div> <div class="mb-3"> <label for="armsname" class="form-label">Arms FullName:</label> <input type="text" class="form-control" id="arms_long_name" name="arms_long_name" autocomplete="off" value="<?php if(isset($_POST['arms_long_name'])){ echo $_POST['arms_long_name']; } ?>"> <span id="longNameError" class="text-danger"></span> </div> <div class="mb-3"> <label for="armsshort" class="form-label">Arms ShortName:</label> <input type="text" class="form-control" id="arms_short_name" name="arms_short_name" autocomplete="off" value="<?php if(isset($_POST['arms_short_name'])){ echo $_POST['arms_short_name']; } ?>"> <span id="shortNameError" class="text-danger"></span> </div> </div> <div class="modal-footer modal-bg"> <button type="button" class="btn btn-outline-light btn-sm" data-bs-dismiss="modal"> Close </button> <button type="submit" class="btn btn-dark btn-sm">Submit</button> </div> </form> </div> </div> </div> My script <script> //Modal $('#submitForm').submit(function(event) { event.preventDefault(); $("#armsModal").on("hidden.bs.modal", function() { $('#longNameError').text(''); $('#shortNameError').text(''); $("#submitForm")[0].reset(); }); $('#armsModal').on('hidden.bs.modal', function () { // Clear form fields $('#submitForm')[0].reset(); // Clear error messages $('.invalid-feedback').text(''); }); // Get form data var formData = { 'arms_long_name': $('#arms_long_name').val(), 'arms_short_name': $('#arms_short_name').val() }; // AJAX request $.ajax({ type: 'POST', url: 'school-arms-action.php', data: formData, dataType: 'json', encode: true }) .done(function(data) { if (!data.success) { if (data.errors.arms_long_name) { $('#longNameError').text(data.errors.arms_long_name); } if (data.errors.arms_short_name) { $('#shortNameError').text(data.errors.arms_short_name); } }else{ modalMessage.innerHTML = '<div class="alert alert-success text-center text-black">ARMS SAVE SUCCESSFUL!</div>'; setTimeout(function() { window.location.href = 'school-arms'; }, 2000); // 2 seconds delay } }); }); </script> My school-arms-action.php $response = array('success' => false, 'errors' => array()); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $arms_long_name = ucwords($_POST['arms_long_name']); $arms_short_name = strtoupper($_POST['arms_short_name']); $arms_id = mt_rand(100, 999); // Validation if (empty($arms_long_name)) { $response['errors']['arms_long_name'] = 'Arms LongName is Required.'; } if (empty($arms_short_name)) { $response['errors']['arms_short_name'] = 'Arms ShortName is Required.'; } // If no errors, proceed to submission if (empty($response['errors'])) { try { $pdo = new PDO("mysql:host=localhost;dbname=db_name", "username", "password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $table=$pdo->query("ALTER TABLE tbl_school_arms AUTO_INCREMENT = 1"); $table->execute(); $stmt = $pdo->prepare(" SELECT * FROM tbl_school_arms WHERE arms_name_long = :arms_name_long OR arms_name_short = :arms_name_short "); $stmt->bindParam(':arms_name_long', $arms_long_name, PDO::PARAM_STR); $stmt->bindParam(':arms_name_short', $arms_short_name, PDO::PARAM_STR); $stmt->execute(); $existingEntry = $stmt->fetch(PDO::FETCH_ASSOC); if ($existingEntry) { //This is what i used but not the right thing i want $response['errors']['arms_long_name'] = 'Duplicate Entry'; } else { // Perform database operations using PDO $stmt = $pdo->prepare(" INSERT INTO tbl_school_arms (arms_id, arms_name_long, arms_name_short) VALUES (:arms_id, :arms_name_long, :arms_name_short)"); $stmt->bindParam(":arms_id", $arms_id); $stmt->bindParam(":arms_name_long", $arms_long_name); $stmt->bindParam(":arms_name_short", $arms_short_name); $stmt->execute(); if($stmt->rowCount()){ $response['success'] = true; } } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } } } echo json_encode($response);
  2. I am using osclass Osclass v8.0.2 free classified. I am trying to implement load more i.e infinite scroll facility on homepage page. When user scrolls, listings should be loaded automatically to give users pleasant and engaging experiences. Below is my code: Got from plugin. That I want to directly insert in osclass script. For the learning purpose. I am trying it on my localhost. Please help to achieve this, any help is highly appreciated. Thanks. <?php $content_block = htmlspecialchars_decode(inf_param('#main')); $listings_parent_block = htmlspecialchars_decode(inf_param('#listing-card-list')); $pagination_block = htmlspecialchars_decode(inf_param('.paginate')); $pagination_next = htmlspecialchars_decode(inf_param('a.searchPaginationNext')); $loaded_listings_count = htmlspecialchars_decode(inf_param('loaded_listings_count')); $report_errors = htmlspecialchars_decode(inf_param('report_errors')); ?> <style> <?php echo $pagination_block; ?> {display:none!important;} .inf-loader {display:none;width:100%;padding:25px 5px;margin:20px 0;background:#eee;border-radius:6px;color:#777;font-size:16px;text-align:center;line-height:20px;} .inf-loader > div {display:inline-block;width:auto;position:relative;padding-left:44px;} .inf-loader img {position:absolute;display:inline-block;top:-6px;left:0;width:32px;height:32px;max-height:32px;max-width:32px;} .inf-loader span {display:inline-block;font-weight:bold;line-height:20px;font-size:14px;} <?php echo $content_block; ?>.loading .inf-loader {display:inline-block;} </style> <script async type="text/javascript"> $(document).ready(function() { var currentPag = 1; var isLoading = false; var pagUrl = ''; var newUrl = ''; var oldUrl = ''; // ADD LOADING BLOCK ABOVE PAGINATION var loadingBlock = '<div class="inf-loader"><div><img src="<?php echo osc_base_url(); ?>oc-content/plugins/infinite/img/loader.gif"/><span><?php echo osc_esc_js(__('Loading items...', 'infinite')); ?></span></div></div>'; $(window).scroll(function(e) { var scroll = $(window).scrollTop(); var threshold = $('<?php echo $content_block; ?>').position().top + $('<?php echo $content_block; ?>').innerHeight() - 100; var position = $(window).scrollTop() + $(window).innerHeight(); if($('<?php echo $pagination_next; ?>').length) { pagUrl = $('<?php echo $pagination_next; ?>').attr('href'); } else { pagUrl = ''; } //console.log(oldUrl + '--->' + pagUrl ); // loading block add above pagination now if(!$('<?php echo $content_block; ?>').find('.inf-loader').length) { $(loadingBlock).insertBefore($('<?php echo $pagination_block; ?>')); } if(!$('<?php echo $content_block; ?>').length || !$('<?php echo $listings_parent_block; ?>').length || !$('<?php echo $pagination_block; ?>').length || !$('<?php echo $pagination_next; ?>').length) { infCheckBlocks(); } else if(position > threshold && isLoading == false && pagUrl != oldUrl && pagUrl != '' && pagUrl != '#') { isLoading = true; $('<?php echo $content_block; ?>').addClass('loading'); $.ajax({ url: pagUrl, type: "GET", success: function(response){ var length = response.length; var data = $(response).contents().find('<?php echo $listings_parent_block ; ?>').html(); var pagBlock = $(response).contents().find('<?php echo $pagination_block; ?>'); var currItemCount = $(response).contents().find('<?php echo $loaded_listings_count; ?>').text(); oldUrl = pagUrl; $('<?php echo $pagination_block; ?>').html(pagBlock); $('<?php echo $listings_parent_block; ?>').append(data); if($('<?php echo $loaded_listings_count; ?>').length) { $('<?php echo $loaded_listings_count; ?>').text(currItemCount); } // lazy load if exists if(typeof $.fn.Lazy !== 'undefined') { $('<?php echo $listings_parent_block; ?>').find('img.lazy').Lazy({ appendScroll: window, scrollDirection: 'both', effect: 'fadeIn', effectTime: 300, afterLoad: function(element) { setTimeout(function() { element.css('transition', '0.2s'); }, 300); } }); } isLoading = false; currentPag = currentPag + 1; $('<?php echo $content_block; ?>').removeClass('loading'); }, error: function(response){ hasPag = false; $('<?php echo $content_block; ?>').removeClass('loading'); response = response.responseText; console.log(response); console.log(data); } }); } }); }); function infCheckBlocks() { <?php if($report_errors == 1) { ?> console.log('<?php echo osc_esc_js(__('Infinite scroll failed to load next items, check message bellow!', 'infinite')); ?>'); if(!$('<?php echo $content_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Content block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $listings_parent_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Listing parent block does not exists, make sure selector is correct. Current selector: %s', 'infinite'), $content_block)); ?>'); } if(!$('<?php echo $pagination_block; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination block does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_block)); ?>'); } if(!$('<?php echo $pagination_next; ?>').length) { console.log('<?php echo osc_esc_js(sprintf(__('Pagination next button does not exists, maybe there are no other pages. Make sure selector is correct. Current selector: %s', 'infinite'), $pagination_next)); ?>'); } <?php } ?> } </script>
  3. Hi Freaks, I've been working on an issue trying to get an infinite scrolling system to work. I originally posted about it here -> I've been trying to debug and figure out the issue as I was pretty sure it was in the jquery/ajax script and not my PHP. The original script I'm using is in the original post linked above bur for reader convenience I'll post it again here -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> the issue that I found is in the if statement condition-> if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { I added some console logs-> .... console.log("This is the scrollHeight: " + document.body.scrollHeight); console.log("This is the scrollTop: " + document.body.scrollTop); console.log(""); console.log("This is scrollTop + innerHeight: " + (document.body.scrollTop + window.innerHeight)); console.log(""); if((document.body.scrollTop + window.innerHeight >= 2500) && noMorePosts == 'false') { $('#loading').show(); console.log('This is fucked up'); // noMorePosts = true; ....... And it turns out that the overflow comments were being displayed but I had to scroll alll the way to the bottom of the page for it to happen. In the above code you can see where I altered the if condition to get the overflow comments to display sooner. This seems like a really bad fix to me as it's such an absolute value (2500) and doesn't take into account so many different variables in user system, setup etc etc. Also, at times it will load the overflow comments more than once. I've seen them repeated up to 3-4 times, which is certainly not acceptable. So I have 2 questions about this issue that I'm really hoping someone can help me resolve: 1) What is a more appropriate fix for the if condition rather than having that hardcoded 2500 in there? 2) What are some ways I can fix the sometimes repetitive overflow comments displaying? As I said in my original post, this jquery/ajax isn't my code and I'm trying to work through it when I get the time, but there is no mechanism in it to make noMorePosts = true and my commented out attempt at it didn't work. To say that I'm really uncomfortable with jquery and ajax would be an understatement. I look forward to reading your responses and hope a great weekend to you all. TIA
  4. So this is kind of a carry on from my last post about while looping, but I felt it was better to start it in a new thread because the framing of the question has changed. For those of you who responded to my last post I thank you and here is the issue and backstory on that post: I'm trying to integrate an AJAX infinite scrolling system into a project. I'm really uncomfortable with AJAX and have watched a few tutorials on it and have tried to integrate what I've learned into my PHP. The one tutorial that made the most sense to me also, obviously uses some PHP but it's kept at a basic level and the PHP of my own that I'm integrating it with is quite a bit more in depth. Before I start with the breakdown, I'd like to make clear that I'm not ignoring anyone's advice on using a foreach over the while loop. The ajax guy is using a while loop in his more simple examples and since I'm so uncomfortable with AJAX I wanted to stay as true to his examples as possible until I got it functioning correctly then I plan on tidying it up. I just want to get it functioning first to where I have a deeper understanding as I'm doing a lot of customization so it fits with my already written code. That being said, I'm going to try to make this post as organized and clear as possible as I really need some help. I have a news_feed.php includes file that looks like this-> <div class="col-sm-12 col-lg-8 ms-3 me-3 column2"> <form action="" method="POST"> <textarea class="form-control" name="post_text" id="text-area" placeholder="Post to your profile" rows="6" autofocus></textarea> <div class="buttons"> <input class="form-group btn btn-outline my-2 button" type="submit" name="submit_post" id="post-button" data-bs-toggle="tooltip" title="Post to your profile" data-bs-html="true" value="Post"> </div> </form> <?php //$post->getUserPosts(); ?> <div class="posts_area"></div> <img src="img/icons/loading.gif" id="loading"> </div> <!-- end newsfeed --> </div> <!-- end inner row --> </div> </div> It's all pretty straight forward. When the $post->getUserPosts() is uncommented all the posts are displayed. It's commented out right now because of the next 2 files. Next I have an ajax_load_posts.php file that looks like this -> <?php require_once($_SERVER["DOCUMENT_ROOT"] . "/qcic/assets/core/init.php"); $user = new User(); $posts = new Post(); $limit = 10; // loaded posts per call // pull userLoggedIn from ajax script $request = $_REQUEST['userLoggedIn']; $posts->getUserPosts($request, $limit); The last line in this file is why I have the $post->getUserPosts() in the previous one commented out. Next I have the following AJAX. None of this is my code and it's the code I'm trying to integrate into my own project -> <script> var userLoggedIn = '<?php echo $user->data()->username; ?>'; $(document).ready(function() { $('#loading').show(); //ajax for loading first posts $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=1&userLoggedIn=" + userLoggedIn, cache: false, success: function(data) { $('#loading').hide(); $('.posts_area').html(data); } }); $(window).scroll(function() { var height = $('.posts_area').height(); //div containing posts var scroll_top = $(this).scrollTop(); var page = $('.posts_area').find('.nextPage').val(); var noMorePosts = $('.posts_area').find('.noMorePosts').val(); if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') { $('#loading').show(); var ajaxReq = $.ajax({ url: "includes/handlers/ajax_load_posts.php", type: "POST", data: "page=" + page + "&userLoggedIn=" + userLoggedIn, cache: false, success: function(response) { $('.posts_area').find('.nextPage').remove(); //removes current next page $('.posts_area').find('.noMorePosts').remove(); //removes current next page $('#loading').hide(); $('.posts_area').append(response); } }); } // end if return false; }); }); </script> Finally I have my getUserPosts() method in my Post class. The majority of this is my code but I've had to make some amendments for this particular task I'm working on. (again, please don't think I'm ignoring anyones advice, I'm not, I will change many things once my understanding is more complete and I get it functioning). -> <?php public function getUserPosts($data, $limit) { // public function getUserPosts() { //$page comes from the $_GET data in ajax script $page = $data['page']; $userLoggedIn = $this->user->username; if($page == 1) { $start = 0; } else { $start = ($page - 1) * $limit; } $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects $str = ""; //html string to return if (count($this->_data) > 0) { $num_iterations = 0; # number of results checked (not necessarily posted) $count = 1; // foreach ($this->data() as $obj) { // $post_data = array( // "id" => $obj->id, // "content" => $obj->content, // "added_by" => $obj->add_by, // "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), // "user_to" => $obj->user_to, // ); $cnt = 0; while($cnt < count($this->data())) { $post_data = array( "id" => $this->data()[$cnt]->id, "content" => $this->data()[$cnt]->content, "added_by" => $this->data()[$cnt]->add_by, "date_added" => date("F d, Y H:i:s", strtotime($this->data()[$cnt]->date_added)), "user_to" => $this->data()[$cnt]->user_to, ); //prepare user string if it's not posted to a user if ($post_data["user_to"] == "none") { $user_to = ""; } else { $user_to_obj = new User($post_data["user_to"]); $user_to_firstname = $user_to_obj->data()->firstname; $user_to_lastname = $user_to_obj->data()->lastname; $user_to = "to <a href='" . $post_data["user_to"] ."'>" . $user_to_firstname . " " . $user_to_lastname . "</a>"; } //check if poster has account closed $added_by_obj = new User($post_data["added_by"]); if ($added_by_obj->isClosed()) { continue; } if($num_iterations++ < $start) { continue; } //load 10 posts and break if($count > $limit) { break; } else { $count++; } //TODO change this for people who use username instead of real names $firstname = $added_by_obj->data()->firstname; $lastname = $added_by_obj->data()->lastname; if ($firstname && $lastname) { $name = $firstname . " " . $lastname; } else { $name = $added_by_obj->data()->username; } $profile_pic = $added_by_obj->data()->profile_pic; //timeframe $datetime_now = date("Y-m-d H:i:s"); $start_date = new DateTime($post_data["date_added"]); //time of post $end_date = new DateTime($datetime_now); // current time $interval = $start_date->diff($end_date); //difference if ($interval->y >= 1) { if ($interval == 1) { $time_message = "1 year ago"; } else { $time_message = $interval->y . " years ago"; } } elseif ($interval->m >= 1) { if ($interval->d == 0) { $days = " ago"; } elseif ($interval->d == 1) { $days = "1 day ago"; } else { $days = $interval->d . " days ago"; } if ($interval->m == 1) { $time_message = "1 month " . $days; } else { $time_message = $interval->m . " months " . $days; } } elseif ($interval->d >= 1) { if ($interval->d == 1) { $time_message = "Yesterday"; } else { $time_message = $interval->d . " days ago"; } } elseif ($interval->h >= 1) { if ($interval->h == 1) { $time_message = "An hour ago"; } else { $time_message = $interval->h . " hours ago"; } } elseif ($interval->i >= 1) { if ($interval->i == 1) { $time_message = "A minute ago"; } else { $time_message = $interval->i . " minutes ago"; } } elseif ($interval->s < 30) { if ($interval->s == 1) { $time_message = "Just now"; } else { $time_message = $interval->s . " seconds ago"; } } $str .= " <div class='status_post'> <div class='post_profile_pic'> <img src='../usernet/img/profile_pics/{$profile_pic}' width='50'> </div> <div class='posted_by'> <a href='{$post_data['added_by']}'> {$name} </a> {$user_to} &nbsp;&nbsp;&nbsp;&nbsp; {$time_message} </div> <div id='post_body'> {$post_data['content']} <br> </div> </div> <hr>"; $cnt++; } if($count > $limit) { //keeping these hidden just to store the values $str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'> <input type='hidden' class='noMorePosts' value='false'>"; } else { $str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align: centre;'> No more posts to show!</p>"; } } echo $str; } The original commented out at the top (with no parameters) is my original and corresponds to the commented out call to this method in the first file I posted. As is, this is not showing the posts only the loading.gif from the first file. I suspect it's not reading the ajax_load_post.php file correctly if at all, as that is where the new call to this method is located. I'm not sure what my actual question is other than "How do I get this working properly?". outside using AJAX for some API calls this is my first foray into using it in a more complex manner. I've tried to keep my code well commented and this post organized so as not to discourage people from responding. I'm pretty lost in the jungle right now and any compass or map any of you could provide would be appreciated. Thank you.
  5. Currently I have a table in my view class that is populated with data from the backend using MVC framework in codeigniter. Now I have a dropdown above each column that is filling in the same records from my database. So I want to be able to filter my records as soon as the person clicks the item in the dropdown list. To achieve this I'm using a Jquery to get the selected item and sending that value to my controller. Code: So far I have this in my view class: <table> <tr> <th width="10%">Source</th> </tr> <tr> <td width="5%"><select id="your_id_name"> <option value="">All </option> <?php if($sources) foreach($sources as $source): ?> <option value="<?php echo $source['title'] ?>"><?php echo $source['title'] ?></option> <?php endforeach;?> </select></td> <td width="10%"><select id="contact_type"> <option value="">All </option> <?php if($types) foreach($types as $type): ?> <option value="<?php echo $type['id'] ?>"><?php echo $type['title'] ?></option> <?php endforeach;?> </select></td> </tr> <tbody> <?php if(isset($records) && count($records) > 0) { foreach($records as $row ){ ?> <tr> <td><?= $row->source ?></td> <td><?= $row->title ?></td> </tr> <?php } } ?> </tbody> <script type="application/javascript"> $('#your_id_name').on('change', function() { console.log($('#your_id_name').val()); $.get('<?php echo base_url('ajax_dropdown'); ?>', { selected: $('#your_id_name').val() }, function(res) { var values = JSON.parse(res); // then do something var status = values.status; var records = values.records; var html = "" records.forEach(function(row){ html += `<tr><td>${row.source}</td> <td>${row.title }</td></tr> `; console.log(tbody_tag) }) var tbody_tag = $('tbody#table_body'); tbody_tag.html(html); }) }) $('#contact_type').on('change', function() { console.log($('#contact_type').val()); $.get('<?php echo base_url('ajax_dropdown'); ?>', { selected_contact: $('#contact_type').val() }, function(res) { var values = JSON.parse(res); // then do something var status = values.status; var records = values.records; var html = "" records.forEach(function(row){ html += `<tr><td>${row.source}</td> <td>${row.title}</td></tr> `; }) var tbody_tag = $('tbody#table_body'); tbody_tag.html(html); }) }) controller class: public function ajax_lists(){ $data = array(); // store data in here, store all data you need in data $selected_input = $this->input->get('selected'); $selected_input2 = $this->input->get('selected_contact'); $data['records'] =$this->contacts_model->get_records($selected_input,$selected_input2); echo json_encode($data); } Model Class: function get_records($selected_input = null,$selected_input2 =null){ $this->db->select("*"); $this->db->from("crm_contacts as con"); if($selected_input){ $this->db->where("con.added_by",$selected_input); } if($selected_input2){ $this->db->where("con.contact_type",$selected_input2); } $query = $this->db->get(); return $query->result(); } Here as of now I can filter all my records 1 at a time. So suppose I filter the table by source and then inside that source I want to filter the leftover data by contact_type, I cannot do it since doing so resets the 1st filter I had and filters all the data according to the new select item I have clicked.
  6. I'm currently passing values in my URL that I want to GET and insert in my controller class for filtering. My current URL looks something like this: http://localhost/reports/lists?source=Product1&status=4. Now to get the value of suppose source, I'm using the following code: let searchParams = new URLSearchParams(window.location.search); var status = searchParams.get('source'); Now I want this status variable to go to my controller class so that I can use it as 1 of my parameters for my model class: Full code: View Class: <?php $postd = json_encode(array_filter($post)); ?> <table id="item-list"> <tr> <th>Ref.No#</th> <th>Source</th> </tr> </table> <script> $(document).ready(function() { function sendreq(){ setpostdatas();cleartable();getleads(); } var userrole = "<?php echo $this->session->userdata('clientrole')?>"; var slug = '<?php echo $slug?>'; var postd = '<?php echo $postd; ?>'; if( userrole > 1 && userrole != 5){ $('#item-list').DataTable({ "processing": true, "stateSave": true, "serverSide": true, "ordering": false, "createdRow": function( row, data, dataIndex){ $(row).has( "div.overdueupdate" ).css('background-color','#FFC7CE'); }, "ajax": { url: "<?php echo site_url(); ?>reports/loadLeads", data: {slug: slug, postdata: postd}, type : 'POST', "dataSrc": function ( d ) { d.myKey = "myValue"; if(d.recordsTotal == 0 || d.data == null){ $("#item-list_info").text("No records found"); $("#item-list_processing").css("display","none"); } return d.data; } }, 'columns': [ {"data": "id", "id": "id"}, {"data": "refno", "refno": "refno"}, {"data": "source", "source": "source"}, ] }); } Controller Class: public function loadLeads($p=''){ $leadsource = $this->input->get('status'); if(isset($_POST['postdata'])){ if($_POST['postdata'] != null && $_POST['postdata'] != 'null'){ $post=$_POST['postdata']; } $post = json_decode($post,true); unset($post['slug']); unset($post['page']); $sort = $post['afsort']; if($sort == "asc"){ $sortQ = 'l.updated_date asc,'; }else if ($sort == "desc"){ $sortQ = 'l.updated_date desc,'; } } $offset = (int)$_POST['start'] ; $pstdatas = explode(',', $_POST['postdata']); unset($pstdatas['item-list_length']); if($this->session->userdata('clientrole') == 1 || $this->session->userdata('clientrole') == 5 ){ $content['leads']=$this->leads_model->get_pagination($_POST['length'],$offset,$where,'',false,$sortQ?$sortQ:'l.assign_status =\'Unassigned\' desc,',$all,$leadsource); }else{ $content['leads']=$this->leads_model->get_pagination($_POST['length'],$offset,$where,'',false,$sortQ?$sortQ:'l.assigned_date desc,',$all,$leadsource); } Now here in my controller class I want that AJAX variable to be passed so that I can use it my model query.
  7. I have a table that shows the redirect from and redirect to columns from my database. By default, all the records are shown, but there is a from and to filter I'm using to search by a particular redirect. Now there are a lot of times that after I input the filters, it gives me a Undefined variable: redirects error, but sometimes it works. Here is my code: View Class: <?php if ($redirects): ?> <form name="redirectform" action="admin/redirects" method="post"> <div> <input list="search-from-list" id="search-from" name="search-from" style="width:100%;"/> <datalist id="search-from-list"> <?php foreach ($allredirects as $allredirect){ ?> <option value="<?php echo $allredirect->from; ?>" id="<?php echo $allredirect->id; ?>" /> <?php } ?> </datalist> </div> <input type="hidden" name="linkid" id="linkid" /> <input type="hidden" name="linkidto" id="linkidto" /> <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>"> </div> <input list="search-to-list" id="search-to" name="search-to" style="width:100%;" /> <datalist id="search-to-list"> <?php foreach ($allredirects as $allredirect){ ?> <option value="<?php echo $allredirect->to; ?>" id="<?php echo $allredirect->id; ?>" /> <?php } ?> </datalist> </div> </form> <table> <?php foreach ($redirects as $redirect): ?> <tr> <td><?php echo $from=str_replace('%', '*', $redirect->from);?></td> <td><?php echo $redirect->to;?></td> </tr> <?php endforeach ?> </table> <?php echo form_close() ?> </div> <?php else: ?> <div class="no_data">No Data</div> <?php endif ?> <script type="text/javascript"> $("#search-from").select(function(e){ var g = $('#search-from').val(); var id = $('#search-from-list').find("option[value='"+g+"']").attr('id'); $('#linkid').val(id); }); $("#search-to").select(function(e){ var g = $('#search-to').val(); var id = $('#search-to-list').find("option[value='"+g+"']").attr('id'); $('#linkidto').val(id); }); </script> Controller Class: public function index() { if(isset($_POST["search-from"]) && !empty($_POST["search-from"])){ if(isset($_POST["linkid"]) && !empty($_POST["linkid"])){ $from_id = $_POST["linkid"]; $this->template->redirects = $this->redirect_m->order_by('`from`')->get_by_id($from_id); } }else if(isset($_POST["search-to"]) && !empty($_POST["search-to"])){ if(isset($_POST["linkidto"]) && !empty($_POST["linkidto"])){ $to_id = $_POST["linkidto"]; $this->template->redirects = $this->redirect_m->order_by('`to`')->get_by_id($to_id); } }else{ $this->template->redirects = $this->redirect_m->order_by('`from`')->limit($this->template->pagination['limit'], $this->template->pagination['offset'])->get_all(); } $this->template->allredirects = $this->redirect_m->order_by('`from`')->get_all(); $this->template->build('admin/index'); } Here basically what I'm doing is that the input with the ids search-from and search-to hold an autocomplete function for the redirect links. I have other 2 input fields linkid and linkidto which are hidden. Now I did some debugging and found out that the reason for my error is because the AJAX call is taking too long. Basically what the ajax call does is convert whatever text that is there in the input field of search-from and fetches the id for that from the database and then returns the value according to that id. So I changed the hidden fields to text and manually inserted the ids for the search fields I entered and it worked everytime. So now what I think the problem is that the AJAX call is taking too long to convert the selected options to their respective ids and this ends up giving me an error. So maybe what I want here is a delay timer to the page until the AJAX call has been made?
  8. I have here a select query where in I have to get the $den_name and $currDate from a js variable. $disData="SELECT bDate.* FROM (SELECT bDentist.* FROM ( SELECT bBranch.*,concat(px_fname,' ', px_lname) as px_name, concat(px_contact,' / ', px_contact2) as px_connum FROM appointments bBranch WHERE bBranch.brnch_id = '$id') AS bDentist WHERE bDentist.den_name = '$dentistName') AS bDate WHERE bDate.s_date = '$currDate'"; The reason for doing this is so that I can output the records when I clicked a specific date and dentist #1 that matches their values. I tried using ajax here is my code for trying to get the dentist's name // JS Var currDen to PHP Var const den1 = document.querySelector('.D1'); const den2 = document.querySelector('.D2'); const den3 = document.querySelector('.D3'); let currDen = ''; // if 'active' exists if( den1.classList.contains('active')) { currDen = document.getElementById("D1").innerHTML; }else if (den2.classList.contains('active')){ currDen = document.getElementById("D2").innerHTML; }else if (den3.classList.contains('active')){ currDen = document.getElementById("D3").innerHTML; }else{ currDen = '땡!'; }; console.log(currDen); const xhrDen = new XMLHttpRequest(); jsonStr = JSON.stringify(currDen); console.log (jsonStr); xhrDen.open("POST" , "clickedD.php"); xhrDen.setRequestHeader("Content-type" , "application/json"); xhrDen.send(jsonStr); }); }); this is the clickedD.php where I post it <?php $requestPayload= file_get_contents("php://input"); var_dump($requestPayload); $dentistName = json_decode($requestPayload,true); var_dump($dentistName); echo $dentistName; and in does return this to the network dev tool I also tried checking it if its empty with this if (empty($requestPayload)) { echo "Variable is empty.<br>"; } else { echo $requestPayload; } if (empty($dentistName)) { echo "Variable is empty.<br>"; } and this is what it output what is wrong with my code ? please help me out
  9. What I'm hoping to do is , when an <a> tag is click it will send a text value to php to change whatever name is assigned on the $table variable. To give an example. On the side are all the branches this clinic has. Instead of creating new php file for each of the branch ( with the same design and functionality) and href it accordingly, once click it will send a text to replace the default value of $table. I think AJAX will help do the trick but I'm new to it. Please help me, I'm so lost. Below is my code that displays all the branch, and what it looks like. <div class="BNavcontainer" > <div id="branchnav" class="SideBNav"> <?php /* To display Branch Name from djams_db */ $brnch = $conn->query("SELECT * FROM branches") or die($conn->error); while($row=$brnch->fetch_assoc()): ?> <a data-id='<?php echo $row['brnch_id'] ?>' href="djams_rmc.php?<?php echo $row['brnch_name'] ?>" id="b<?php echo ($row['brnch_id']) +1 ?>" > <?php echo ($row['brnch_name']) ?> </a> <?php endwhile; ?> </div> </div>
  10. I have a php page tool.php that has a function named "create_event". I want to make a button in a different page (dashboard.php), that when I click on it, it runs the "create_event" function from tool.php and shows the output from the function on dashboard.php page. I'm totally new to ajax and jquery and not sure how to do this. I did google this but not much luck. My site is build with WordPress and this is part of custom plugin that I'm making. Thank you in advance.
  11. I have an index.php file which includes my form and code to move the user's uploaded file to s3. My HTML form calls a js function sendEmails() which makes an AJAX request to another php script dbSystem() to validate the emails input and add it to a database. Everything is working except that the php code in my index.php file (at the very bottom) does not execute. It's supposed to execute when the user uploads a file and presses submit but it doesn't go into the if statement. I tried putting the $fileName = basename($_FILES["fileName"]["name"]) statement before the if statement but I get an undefined index error. I put my a comment in my code to show which if statement I am talking about. This is my HTML code in index.php: <form action="javascript:void(0)" method="POST" id="files" enctype="multipart/form-data"> <label class="col-md-4 col-form-label text-md-right">Select File: <span class="text-danger">*</span></label> <input type="file" id="userFile" name="fileName" style="cursor: pointer; max-width: 170px;" onchange="enableBtn()"> <label class="col-md-4 col-form-label text-md-right">Authorized Users: <span class="text-danger">*</span></label> <input placeholder="Enter e-mail(s) here..." id="req" autocomplete="off"/> <button id="submitBtn" name="submitBtn" class="<?php echo SUBMIT_BUTTON_STYLE; ?>" onclick="return sendEmails()" disabled>Submit</button> </form> This is my php code in index.php: <?php $conn = new mysqli($servername, $username, $password, $db); $sql = "SELECT sender_id, sender_email, receiver_emails, receiver_ids, file_name from filedrop_logs"; $result = mysqli_query($conn, $sql); if ($result) { echo "<div class='outputDiv'>"; echo "<table id='sharedOthers'>"; echo "<thead><tr class='headings'>"; echo "<th class='files'>Files</th>"; echo "<th class='users'>Users</th>"; echo "</tr></thead>"; while ($row = mysqli_fetch_assoc($result)) { $receiverEmails = $row['receiver_emails']; $fileName = $row['file_name']; echo "<tbody id='bodyOthers'>"; echo "<tr id='rowOthers'>"; echo "<td>$fileName<br>"; $objects = getListofObjects('FileDrop'); foreach ($objects as $object) { $file = $object['Key']; $splits = explode('/', $file); if (end($splits) !== '') { $presignedUrl = getPresignedUrlForPrivateFile($object['Key'], '+20 minutes'); $link = '<a href="'.$presignedUrl.'">Download</a>'; echo $link; } } echo "&nbsp;&nbsp;&nbsp;&nbsp;<a href=''>Delete</a></td>"; echo "<td>$receiverEmails</td>"; echo "</tr></tbody>"; } echo "</table></div>"; } ?> <?php //the if statement below doesn't execute if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES["fileName"])) { $fileName = basename($_FILES["fileName"]["name"]); $error = $_FILES["fileName"]["error"]; $tmpName = $_FILES["fileName"]["tmp_name"]; if (isset(fileName) && $fileName != '' && $tmpName != '' && sys_get_temp_dir()) { $separator = DIRECTORY_SEPARATOR; $newDir = sys_get_temp_dir() . $separator . "FileDrop" . microtime(true); if (!file_exists($newDir)) { mkdir($newDir, 0777, true); // creates temp FileDrop directory $tempFilePath = $newDir . $separator . $fileName; // creates temp file inside FileDrop directory if (move_uploaded_file($tmpName, $tempFilePath)) { // moves file to tmp folder $s3FileName = "FileDrop" . substr($newDir, 4) . $separator . $fileName; $result = putFileToS3($s3FileName, $tempFilePath, 'public-read'); deleteDir($newDir); } } } } ?> This is my js code in case you want to see it: function sendEmails() { var fileData = $('#userFile').prop('files')[0]; var formData = new FormData(); formData.append('tags', JSON.stringify(tags)); formData.append('fileName', fileData); $.ajax({ type: "POST", url: "../FileDrop/dbSystem.php", processData: false, contentType: false, data: formData, success: function(result) { result = JSON.parse(result); if (result.validity === "valid emails") { location.reload(); resetInputs(); //IMPORTANT $(".outputDiv").show(); } else { var tagsBrackets = result.emails.toString().replace(/[\[\]']+/g,''); var tagsQuotes = tagsBrackets.replace(/['"]+/g, ''); var tagsInvalid = tagsQuotes.replace(/,/g, ", "); $('#alertModal').modal({show:true}); document.getElementById('invalid').textContent = tagsInvalid; } } }); return false; } I've been stuck on this for so long, so I'd really appreciate the help!!
  12. It give an the link like http://localhost/aps/undefined Object not found! The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.35 (Win32) OpenSSL/1.1.0i PHP/7.2.11 //The php code to fetch data //The php code to fetch data <?php include('db.php'); $query = ''; $output = array(); $query .= "SELECT * FROM users "; if(isset($_POST["search"]["value"])) { $query .= 'WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" '; $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" '; } if(isset($_POST["order"])) { $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' '; } else { $query .= 'ORDER BY id DESC '; } if($_POST["length"] != -1) { $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length']; } $statement = $connection->prepare($query); $statement->execute(); $result = $statement->fetchAll(); $data = array(); $filtered_rows = $statement->rowCount(); foreach($result as $row) { $sub_array = array(); $sub_array[] = $row["first_name"]; $sub_array[] = $row["last_name"]; $sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>'; $sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>'; $data[] = $sub_array; } $output = array( "draw" => intval($_POST["draw"]), "recordsTotal" => $filtered_rows, "recordsFiltered" => get_total_all_records(), "data" => $data ); echo json_encode($output); ?> //javasrcipt jquery var dataTable = $('#user_data').DataTable({ "processing":true, "serverSide":true, "order":[], "ajax":{ url:"fetch.php", type:"POST" }, "columnDefs":[ { "targets":[0, 3, 4], "orderable":false, }, ] });
  13. Hi all, Bit of a dilema. If I add, update items through the Modal form, all works well. But, if I delete an item, everything works fine, but the window stays greyed out. Even if I check a checkbox and delete that way it works fine. The Delete part of the Ajax: $(document).on("click", ".delete", function() { var id=$(this).attr("data-id"); $('#id_d').val(id); }); $(document).on("click", "#delete", function() { $.ajax({ url: "includes/save.php", type: "POST", cache: false, data:{ type:3, id: $("#id_d").val() }, success: function(dataResult){ $('#deleteDriverModal').modal('hide'); $("#"+dataResult).remove(); } }); }); Here is the Multiple Delete section: $(document).on("click", "#delete_multiple", function() { var user = []; $(".user_checkbox:checked").each(function() { user.push($(this).data('user-id')); }); if(user.length <=0) { alert("Please select records."); } else { WRN_PROFILE_DELETE = "Are you sure you want to delete "+(user.length>1?"these":"this")+" row?"; var checked = confirm(WRN_PROFILE_DELETE); if(checked === true) { var selected_values = user.join(","); console.log(selected_values); $.ajax({ type: "POST", url: "includes/save.php", cache:false, data:{ type: 4, id : selected_values }, success: function(response) { var ids = response.split(","); for (var i=0; i < ids.length; i++ ) { $("#"+ids[i]).remove(); } } }); } } }); $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); var checkbox = $('table tbody input[type="checkbox"]'); $("#selectAll").click(function(){ if(this.checked){ checkbox.each(function(){ this.checked = true; }); } else{ checkbox.each(function(){ this.checked = false; }); } }); checkbox.click(function(){ if(!this.checked){ $("#selectAll").prop("checked", false); } }); }); If anyone could help that would be great.
  14. //my controller <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class homeController extends Controller { public function index() { $employee = DB::table('employee')->orderBy('id','desc')->get(); $department = DB::table('department')->orderBy('id','desc')->get(); return view('index', ['employee' => $employee , 'department' => $department]); } } //my routes Route::get('index','homeController@index'); //my view using blade temmplating engine @foreach($employee as $emp) <div class="employee"> <b>{{ $emp->name }} </b> <a href="employee/{{ $emp->id }}"> <p class="intro">{{ substr($emp->intro ,0, 50) }}...</p> </a> </div> @endforeach @foreach($department as $dep) <div class="department"> <b>{{ $dep->name }} </b> <a href="department/{{ $dep->id }}"> <p class="desc">{{ substr($dep->description ,0, 100) }}...</p> </a> </div> @endforeach I want to fetch using ajax, how can i do it, teach/help me
  15. Hi, I have a form for news articles. It has a title and a body which is fine. I also have a search box that allows the user to search for a memeber and click their name when it appears. This moves a div with a data-id into another div. The purpose of this is to tag them in the article. I am able to post all of the simple stuff but how would i post these value. I am assuming that i would need to create an array of said values but i am struggling to get them showing in post at all. Here is the code i have so far <?php function searchForPeople($searchVal, $exclude = '0'){ $sv1 = $searchVal; $sv2 = $searchVal; include 'includes/dbconn.php'; $out =""; $stmt = $conn -> prepare(" SELECT fname, lname, id FROM person WHERE id NOT IN (".implode(',', array_map('intval', $exclude)).") AND (fname LIKE CONCAT('%',?,'%') OR lname LIKE CONCAT('%',?,'%')) "); $stmt -> bind_param('ss', $sv1, $sv2); $stmt -> execute(); $stmt -> bind_result($fn, $ln, $pid); while($stmt -> fetch()){ $out .= "<div class='btn btn-primary m-1 tagInArticle' name='taggedPerson[]' data-id='$pid'>$fn $ln</div>"; } return $out; } ?> ...... <div id="searchResultsHere"> <!-- ajax content here --> </div> <hr> <div id="taggedInArticleContainer"> <!-- ajax content here --> </div> ....... <div class="col-lg-2"> <button type="submit" name="PublishNewNews" class="btn btn-primary w-100 mb-3">Publish</button> <button class="btn btn-primary w-100">Save</button> <hr> <div class="btn btn-warning w-100 mb-3">Private</div> <input type="hidden" name="howVisible" value="Private"> <hr> <p class="text-justify">Private news articles will only be avilable to logged in users</p> </div> ....... <script> $('#searchResultsHere').on('click', '.tagInArticle', function tagInArticle(){ var tagButton = $(this); tagButton.appendTo('#taggedInArticleContainer') }); $('#searchForPeopleBox').keyup(function(){ var searchVal = $(this).val() var tagged = '0' var tagged = $('#taggedInArticleContainer').find('.tagInArticle').map(function(){ return $(this).data('id'); }).get(); $.ajax({ type: 'post', data: {"ajax" : 'one', "val" : searchVal, "exclude" : tagged}, success: function(resp){ $('#searchResultsHere').html(resp) } }) }); </script> I hope this is enough to go on. I am sure it is simple but i just cant get it. Thanks all in advance.
  16. Background: I'm comparing 2 styles of Ajax: 1.) "jquery style" 2.) "ActiveXObject Microsoft.XMLHTTP style" Question: Is one better (faster, more cross-browser compliant) than the other? My experience: Both seem equally fast. The Microsoft style is a bit longer, but I don't have to load jquery.js to my page! Code Examples: Jquery style on my PHP page: function getInfo(ProductNumber){ $.ajax({ url:'Ajax-PHP-Page.php?ProductNumber='+ProductNumber, success: function(html) { document.getElementById("my_div").value = ''; document.getElementById("my_div").value = html; } }); } Microsoft style on my PHP page: function getInfo(ProductNumber) { 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("my_div").value = this.responseText; } }; xmlhttp.open("GET","Ajax-PHP-Page.php?ProductNumber="+ProductNumber,true); xmlhttp.send(); } Thank you!!
  17. HI all, I am building a php application and i am wanting to use notifications. At the moment i am just wanting to understand the methodology behind this. I dont necessarily have a use case for these notifications yet but i am going to base it off of the following: A user submits something to the database, another user gets a notifications that this has happened. I see the notifications being something appearing in the header bar (saying "you have a notification"...) I know that i will need to use ajax for this and JS/JQ but i am not really sure where to start with this. I have done some research and have come up a little blank. My main question at the moment is how does the submission of data to the database trigger the notification? As always and help here is appreciated. Kind Regards Adam
  18. I have created a registration page to access my website. After the user registrate himself should appear an alert saying that the registration was OK and a redirect to main.php page... however for some reason if I create an insert statement the alert and the redirect don't appear... If I remove the insert the alert and the redirect works... why? This is part of the code of my 3 files: registration.php (ajax call) $('#submit').click(function() { var username2 = $('#uname2').val(); var password2 = $('#psw2').val(); $.ajax({ url: 'ajax/response.php', type: 'GET', data: {username2 : username2, password2: password2}, success: function(data) { if(data === 'correct') { alert("Username and Password have been created!"); //don' work with the insert location.replace("main.php"); //don' work with the insert } else { alert("Username or password are not correct... please register yourself!"); } } }); }); response.php (answer to ajax call) if(isset($_GET['username2']) && isset($_GET['password2'])) { $username2 = $_GET['username2']; $password2 = $_GET['password2']; if (checkUser($pdo, $username2) === true) { echo 'duplicate'; } else { insertUserPwd($pdo, $username2, $password2); //including this line the redirect and the alert doesn't work... the insert is OK echo 'correct'; } } data_access.php (the function works but doesn't permit alert and redirect to appear) function insertUserPwd(PDO $pdo, $usr, $pwd) { $data = [ 'id' => '', 'user' => $usr, 'password' => $pwd ]; $sql = "INSERT INTO users (id, user, password) VALUES (:id, :user, :password)"; $stmt= $pdo->prepare($sql); $stmt->execute($data); } Can someone help me to fix the code?
  19. i've to populate google charts with dynamic data. the data looks llike. +----+-------+---------+-------+-----------+---------+------+ | id | name | physics | maths | chemistry | biology | sst | +----+-------+---------+-------+-----------+---------+------+ | 1 | Name1 | 10 | 25 | 35 | 42 | 62 | | 2 | Name2 | 80 | 45 | 45 | 45 | 25 | | 3 | Name3 | 63 | 25 | 63 | 36 | 36 | | 4 | Name4 | 82 | 36 | 75 | 48 | 42 | | 5 | Name5 | 45 | 45 | 78 | 25 | 24 | | 6 | Name6 | 36 | 36 | 15 | 75 | 36 | | 7 | Name7 | 99 | 45 | 24 | 24 | 45 | | 8 | Name8 | 45 | 85 | 85 | 85 | 96 | +----+-------+---------+-------+-----------+---------+------+ i have to create google charts based on this such that # namewise - such that when i select a name it displays all subject marks of that particular name in a column chart #markswise - when i select a subject, it displays all the names with marks in that particular subject. conisdiering that data may be added and i've to accumulate that also, for namewise i did // chart.php <?php include("connection.php"); $query = "SELECT name FROM csv GROUP BY name DESC"; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); ?> <!DOCTYPE html> <html> <head> <title>Google charts</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> </head> <body> <br /><br /> <div class="container"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-md-9"> <h3 class="panel-title">Student Wise Marks Data</h3> </div> <div class="col-md-3"> <select name="name" class="form-control" id="name"> <option value="">Select Student</option> <?php foreach($result as $row) { echo '<option value="'.$row["name"].'">'.$row["name"].'</option>'; } ?> </select> </div> </div> </div> <div class="panel-body"> <div id="chart_area" style="width: 1000px; height: 620px;"></div> </div> </div> </div> </body> </html> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'bar']}); google.charts.setOnLoadCallback(); function load_student_data(name, title) { var temp_title = title + ' '+name+''; $.ajax({ url:"fetch.php", method:"POST", data:{name:name}, dataType:"JSON", success:function(data) { drawStudentwiseChart(data, temp_title); } }); } function drawStudentwiseChart(chart_data, chart_main_title) { var jsonData = chart_data; var data = new google.visualization.DataTable(); data.addColumn('number', 'Physics'); data.addColumn('number', 'Maths'); data.addColumn('number', 'Chemistry'); data.addColumn('number', 'Biology'); data.addColumn('number', 'SST'); $.each(jsonData, function(i, jsonData){ var Physics = jsonData.Physics; var Maths = jsonData.Maths; var Chemistry = jsonData.Chemistry; var Biology = jsonData.Biology; var SST = jsonData.SST; data.addRows([[Physics,Maths,Chemistry,Biology,SST]]); }); var options = { title:chart_main_title, hAxis: { title: "Subjects" }, vAxis: { title: 'Percentage' } }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_area')); chart.draw(data, options); } </script> <script> $(document).ready(function(){ $('#name').change(function(){ var name = $(this).val(); if(name != '') { load_student_data(name, 'Student wise marks data'); } }); }); </script> and in order to fetch data // fetch.php <?php //fetch.php include('connection.php'); if(isset($_POST["name"])) { $query = " SELECT * FROM csv WHERE name = '".$_POST["name"]."' ORDER BY id ASC "; $statement = $connect->prepare($query); $statement->execute(); $result = $statement->fetchAll(); foreach($result as $row) { $output[] = array( 'Physics' => $row["Physics"], 'Maths' => $row["Maths"], 'Chemistry' => $row["Chemistry"], 'Biology' => $row["Biology"], 'SST' => $row["SST"], ); } echo json_encode($output); } ?> it diplays a blank page. however when i play with singular values i.e one subject at a time it displays fine
  20. i was working on a mini project that imports csv file to the database through ajax and it's working fine <?php if(!empty($_FILES["marks_file"]["name"])) { $connect = mysqli_connect("localhost", "root", "", "dbname"); $output = ''; $allowed_ext = array("csv"); $extension = end(explode(".", $_FILES["marks_file"]["name"])); if(in_array($extension, $allowed_ext)) { $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r'); fgetcsv($file_data); while($row = fgetcsv($file_data)) { $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } $select = "SELECT * FROM csv ORDER BY id DESC"; $result = mysqli_query($connect, $select); $output .= ' <table class="table table-bordered"> <tr> <th width="25%" >name</th> <th width="15%" >Physics</th> <th width="15%" >Maths</th> <th width="15%" >Chemistry</th> <th width="15%" >Biology</th> <th width="15%" >SST</th> </tr> '; while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["Physics"].'</td> <td>'.$row["Maths"].'</td> <td>'.$row["Chemistry"].'</td> <td>'.$row["Biology"].'</td> <td>'.$row["SST"].'</td> </tr> '; } $output .= '</table>'; echo $output; } else { echo 'errorx'; } } else { echo "errory"; } ?> however the imported csv files inserts null values in the tables because the format of all csv files assigned to me are in the exact same format: ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 i changed my code a bit modified the functions to espace blank spaces and not return null values in the data tables while (($row = fgetcsv($file_data, 1000, ",")) !== FALSE) { if ((string) $row[0] != '0' and empty($row[0])) { continue; } $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } But it doesn't work with the specified csv files i think the ajax call breaks and that's why nothing happens.However it works fine with csv files without blank spaces
  21. I've been following this tutorial on how to use ajax I have to admit I'm new at it. I could use jquery but I hate it. I would like to know if someone can help me figure out why my code is reading Uncaught TypeError: Cannot set property 'onreadystatechange' of undefined. when I fire off the Friend request button or block button. ? <?php error_reporting(E_ALL); ini_set('display_errors', '1'); include_once('includes/check_login_status.php');?> <?php $u = ""; $profile_pic = ""; $profile_pic_btn = ""; $avatar_form = ""; $avatar = ""; $date_added = ""; $joindate = ""; $lastsession = ""; // Make sure the _GET username is set, and sanitize it if(isset($_GET["u"])){ $u = preg_replace('#[^a-z0-9_]#i', '', $_GET['u']); }else { header("location: register.php"); exit(); } $notactive = ""; $sql = "SELECT * FROM register WHERE username='$u' AND activated='1' LIMIT 1"; $user_query = mysqli_query($db_conx, $sql); $numrows = mysqli_num_rows($user_query); if($numrows < 1){ $notactive.= " <br/> <span style='color:red;'>That user does not exist or is not yet activated press back</span> <br/>"; } // Check to see if the viewer is the account owner $isOwner = "no"; if($u == $log_username && $user_ok == true){ $isOwner = "yes"; $profile_pic_btn = '<a href="#" onclick="return false;" onmousedown="toggleElement(\'avatar_form\')">Toggle Avatar Form</a>'; $avatar_form = '<form id="avatar_form" enctype="multipart/form-data" method="post" action="php_parsers/photo_system.php">'; $avatar_form .= '<h4>Change your avatar</h4>'; $avatar_form .= '<input type="file" name="avatar" required>'; $avatar_form .= '<p><input type="submit" value="Upload"></p>'; $avatar_form .= '</form>'; } // Fetch the user row from the query above while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) { $profile_id = $row["id"]; $avatar = $row["avatar"]; $lastlogin = $row["lastlogin"]; $date_added = $row["date_added"]; $joindate = strftime("%b %d, %Y", strtotime($date_added)); $lastsession = strftime("%b %d, %Y", strtotime($lastlogin)); } $profile_pic = '<img src="user/'.$u.'/'.$avatar.'" alt="'.$u.'">'; if($avatar == NULL){ $profile_pic = '<img src="images/765-default-avatar.png" alt="'.$u.'">'; } ?> <?php $isFriend = false; $ownerBlockViewer = false; $viewerBlockOwner = false; if($u != $log_username && $user_ok == true){ $friend_check = "SELECT id FROM friends WHERE user1='$log_username' AND user2='$u' AND accepted='1' OR user1='$u' AND user2='$log_username' AND accepted='1' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $friend_check)) > 0){ $isFriend = true; } $block_check1 = "SELECT id FROM blockedusers WHERE blocker='$u' AND blockee='$log_username' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check1)) > 0){ $ownerBlockViewer = true; } $block_check2 = "SELECT id FROM blockedusers WHERE blocker='$log_username' AND blockee='$u' LIMIT 1"; if(mysqli_num_rows(mysqli_query($db_conx, $block_check2)) > 0){ $viewerBlockOwner = true; } } ?> <?php $friend_button = '<button disabled>Request As Friend</button>'; $block_button = '<button disabled>Block User</button>'; // LOGIC FOR FRIEND BUTTON if($isFriend == true){ $friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>'; } else if($user_ok == true && $u != $log_username && $ownerBlockViewer == false){ $friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>'; } // LOGIC FOR BLOCK BUTTON if($viewerBlockOwner == true){ $block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>'; } else if($user_ok == true && $u != $log_username){ $block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>'; } ?> <?php $friendsHTML = ''; $friends_view_all_link = ''; $sql = "SELECT COUNT(id) FROM friends WHERE user1='$u' AND accepted='1' OR user2='$u' AND accepted='1'"; $query = mysqli_query($db_conx, $sql); $query_count = mysqli_fetch_row($query); $friend_count = $query_count[0]; if($friend_count < 1){ $friendsHTML = $u." has no friends yet"; } else { $max = 18; $all_friends = array(); $sql = "SELECT user1 FROM friends WHERE user2='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user1"]); } $sql = "SELECT user2 FROM friends WHERE user1='$u' AND accepted='1' ORDER BY RAND() LIMIT $max"; $query = mysqli_query($db_conx, $sql); while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { array_push($all_friends, $row["user2"]); } $friendArrayCount = count($all_friends); if($friendArrayCount > $max){ array_splice($all_friends, $max); } if($friend_count > $max){ $friends_view_all_link = '<a href="view_friends.php?u='.$u.'">view all</a>'; } $orLogic = ''; foreach($all_friends as $key => $user){ $orLogic .= "username='$user' OR "; } $orLogic = chop($orLogic, "OR "); $sql = "SELECT username, avatar FROM register WHERE $orLogic"; $query = mysqli_query($db_conx, $sql); while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) { $friend_username = $row["username"]; $friend_avatar = $row["avatar"]; if($friend_avatar != ""){ $friend_pic = 'user/'.$friend_username.'/'.$friend_avatar.''; } else { $friend_pic = 'images/765-default-avatar.png'; } $friendsHTML .= '<a href="index.php?u='.$friend_username.'"><img class="friendpics" src="'.$friend_pic.'" alt="'.$friend_username.'" title="'.$friend_username.'"></a>'; } } ?> <?php $coverpic = ""; $sql = "SELECT filename FROM photos WHERE user='$u' ORDER BY RAND() LIMIT 1"; $query = mysqli_query($db_conx, $sql); if(mysqli_num_rows($query) > 0){ $row = mysqli_fetch_row($query); $filename = $row[0]; $coverpic = '<img src="user/'.$u.'/'.$filename.'" alt="pic">'; } ?> <!DOCTYPE html> <html> <head> <script type="application/javascript"> function _(x){ return document.getElementById(x); } function ajaxObj (meth, url){ var x = new XMLHttpRequest(); x.open(meth, url, true); x.setRequestHeader("Content-type", "application/x-www-form-urlendcoded"); } function ajaxReturn(x){ if(x.readyState == 4 && x.status == 200){ return true; } } function friendToggle(type,user,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $u; ?>."); if(conf != true){ return false; } _(elem).innerHTML = '<img src="images/bullet-svg-animated.gif" width="50" height="50">'; var ajax = ajaxObj("POST", "php_parsers/friend_system.php"); ajax.onreadystatechange = function(){ if(ajaxReturn(ajax) == true) { if(ajax.responseText.trim() == "friend_request_sent"){ _(elem).innerHTML = 'OK Friend Request Sent'; } else if(ajax.responseText.trim() == "unfriend_ok"){ _(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>'; } else { alert(ajax.responseText.trim()); _(elem).innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&user="+user); } function blockToggle(type,blockee,elem){ var conf = confirm("Press OK to confirm the '"+type+"' action on user <?php echo $u; ?>."); if(conf != true){ return false; } var elem = document.getElementById(elem); elem.innerHTML = '<img src="images/bullet-svg-animated.gif" width="50" height="50">'; var ajax = ajaxObj("POST", "php_parsers/block_system.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText.trim() == "blocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'unblock\',\'<?php echo $u; ?>\',\'blockBtn\')">Unblock User</button>'; } else if(ajax.responseText.trim() == "unblocked_ok"){ elem.innerHTML = '<button onclick="blockToggle(\'block\',\'<?php echo $u; ?>\',\'blockBtn\')">Block User</button>'; } else { alert(ajax.responseText.trim()); elem.innerHTML = 'Try again later'; } } } ajax.send("type="+type+"&blockee="+blockee); } </script> <title><?php echo $u; ?></title> <link rel="stylesheet" type="text/css" href="css/style.css" /> </head> <style type="text/css"> div#profile_pic_box{float:right; border:#999 2px solid; width:200px; height:200px; margin:20px 30px 0px 0px; overflow-y:hidden;} div#profile_pic_box > img{z-index:2000; width:200px;} div#profile_pic_box > a { display: none; position:absolute; margin:140px 0px 0px 120px; z-index:4000; background:#D8F08E; border:#81A332 1px solid; border-radius:3px; padding:5px; font-size:12px; text-decoration:none; color:#60750B; } div#profile_pic_box > form{ display:none; position:absolute; z-index:3000; padding:10px; opacity:.8; background:#F0FEC2; width:180px; height:180px; } div#profile_pic_box:hover a { display: block; } div#photo_showcase{float:right; background:url(css/photo_showcase_bg.jpg) no-repeat; width:136px; height:127px; margin:20px 30px 0px 0px; cursor:pointer;} div#photo_showcase > img{width:74px; height:74px; margin:37px 0px 0px 9px;} img.friendpics{border:#000 1px solid; width:40px; height:40px; margin:2px;} </style> <style type="text/css"> textarea#statustext{width:982px; height:80px; padding:8px; border:#999 1px solid; font-size:16px;} div.status_boxes{padding:12px; line-height:1.5em;} div.status_boxes > div{padding:8px; border:#99C20C 1px solid; background: #F4FDDF;} div.status_boxes > div > b{font-size:12px;} div.status_boxes > button{padding:5px; font-size:12px;} textarea.replytext{width:98%; height:40px; padding:1%; border:#999 1px solid;} div.reply_boxes{padding:12px; border:#999 1px solid; background:#F5F5F5;} div.reply_boxes > div > b{font-size:12px;} </style> <body> <div class="header"> <h2>Home</h2> <?php include_once('dynamic_header.php');?> </div> <div class="content"> <?php if (isset($_SESSION['success'])): ?> <div class="error success"> <h3> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?> </h3> </div> <?php endif ?> <p>Welcome <strong><?php echo $u; ?> </strong></p> <?php echo $notactive ?> <div id="profile_pic_box" ><?php echo $profile_pic_btn; ?><?php echo $avatar_form; ?><?php echo $profile_pic; ?></div> <div id="photo_showcase" onclick="window.location = 'photos.php?u=<?php echo $u; ?>';" title="view <?php echo $u; ?>'s photo galleries"> <?php echo $coverpic; ?> </div> <br> <p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p> <p>Join Date: <?php echo $date_added; ?></p> <p>Last Session: <?php echo $lastsession; ?></p> <br /> <?php $member_list =''; if(isset($_GET["u"])){ $u = preg_replace('#[^a-z]#i','',$_GET['u']); $sql = mysqli_query($db_conx,"SELECT * FROM register"); while($row = mysqli_fetch_array($sql)){ $u = $row['username']; $member_list .=' <a href="user.php?u='.$u.'">'.$u.'</a> '; } } ?> <?php echo $member_list ?> <br /> <br /> <hr /> <p>Friend Button: <span id="friendBtn"><?php echo $friend_button; ?></span> <?php echo $u." has ".$friend_count." friends"; ?> <?php echo $friends_view_all_link; ?></p> <p>Block Button: <span id="blockBtn"><?php echo $block_button; ?></span></p> <hr /> <p><?php echo $friendsHTML; ?></p> <hr /> </div> </body> </html>
  22. i'm trying to make a notification tab work but do not seem to get it right. The dropdown is working fine but the ajax call to newfriends.php is not working right, when viewed with firebug there are no results to be seen in the dropdown.Quite confusing. (note the dropdown menu is located in header and can only be displayed if the session is initialised) here is the ajax used in jquery: function load_notifications(view=''){ $.ajax({ url: "notification/new_friends.php", method: "POST", data:{view:"view"}, dataType:"json", success: function(data){ $(".dropdown-menu").html(data.notification); if(data.unseen_notification>0){ $(".badge1").html(data.unseen_notification); } } }); //$(".dynamic-notification").load("notification/pm_n.php"); // $(".dynamic-notification-f").load("notification/new_friends.php"); }; load_notifications(); $(document).on("click",".count_friend", function(){ load_notifications('yes'); }); //loads every 2 seconds for chat setInterval(function(){load_notifications();},2000); here is the new_friends.php content: <?php include '../includes/dbconfig.inc.php'; if (isset($_POST['view'])) { if($_POST['view'] !=''){ $update="update friends set count='1' where friend_one=:session and count='0'"; $stmt=$conn->prepare($update); $stmt->bindValue(":session", $_SESSION['uname']); $stmt->execute(); } $sql123="select id from friends where friend_two=:sess_uname and count='0'"; $stmt123=$conn->prepare($sql123); $stmt123->bindValue(":sess_uname", $_SESSION['uname']); $stmt123->execute(); $request_count=$stmt123->fetchColumn(); //$count_friend=$stmt123->rowCount(); /*$sql_f_count="select *from user where user_id=:session_id and activated='1' limit 1"; $stmt_f_count=$conn->prepare($sql_f_count); $stmt_f_count->bindValue(":session_id", $_SESSION['id']); $stmt_f_count->execute(); $user_details=$stmt_f_count->fetchAll(); $friend_badge=$user_details[0]['friend_count_badge'];*/ require "notification/friend_request_notification.php"; // $new_friends="<span class='dropdown'><a href='#' data-placement='bottom' class='btn dropdown-toggle' data-toggle='dropdown' title='Friend Requests' data-html='true'><span class='count_friend' style=' height:33px; width:30px;'><span class='badge1 label label-pill'>".$count."</span><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span></a><ul class='dropdown-menu'></ul></span>"; //if($request_count[0]>0){ //$new_friends="<a href='#' data-placement='bottom' class='btn' data-trigger='focus' title='Friend Requests' data-toggle='popover' data-html='true' data-content='".$friend_requests."'><span class='count_friend' style=' height:33px; width:30px;'><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span><span class='badge'>".$friend_badge."</span></a>"; /*}else{ $new_friends="<a href='all_notifications.php'><img src='img/logo/group-button-black.png' style='height:25px; width:27px;' alt='new_friends_alert'></a>"; }*/ //echo $new_friends; //} $data=array( 'notification'=>$friend_requests, 'unseen_notification' =>$request_count[0][0] ); and the code for friend requests output: <?php //error_reporting(0); require_once 'includes/dbconfig.inc.php'; $sql = "select * from friends where friend_two=:session and accepted='0' order by friends_date_made asc"; $stmt = $conn->prepare($sql); $stmt->bindparam(":session", $_SESSION['uname']); $stmt->execute(); $numrows = $stmt->fetchAll(PDO::FETCH_ASSOC); $friend_requests=""; if ($numrows < 1) { $friend_requests = "You do not have any friend requests"; echo "$friend_requests"; exit(); } else { foreach ($numrows as $i=>$row1 ) { $reqid = $row1['friend_id']; $user1 = $row1['friend_one']; $datemade = $row1['friends_date_made']; $datemade1 = strftime("%B %d, %y", strtotime($datemade)); $sql = "SELECT * FROM user WHERE uname=:user1 LIMIT 1"; $stmt = $conn->prepare($sql); $stmt->bindparam(":user1", $user1); $stmt->execute(); $thumbrow = $stmt->fetchAll(PDO::FETCH_ASSOC); $user1avatar = $thumbrow[$i]['avatar']; $user1id=$thumbrow[$i]['user_id']; if ($user1avatar =="") { $user1pic = '<img src="img/avatardefault.png" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">'; } else { $user1pic = '<img src="../user/user/'.$user1id.'/'.$user1avatar.'" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">'; } $friend_requests .= '<li><div id="'.$reqid.'" float="right" class="friendrequests"> <a href="home.php?u='.$user1.'">'. $user1pic .'</a> <div class="user_info '.$reqid.'" id="'.$reqid.'"><small>' . $datemade1 . '</small> <a href="home.php?u='.$user1.'">'.$user1.'</a> is requesting your friendship<br /><br /> <button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="accept_btn btn btn-warning">Accept</button><span class="show-spinner"></span> or <button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="reject_btn btn btn-warning">Reject</button> </div> </div><hr></li>'; } }
  23. I have made an ajax call (using file activedirectory.php) to active directory to retrieve information such as name,thumbnail photo,mail etc. the ajax call is made on click of a name in a leaderboard ,to fetch only that person's info by matching the post['id']. The problem is that I am unable to retrieve any information and the console gives me an error saying : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data the error type makes it clear that it is unable to pull any data whatsoever. .php file that has been used here :(activedirectory.php) -- <?php /** * Get a list of users from Active Directory. */ $ad_users = ''; $message = ''; $ldap_password = 'Qwerty@33xxxxxx'; $ldap_username = 'maxxxxxxxxxxxx'; $server = 'ldap://xxxxxxxxxx'; $domain = '@asia.xxxxxx.com'; $port = 389; $ldap_connection = ldap_connect($server, $port); if (FALSE === $ldap_connection){ // Uh-oh, something is wrong... } // We have to set this option for the version of Active Directory we are using. ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version'); ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search. if (TRUE === ldap_bind($ldap_connection, $ldap_username.$domain, $ldap_password)){ $base_dn = "OU=Employees,OU=Accounts,OU=xxxxx,DC=xxxxx,DC=xxxxxx,DC=com"; $kid = 'NonExistingAccount'; if (preg_match('#SAM_NAME_MATCHING_REGEX#', $_POST['id'])) { $kid = $_POST['id']; } $search_filter = "(&(objectCategory=person)(samaccountname={$kid}))"; $attributes = array(); $attributes[] = 'givenname'; $attributes[] = 'mail'; $attributes[] = 'samaccountname'; $attributes[] = 'sn'; $result = ldap_search($ldap_connection, $base_dn, $search_filter, $attributes); $maxPageSize = 1000; if (FALSE !== $result){ $entries = ldap_get_entries($ldap_connection, $result); for ($x=0; $x<$entries['count']; $x++){ if (!empty($entries[$x]['givenname'][0]) && !empty($entries[$x]['mail'][0]) && !empty($entries[$x]['samaccountname'][0]) && !empty($entries[$x]['sn'][0]) && 'Shop' !== $entries[$x]['sn'][0] && 'Account' !== $entries[$x]['sn'][0]){ $ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0])); } } } ldap_unbind($ldap_connection); // Clean up after ourselves. } $message .= "Retrieved ". count($ad_users) ." Active Directory users\n"; ?> the javascript that has been used here : $('.leaderboard li').on('click', function () { $.ajax({ url: "../popupData/activedirectory.php", // your script above a little adjusted type: "POST", data: {id:$(this).find('.parent-div').data('id')}, success: function(data){ console.log(data); data = JSON.parse(data); $('#popup').fadeIn(); //whatever you want to fetch ...... // etc .. }, error: function(){ alert('failed, possible script does not exist'); } }); });
  24. Hi there, I was trying to do a live table edit for our site. Everything seemed to be going ok, till i realised that its not actually updating the database, there are no error messages, you have to refresh the page to see it hasn't worked. I'm at a loss as to why was hoping someone might be able to point me in the right direction. thanks, MsKazza tableedit.php table_edit_ajax.php
  25. I've wrote code for sending array to another php file with mysql, everything works, but but i can't add CHANGE function to my code, to make code react on changes (checked/uchecked checkbox) <div id="checkboxes"> <input id="chkbx_0" type="checkbox" name="first" checked="checked" />Option 1 <input id="chkbx_1" type="checkbox" name=second" />Option 2 <input id="chkbx_2" type="checkbox" name="third" />Option 3 <input id="chkbx_3" type="checkbox" name="fourth" checked="checked" />Option 4 </div> <script> $(document).ready(function () { // var name = []; $('#checkboxes input:checked').each(function() { name.push($(this).attr('name')); }).get(); // $.post('load.php', {name:name[1]}, function(data){ $('#name-data').html(data); }); // }); </script>
×
×
  • 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.