I have following dropdown which calls javascript showTable method.
<select name="any_name" id="any_id" onChange="showTable()">
I have following showTable method which calls a php method via post to populate data in my showData div.
function showTable()
{
$.ajax({
type: "POST",
url: "sample.php",
data: {"Id" : myId},
success: function (data)
{
document.getElementById("showData").innerHTML= data;
}
});
}
It works fine. Now the problem arises when I hit FORWARD and then BACKWARD browser button. On hitting BACKWARD button, I get my previous page but my showData div is empty. How can I retain data in this div which I got from my PHP script? I think I have made it clear what I want to ask.
Look for local storage w3schools.com/html/html5_webstorage.asp and manage to save and retreive values between your back/forward behavior.
;)
Related
I am using window.history.pushState() to change the url of the page and put it in the history list, everything works but I have a problem, if for example in a page I execute an operation (ajax), which changes the values in the db and textually update a part of the page, if I browse elsewhere and return to this page, I find what was originally there and not the changes made, to see them correctly I have to refresh the page.
I don't currently use any caching systems
Some contents are loaded with ajax others are directly on the page
window.history.pushState() is used only in the home page in the others I don't need it even if it happens on all
in the example page I have this code
function init() {
$('#weekDays').on('show.bs.modal', function(event) {
var modal = $(this);
$.ajax({
type: 'post',
cache: false,
url: '/my_account/get_giorni_chiusura_sett',
dataType: 'html'
}).done(function(data) {
modal.find('.modal-content').html(data);
});
});
$('body').on('click', '#save-closing-days', function() {
var dataString = $('#form-weekdays-close').serialize();
$.ajax({
type: 'post',
cache: false,
url: '/my_account/set_giorni_chiusura_sett',
data: dataString,
dataType: 'json'
}).done(function(data) {
if (data.update === 'ok') {
var daysClose = $.map(data.giorni, function(v) {
return '<strong>' + v + '</strong>';
}).join(' - ');
$('#list-days-close').html(daysClose);
$('#weekDays').modal('hide');
}
});
});
}
when I arrive in the page the content is loaded without ajax and generated by php, the first function loads the content in the modal upon opening, the second one saves / updates the data on the database and updates the text on the DOM
Closing days: Saturday - Sunday
Update and become
Closing days: Sunday
Now I move to other pages from the menu and back, but I find it again:
Saturday - Sunday
If I reload the page, the data is updated
The History API doesn't maintain the state of the DOM for you. You need to do that yourself. MDN has a good guide but the short version is:
When the user clicks a link then your JS should prevent the default behaviour and call pushState to change the URL and use DOM methods to update the page to match what the server would send for that URL.
When the user presses the back button in their browser and a popstate event fires then your JS should read the URL (and state data if applicable) from the event and using DOM methods to update the page to match what the server would send for that URL (i.e. undoing the changes from the previous paragraph).
This is my first time attempting filtering and searching the mySQL database. From my research I have found out I need an AJAX call and some PHP query that will help my achieve the filtering I want to achieve.
This is what I want the AJAX search to do:
Have an Apply button. When I click the button I want a URL to get generated and the AJAX call to happen.
Only reload part of the page where the data queried is contented.
So far I have managed to create this:
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(data){
$('#data-holder').html(data);
}
});
});
This manages to create the URL one of the filters, but it does not take the other filters into consideration. I also did not manage to create the button. I am guessing you would need a where statement in the PHP to filter the database?
Would anyone be willing to assist me in creating the AJAX call and PHP query for the filters?
In total I have three filters, and when I click a button I want an AJAX call to filter my database with the three filters and return the results without having to reload the whole webpage.
EDIT: Here is my JS AJAX query:
$("#apply").click(function() {
$country=$('#filter-country').val();
$type=$('#filter-type').val();
$year=$('#filter-year').val();
$.ajax({
type: "GET",
url: "{{$launchsitename->site_code}}",
data: {'country':$country, 'type':$type, 'year':$year},
success: function(data) {
$('#data-holder').append(data);
}
});
});
Now I just need to create a PHP query.
you can use propriety called .Append() instead of .html() ,also here you are getting one element value on change , if you want to get the three of them at one button click , you can make it the same way that you got the val of the first one , and just adding it to the request and handle it back in PHP to divide and execute each one or just pass the three of them to your procedure , depends on what you have
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(response){
$('#data-holder').append(response);
}
});
});
Read about .append()
I want to get 3 values from a web service by providing current URL and current user. My webservice accepts 2 parameter URL and user. Web service works fine.
Now I want to put this 3 values in 3 different textboxes using jquery.in txtOrgCity = city, in txtPin = pin, in txtCountry = country
bellow is code for txtOrgCity
$(document).ready(function () {
$('#txtOrgCity').val({
source: function (request, response) {
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
when I run it gives me [object object] in text box.
How do I define to grab City for txtOrgCity, pin for txtOrgPin, country for txtOrgCountry in response(data.d).?
and do I need to duplicate the same code for other 2 text boxes or any better way.?
Given code is just for some txtbox autocomplete and it works perfectly so I just wanted it to modify a bit for my need. $('#txtOrgCity').val was $('#txtOrgCity').autocomplete
Any help would be appreciated.
--
Thanks
I recommend that you open this up in google chrome. Open up your developer tools (press f12) and, open up resources and select the page you are currently working on. Then use the find box to search for your javascript method which fires the ajax and put a break point inside the success part of your ajax call. Now run your code and wait to hit the break point. Now you can see what is inside your data.d object. Do not resume and keep debugging. Open up your console tab and type data.d. you should see an intelicence option box with all the variables inside your data.d object. You should see the variable for city, pin and country in whatever way you named them when you deserialized your data and returned it as json to your ajax call.
If, for example, you write data.d.city in your console it should write out the corresponding value. The same goes for any other json variable your service passed back to the browser.
With that information it is easy enough to use jquery and do what you want with the data. So in the succes part of your ajax call you can write:
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
p.s. im writting on a phone.
For your example you should not write out the same code two more times. Do not call ajax inside a jquery .val(), that is wrong. Make a new function which handles your ajax, call it from the page load or anywhere you need :
function loadData(//put your user parameter in here if you need){
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
},
error: function (err) {
//welldone for handling your error message. Many people neglect this. As a developer that is like coding blindly. At the very least you can console.log(err); if you don't want the user to see
alert(err);
}
});
}
Instead of $('#txtOrgCity').val({})
In your .ready function make the AJAX call first.
Store d.OrgCity, d.OrgPin & d.OrgCountry into some local JavaScript variables. In the Ajax call success use these values to deposit into textboxes like
$('#txtOrgCity').val(d.OrgCity)
You are after JSON.stringify(). So where you specify your .val() You want .val(JSON.stringify());
I have a button on my site, that when pressed sets the corresponding value in an JSON file to either 0 or 1. A function is continuously running and updating the color of the button depending of the JSON file. This is needed so the button has the same state on all devices.
Now my Problem: It is slow. I want it to be instantly on at least the device the button is clicked. I tried it by setting the color at the same time as the JSON file is updated, but this is buggy since the Ajax call takes some time and the button sometimes flickers. I made the following test: Every time the getStatus() function was called it would add either 1 or 0 to a div. I noticed that after the JSON changed it would still print out the old state a few times before printing the correct one, eventhought i turned cache off
Is there a way to make it faster? Here is the code:
Inex.html:
function getStatus() {
$.ajax({
url: 'status.json',
dataType: 'json',
cache: 'false',
success: function(data) {
varstatus = data;
setColor();
getStatus();
}
})
}
Index.php
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString);
$data[$_GET['id']] = "$f";
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
Another problem I have is that the page is not alway working at the first time. I have to reload to make the updates show, but then it works without.
Or is there another way to do this, without continuously downloading the file?
There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.