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. I am retrieving data via Ajax into Choices.js select options My scenario is when I select date, getting the available restaurant tables The retrieving data is 100% working, but it reflects in the select options only in the first request, then when I try to reselect another date I receive the below console error, and choices still keep the initial retrieved data choices.min.js:11 Trying to initialise Choices on element already initialised Choices setValue Function var el = document.getElementsByClassName("table_number")[0]; if (el) { function setChoices(values) { const tableNumbers = new Choices(el, { removeItemButton: true, }).setValue(values); } setChoices(values); } Ajax Code let shiftDate = document.getElementById('reservation_shift_date'); shiftDate.addEventListener("change", function(){ let request = new XMLHttpRequest(); request.open("POST","get_tables.php",true); request.setRequestHeader("content-type","application/x-www-form-urlencoded"); request.onreadystatechange = function(){ if(request.readyState == 4 && request.status == 200){ setChoices(JSON.parse(request.responseText)); } } request.send("date="+shiftDate.value); }); get_tables.php if($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['date'])){ $stmt = $conn->prepare("SELECT table_id FROM reservation WHERE shift_date = ?"); $stmt->execute([$_POST['date']]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach($rows as $row){ $reserved_tables_id[] = $row['table_id']; } $in = implode(',',$reserved_tables_id); $execute_query = mysqli_query($dbConnection,"SELECT id, table_name FROM tables WHERE id NOT IN ($in)"); while($row = mysqli_fetch_assoc($execute_query)){ $tbl_id = $row['id']; $tbl_name = $row['table_name']; $arr[] = ["value"=>$tbl_id,"label"=>$tbl_name]; } echo json_encode($arr); }
  2. 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
  3. 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.
  4. 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.
  5. 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.
  6. 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?
  7. 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
  8. 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>
  9. 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.
  10. 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!!
  11. 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, }, ] });
  12. 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.
  13. //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
  14. 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.
  15. 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!!
  16. 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
  17. 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>'; } }
  18. 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'); } }); });
  19. 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
  20. 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>
  21. 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" .
  22. 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.
  23. 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
  24. Here's what I'm trying to do. I retrieve results using php foreach loop. Within that loop results, I want to show a div(.show-details) on mouse over only. How do I do that? This is my code so far. <style> .show-details { display: none; } </style> $get_records = $db->prepare("SELECT * FROM records WHERE record_id = :record_id"); $get_records->bindParam(':record_id', $record_id); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0){ foreach($result_records as $row) { $get_record_title = $row['record_title']; $get_record_details = $row['record_details']; $get_record_price = $row['record_price']; ?> <div class="product"> <div class="product-title"> <?php echo $get_record_title; ?> </div> <div class="product-price"> <?php echo $get_record_price; ?> </div> </div> <div class="show-details"> <?php echo $get_record_details; ?> </div> <?php } } else { echo 'no results.'; } <script> $(document).ready(function() { $(".product").mouseover(function(){ $(".show-details").css("display", "block"); }); }); </script>
  25. Basically I have a very long form select option drop down list. What I would like to do is that for each option "value", I want to remove the spaces and instead add dash to it. Doing each option value by hand would take me a very long time, so I thought I might try jquery for short cut. If you have another method, let me know. Here's what I have so far. Doesn't seem to work. <script> $(document).ready(function () { $('#model').change(function(){ var str = $(this).val(); str = str.replace(/\s+/g, "-"); }); }); </script> // here's an example of select options <select id="model" name="model"> <option value="john doe" >John Doe</option> <option value="john smith lu" >John Smith Lu</option> </select>
×
×
  • 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.