jquery ajax php recordset caching - php

I currently have a jQuery/ajax request which produces a recordset which appears in #contentDiv on my page. The user can then browse the results and view further details of an item. Once on the page for the item it the user hits back on their browser they return to the default page for my search without their generated search results.
The current jQuery code is:
$j.ajax({
type: 'POST',
url: '/availability/search',
dataType: 'html',
data: data,
success: function(data) {
$j('#col2AvailabilityContent').html(data);
}
});
Is it possible to pass the content of the results generated and passed to #colAvailabilityContent to a cache and draw these out when the back button is used.
Thanks

Yes. The trick is to change your hash location.
For example, let's say your site is http://simnom.com/index.php.
Once your results appear, change your URL to simnom.com/index.php#x, then to index.php#results
Then, when the user hits back button, it will just go to index.php#x.
You can use the javascript:
if(location.hash == '#x') {
$("#col2Availability").html(availabilitycontent);
}
And then keep $j.ajax()'s "data" stored as a global var "availabilitycontent".

Related

Progress bar displaying processed data percentage

I am working on a PHP application that has a template, functions,api structure and I am facing the following problem:
In a tpl I have a html form through which the user may upload a bunch of data. I take the data an send them over to the functions file to process them and then display the results to the user. What I want to achieve is a progress bar that displays the percentage of the processed data to the user through a bootstrap modal and progress bar.
When I submit the form through the html way the page starts to load immediately
thus I cannot update the modal data (trying to do it with a query call from the functions file).
When I do it the query post way because the processing is asynchronous not only the modal is not being updated but when the next page loads the session is not updated either.
Is there an other way around to do this? The only way I have made the progress bar is through the xhr way but this is done in the tpl layer and does not represent the actual data processed.
Thank you in advance.
Bind this function to your button instead of using the submit method, and then you can dynamically rebuild your progress bar with the information contained in the response.
function build_progress_bar() {
var SendInfo= { "info":stuff };
$.ajax({
type: 'POST',
url: 'https://yoursite.com/your_php_script.php',
data: SendInfo,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
traditional: true,
success: function (data) {
data = JSON.parse(data);
var html = buildProgressBar(data);
function buildProgressBar(info) {
// Build your Progress bar HTML here
return progressBar;
}
document.getElementById("YOUR_PROGRESS_BAR_CONTAINER").innerHTML = html;
}
});
}
Note: You will need jQuery included to use aJax.

Php like counter

I want to create 'like' counter.
Currently I use ajax with php and on button click in like.php I update count in database and echo back count number to jquery.
$('btn').on('click',function(){
$.ajax({
url: 'like.php',
type: 'post',
data: someData,
dataType: 'json',
}).done(function(response){
//increase like shown on response
}).fail(function(jqXHR, textStatus, errorThrown) {
});
});
This would be triggering likes from client side.
I would like to do this on server side instead, so on button click to call php file:
Example (I put this in my page):
like
And then in like.php update count in database as above.
2 questions:
is it possible for url not to change when I click this?
how would I echo back like count from like.php this way? (because I dont use ajax to call like.php like in first example)
to your first question: simply no!
But you could make it a submit button and do post to the same url wich wouldn't change the url and you can push data through submit...
to your second question -> your like.php has to return the whole html with your counter-value ;)
cheerio :)

Using JQuery to refresh an HTML form (located on a PHP page)

I'd like to update a form, more exactly I wish to display an extra scroll menu, depending on the user's choice in a first scroll menu.
I have a page, mypage.php page on which there is a form. Here it is :
<form method="post" action="wedontcare.php" enctype="multipart/form-data">
<label for="base">3 - Select a DB </label><br />
<?php
include 'functions.php';
offers_choice_DB();
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
I have a separated file "functions.php" where are declared all the functions I use here. offers_choice_DB() displays a scroll menu where I can select a database (actually, this function performs a MySQL query and echoes the result in a scroll menu). If the user selects a database, then $_POST['base_name_choice'] exists. And it does, because when i only work with PHP/HTML, all is doing fine.
My purpose is to allow the user to select a database, then for this database I'd like to display a second scroll menu that displays some tables from this DB. This scroll menu will only be displayed if a POST value has been set. The offers_choice_table($_POST['base_name_choice']) function takes this value as an argument, then echoes the HTML for the scroll menu, containing the tables. Here we are !
Oh, and the submit button is not important here, because I want to have my second scroll menu displayed before the user clicks on the submit button, so we just disregard the target page, ok ?
Before, everything was OK : I used tests, conditions (isset...) but it was not dynamic, I had to call other pages, ...etc. And now I want, as you guessed, to use jQuery to refresh mypage.php as soon as the user selects a database so that an extra menu appears.
I started to listen to a change in my scroll menu, but then I don't know what to do to refresh my page with a POST parameter containing the selected database. Anyway, here is my code :
<script type="text/javascript">
$( '#base_name_choice' ).change(function() {
var val = $(this).val(); //here I retrieve the DB name
alert( val ); //I notify myself to check the value : it works
$.ajax({
type: 'POST', //I could have chosen $.post...
data: 'base_name_choice='+val, //I try to set the value properly
datatype: 'html', //we handle HTML, isn't it ?
success: function(){
alert( "call ok" ); //displays if the call is made
//and here...???? I don't know whatto do
}
})
});
</script>
Here it is...any help will be appreciated ! Thanks :)
Regards
The issue here is that your page is rendered first (html + php preprocessing). That means that once your page is rendered, you won't be able to make direct php method calls such as offers_choice_table or change the $_POST parameters.
How you normally do this, is by making an AJAX call from your javascript to a PHP script/method which than generates the second menu based on the parameter that the user chose.
So, you don't need this part:
if (isset($_POST['base_name_choice'])){
offers_choice_table($_POST['base_name_choice']);
}
because you will call "offers_choice_table" method with an ajax call.
You make the ajax call to a url which will return the second menu
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data){
alert( "call ok" ); //displays if the call is made
// here you can append the data that is returned from your php script which generates the second menu
$('form').append(data);
}
})
You should use GET instead of POST, in your new PHP file:
if (isset($_GET['base_name_choice'])) {
offers_choice_table($_GET['base_name_choice']);
}
You SHOULD check if the variable has a value set, especially if your function is expecting one. You can use whatever functions you want in this file, it is like any other PHP file you would write. Include any files that you want.
You should make sure to avoid SQL injection when using a GET or POST value in a query: How can I prevent SQL injection in PHP?
In the .ajax() call, there is a callback function success, this runs if the server response is good (i.e. not a 404 or 500). There first parameter in that function is what the server returned. In your case, it would be the HTML you echoed out. You can use jQuery to append the response to an element:
$.ajax({
type: "GET",
url: "generate_second_menu.php",
data: { base_name_choice: val},
success: function(data) {
// it looks like you're only returning the options of the select, so we'll build out the select and add them
var $newSelect = $('<select></select>');
$newSelect.append(data);
// and then add the select to the form (you may want to make this selector for specific)
$('form').append($newSelect);
}
});

Get Ajax Previous Request with Browser Back Button

I’m facing a situation with Ajax request on back button.
I created a form which posts values and returns results via ajax request according the given filters and loads on a specific div. When I click on any of the link on page, it opens the new url as expected. On clicking on browser back button it opens the previous form page with default values. How can I enable browser state functionality so that I have results with last posted values with browser back button. Note that type of ajax is POST.
One solution I got is that to modify this form type to GET instead of POST, but this would take much time to do changes in server side code.
var page_url = $(this).attr('href');
page_url = page_url.split(':');
var page = page_url['1'];
$form = $('#form);
$.ajax({
type: 'POST',
data: $form.serialize(),
url: webroot + 'controller /action/page:'+page
}).done(function (result){
})
I want to know the possible solution.
You should set cache to false:
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (json) {...}
});
Source https://stackoverflow.com/a/25230377
you can use Jquery .unload() function or try cookies you could read it from here How do I set/unset cookie with jQuery?
Once you submitting that time dont go for new page, just hide the form elements and display new content in other div. Once you click on back button just show previously hidden div and hide current showing div

Update php generated content without page refresh

I've created a php function (called "category_page" in "category-page.php") which reads data from a file into an associative array and then generates some html to display the information on products.php (the page calling the "category_page" function)
My aim is to allow the user to select from a drop down in order to sort the displayed information without refreshing the page.
I have so far managed to achieve this using document.formname.submit on change of the dropdown and then using $_GET to choose which key in the array to sort by, however, this causes the page to reload.
I have a little knowledge of php, javascript/jquery and have done a fair bit of searching/reading on AJAX to enable an update without refresh/reload, but can't seem to put all the pieces together.
So, in products.php, I have the following javascript/jquery:
function sort_products() {
queryString = "?sort_list="+$("#sort_list").val();
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
}
$("#sort_list").on("change", function() { sort_products() });
and then in category-page.php:
if(isset($_GET['sort_list'])) {
$sort = $_GET['sort_list'];
}
else {
// set default sort order
}
I've verified in Chrome's network panel that a request for category-page.php?sort_list=price is being sent, but the page isn't updating. Any help would be appreciated!
Change this line of code:
$("#sort_list").on("change", function(e) { sort_products(); e.preventDefault(); e.stopPropagation(); });
Once the query is sent, you need to make something with what is returned.
$.ajax({
type: 'GET',
url: 'category-page.php',
data: 'sort_list='+queryString
})
.done(function(data) {
// if your php code returns the html you can make something like this
// the var data will be the html code
$('#your-container').html(data)
})

Categories