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'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>'; } }
  20. 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'); } }); });
  21. 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
  22. 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>
  23. Hello I've been trying to fix this problem for around 3 weeks; so what I want is to be able to send a picture and being able to display it in another page. It send it to the server, but still it doesn't show it. Here is my code: <?php require_once('../Connections/connection.php'); ?> <?php $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "add_post")) { $tiempocotejo= time(); $insertSQL = sprintf("INSERT INTO posts (titulo, categoria, tag, imagen, contenido, descripcion, estatus, plantilla,link, price, autor) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['titulo'], "text"), GetSQLValueString($_POST['categoria'], "text"), GetSQLValueString($_POST['tag'], "text"), GetSQLValueString($_POST['imagen'], "text"), GetSQLValueString($_POST['contenido'], "text"), GetSQLValueString($_POST['descripcion'], "text"), GetSQLValueString($_POST['estatus'], "int"), GetSQLValueString($_POST['plantilla'], "int"), GetSQLValueString($_POST['link'], "text"), GetSQLValueString($_POST['price'], "text"), GetSQLValueString($_SESSION['MM_Id'], "int")); mysql_select_db($database_connection, $connection); $Result1 = mysql_query($insertSQL, $connection) or die(mysql_error()); mysql_select_db($database_connection, $connection); $query_SacarIdPost = sprintf("SELECT posts.id FROM posts WHERE time=%s",$tiempocotejo,"int"); $SacarIdPost = mysql_query($query_SacarIdPost, $connection) or die(mysql_error()); $row_SacarIdPost = mysql_fetch_assoc($SacarIdPost); $totalRows_SacarIdPost = mysql_num_rows($SacarIdPost); mysql_free_result($SacarIdPost); $updateSQL = sprintf("UPDATE posts SET urlamigable= %s WHERE id=%s", GetSQLValueString(limpia_espacios($_POST['titulo'],$row_SacarIdPost['id']), "text"), GetSQLValueString($row_SacarIdPost['id'], "int")); mysql_select_db($database_connection, $connection); $Result1 = mysql_query($updateSQL, $connection) or die(mysql_error()); $insertGoTo = "publishedpost" . UrlAmigablesInvertida($row_SacarIdPost['id']).".php"; header(sprintf("Location: %s", $insertGoTo)); } ?> <style> #select{ padding-left:0px; } #select2{ padding-right:0px; } </style> <!DOCTYPE html> <html lang="en"> <?php include("includes/head.php"); ?> <!-- Preloader --> <div id="preloader"> <div id="status"> </div> </div> <body> <div id="sb-site"> <!-- header-full --> <div class="boxed"> <?php include ("../includes/header.php");?> <?php include("../includes/menu.php");?> </div> <!-- header-full --> <header class="main-header" style="background-color:#f1f1f1;"></header> <!-- container --> <div class="container"> <div class="row"> <!-- Sidebard menu --> <?php include ("../includes/adminsidebar.php"); ?> <!-- Sidebar menu --> <!--Container --> <div class="col-md-9"> <form role="form" action="<?php echo $editFormAction; ?>" name="add_post" method="POST"> <!-- Title --> <div class="form-group"> <label>Title</label> <input type="text" class="form-control" name="titulo" placeholder="Enter title"> </div> <!-- Title --> <!-- upload image --> <div class="form-group"> <input class='file' type="file" class="form-control" name="imagen" onClick="gestionimagen.php" id="images" placeholder="Please choose your image"> </div> <!-- Upload Image --> <div class="form-group"> <label> Description </label><br> <textarea class="" name="descripcion" style="width:100%"></textarea> </div> <!-- Text editors --> <div class="form-group"> <label> Contenido </label> <textarea class="ckeditor" name="contenido"></textarea> </div> <!-- Text editor --> <!-- Category --> <div class="form-group"> <label>Categoria</label> <input type="text" class="form-control" name="categoria" placeholder="Enter categoria"> </div> <div class="form-group"> <label>Tag</label> <input type="text" class="form-control" name="tag" placeholder="Enter tag"> </div> <!-- Category --> <!-- Visibilidad --> <div class="col-md-6" id="select"> <div class="form-group"> <label for="select">Visible</label> <select class="form-control" id="estatus" name="estatus"> <option value="1">Si</option> <option value="0">No</option> </select> </div> </div> <!-- Visibilidad --> <!-- Tiplo de Plantilla necesito trabajar en esto!!!!! pero ya!!!--> <script> function plantilla(){ var formData = new FormData($("#formUpload")[0]); $.ajax({ type: 'POST', url: 'plantillapost.php', data: formData, contentType: false, processData: false }); } </script> <div class="col-md-6" id="select2"> <div class="form-group"> <label for="select">Plantilla</label> <select class="form-control" id="plantilla" name="plantilla"> <option value="1" <?php if (!(strcmp(1, ""))) {echo "SELECTED";} ?>>Normal</option> <option value="2" onClick="plantilla" <?php if (!(strcmp(2, ""))) {echo "SELECTED";} ?>>Full-Width</option> </select> </div> </div> <!-- Tipo de Plantilla --> <div class="col-md-6" id="select"> <div class="form-group"> <label>Link</label> <input type="text" class="form-control" name="link" placeholder="Enter link"> </div> </div> <div class="col-md-6" id="select2"> <div class="form-group"> <label>Price</label> <input type="text" class="form-control" name="price" placeholder="Enter price"> </div> </div> <button type="submit" class="btn btn-ar btn-primary pull-right">Agregar</button> <input type="hidden" name="MM_insert" value="add_post"> </form> </div> <!-- Container --> </div> </div> <!-- container --> <?php include("../includes/footer.php");?> </div> <!-- boxed --> </div> <!-- sb-site --> <?php include("../includes/menuderecha.php");?> <!-- sb-slidebar sb-right --> <?php include("../includes/back-to-top.php");?> <!-- Scripts --> <!-- Compiled in vendors.js --> <!-- <script src="js/jquery.min.js"></script> <script src="js/jquery.cookie.js"></script> <script src="js/imagesloaded.pkgd.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/bootstrap-switch.min.js"></script> <script src="js/wow.min.js"></script> <script src="js/slidebars.min.js"></script> <script src="js/jquery.bxslider.min.js"></script> <script src="js/holder.js"></script> <script src="js/buttons.js"></script> <script src="js/jquery.mixitup.min.js"></script> <script src="js/circles.min.js"></script> <script src="js/masonry.pkgd.min.js"></script> <script src="js/jquery.matchHeight-min.js"></script> --> <script src="<?php echo $urlWeb ?>js/vendors.js"></script> <!--<script type="text/javascript" src="js/jquery.themepunch.tools.min.js?rev=5.0"></script> <script type="text/javascript" src="js/jquery.themepunch.revolution.min.js?rev=5.0"></script>--> <!-- Syntaxhighlighter --> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shCore.js"></script> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shBrushXml.js"></script> <script src="<?php echo $urlWeb ?>js/syntaxhighlighter/shBrushJScript.js"></script> <script src="<?php echo $urlWeb ?>js/DropdownHover.js"></script> <script src="<?php echo $urlWeb ?>js/app.js"></script> <script src="<?php echo $urlWeb ?>js/holder.js"></script> <script src="<?php echo $urlWeb ?>js/home_profile.js"></script> <script src="<?php echo $urlWeb ?>js/efectos.js"></script> </body> </html> But Im still not able to display it, si I tried to do a tutorial that I saw on Internet and it made do another php file, that why I put on the input an action="gestionimagen.php" otherwise I would have never done, here is my code for gestionimagen.php: NOTE: I had to create another table on my server called images, but I would like to be able to do it in my table called posts as I have in the code above. <?php require_once '../Connections/connection.php'; $data = array(); if( isset( $_POST['image_upload'] ) && !empty( $_FILES['imagen'] )){ $image = $_FILES['imagen']; $allowedExts = array("gif", "jpeg", "jpg", "png"); if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } //create directory if not exists if (!file_exists('imagen')) { mkdir('imagen', 0777, true); } $image_name = $image['name']; //get image extension $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION)); //assign unique name to image $name = time().'.'.$ext; //$name = $image_name; //image size calcuation in KB $image_size = $image["size"] / 1024; $image_flag = true; //max image size $max_size = 512; if( in_array($ext, $allowedExts) && $image_size < $max_size ){ $image_flag = true; } else { $image_flag = false; $data['error'] = 'Maybe '.$image_name. ' exceeds max '.$max_size.' KB size or incorrect file extension'; } if( $image["error"] > 0 ){ $image_flag = false; $data['error'] = ''; $data['error'].= '<br/> '.$image_name.' Image contains error - Error Code : '.$image["error"]; } if($image_flag){ move_uploaded_file($image["tmp_name"], "../images/post".$name); $src = "../images/post".$name; $dist = "../images/post/thumbnail_".$name; $data['success'] = $thumbnail = 'thumbnail_'.$name; thumbnail($src, $dist, 200); $sql="INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } } mysqli_close($con); echo json_encode($data); } else { $data[] = 'No Image Selected..'; } ?> So I don't know if did properly explain myself, but thats what I want, send the picture to my server into my table called posts, otherwise can you help me how to properly adapt it to the new table called "images" .
  24. his is my code for a simple catalog store (no cart and checkout), a listing page that will change the items depending on the category (or subcategory). This is my db structure: prod_id Primary bigint(20) AUTO_INCREMENT user_id int(11) cat_id int(11) subcat_id int(11) prod_titulo varchar(250) prod_descripcion varchar(250) The file that is currently listing all the products (store.php) has this script: $(document).ready(function(){ $('#listing_store').empty(); $.ajax({ url: 'store-app/db_query.php', type: 'GET', dataType: 'json', //data: , success: function(data){ for (var i = 0; i < data.length; i++) { var dataHtml = '' + '<div class="col-xs-6 col-md-4 column productbox">' + '<a href="detail.php#' + + data[i].id +'">' + '</a>' + '<div class="product-info">' + ' <div class="product-title"><a href="detalle_producto.php#' + + data[i].id +'">' + data[i].titulo + '</a></div>' + '<div class="product-price">' + '<div class="pull-right"><a href="detalle_producto.php#' + + data[i].id +'" class="btn btn-info btn-sm" role="button">Ver</a></div>' + '<div class="pricetext">$'+ data[i].precio + '</div></div>' + '</div>' + '</div>' $('#listing_store').append(dataHtml); } } }); }); As a result i have the product listed in the listing page. the anchor link for the products to the detail page (detail.php): <a href="detail.php#' + + data[i].id +'"></a> This is the script i have in the detail.php page: $(document).ready(function() { if(window.location.hash){ var id = window.location.hash.substring(1); $('#title').html('cargando...'); $('#desc').html('cargando...'); } LoadProduct(id); }); function LoadProduct(id){ $.ajax({ url: 'store-app/db_query.php', type: 'POST', dataType: 'json', data: { "q": id, }, }).done(function(aviso){ var id = aviso.id; $('#title').html(aviso.titulo); $('#desc').html(aviso.descripcion); }); } }); The product loads ok but the url is mysite/detail.php#1 -> prod_id Finally, the db query file (db_query.php): $sql = mysqli_query($dbc, "SELECT * FROM tienda_prod WHERE prod_activo ='1' ORDER BY prod_fechacreado DESC"); $results = array(); while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){ $results[] = array( 'id' => $row["prod_id"], // or smth like $row["video_title"] for title 'user' => $row["user_id"], 'categoria' => $row["cat_id"], 'subcategoria' => $row["subcat_id"], 'titulo' => $row["prod_titulo"], 'descripcion' => $row["prod_descripcion"], ); } header('Content-Type: application/json'); if (isset($_REQUEST["q"])) { $busqueda = $_REQUEST["q"]; $clave = array_search( $busqueda , array_column($results, 'id') ); echo json_encode( $results[ $clave ] ); } else { echo json_encode( $results ); } What can i do to change product url's to be more friendly/clean: mystore.com/detail.php#1 to mystore.com/(category or subcategory name)/(product title + id) Ex. mystore.com/electric-guitars/fender-telecaster-1 Aclaration: I have other two tables in the db for subcategories and categorias, both with id and name, the product table has both category and subcategory id.
  25. Hi, I have been reading up on ajax using jquery, and theres something I can't seem to find, i have a form that gets the field values from mysql when the page loads, what is the best way to use ajax to edit this form? Obv the ajax request will execute the mysql update statement but how do i get the edited data back into the form, ready to be worked with again. thanks, hope i made sense, just looking for a little direction. MsKazza
×
×
  • 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.