I need to understand how I can change the data of a customer on page 2 without returning to page 1 when reloading the page.
In practice I need to stay on the current page, but currently when I change the data of a customer and save the card, if I am on page 3 it always returns me to page 1.
I tried window.location.reload().
Is there any way to avoid resetting the filters?
This is my JavaScript function:
function rinnova(id) {
var formData = new FormData();
var abbonamento = id.split("-");
var abb = $("#abb" + abbonamento[3]).val();
console.log(abb);
formData.append(
"id",
abbonamento[0] + "-" + abbonamento[1] + "-" + abbonamento[2]
);
formData.append("abb", abb);
$.ajax({
url: "include/rinnovaabbonamento.php",
data: formData,
type: "POST",
contentType: false,
processData: false,
beforeSend: function () {
return confirm("Vuoi rinnovare l'abbonamento?");
},
success: function (response) {
$(".box").html(
"<h3 class='text-center pb-3 pt-3'>Rinnovo confermato!</h3>"
);
document.location.reload();
}
});
}
This is my FooTable code:
if ($('.footable-editing').length) {
var
$modal = $('#footable-editor-modal'),
$editor = $('#footable-editor'),
$editorTitle = $('#footable-editor-title'),
ft = FooTable.init('.footable-editing', {
editing: {
enabled: true,
addRow: function() {
$modal.removeData('row');
$editor.find('#id').val("");
$editor.find('#account').show();
$editor.find('#categoria').val("1");
$editor.find('#costo').val("40.00");
$editor[0].reset();
$editorTitle.text('Add a new row');
$modal.modal('show');
},
editRow: function(row) {
var values = row.val();
$editor.find('#account').hide();
$editor.find('#id').val(values.id);
$editor.find('#nome').val(values.nome);
$editor.find('#cognome').val(values.cognome);
$editor.find('#data').val(values.data);
$editor.find('#luogonascita').val(values.luogonascita);
$editor.find('#residenza').val(values.residenza);
$editor.find('#codicefiscale').val(values.codicefiscale);
$editor.find('#scadenza').val(values.scadenza);
$editor.find('#costo').val(values.costo);
$editor.find('#note').val(values.note);
$editor.find('#attivo').val(values.attivo);
var cat = values.categoria.split(".");
var idcat = cat[0];
if (values.categoria == "Nessuna categoria") {
$("#nessunacategoria").attr('selected', 'selected');
} else {
$("#cat" + idcat).attr('selected', 'selected');
}
$modal.data('row', row);
$editorTitle.text('Edit - ' + values.nome + ' Data');
$modal.modal('show');
},
deleteRow: function(row) {
if (confirm('Sei sicuro di voler cancellare?')) {
var values = row.val();
var formData = new FormData();
formData.append('id', values.id);
formData.append('elimina', "1");
$.ajax({
url: "include/register_account.php",
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
alert(response);
}
});
}
}
}
}),
uid = 10;
};
you have to populate the html page with updated content after the ajax call instead of calling window.reload or document.reload
It's hard to know the details without seeing more of the relevant code, but it sounds like -- from your server's point of view -- there is only ever one page being loaded. When the user sees "page 2", the browser has merely changed the appearance of the page (probably, but not necessarily, including an AJAX request to exchange some information with the server) without actually loading an enire new page. Then, when you ask the server to reload the page, you logically get the original state of the page, which looks like "page 1".
If the address in the URL bar changes whenever the user's view changes (e.g. from "page 1" to "page 2"), then you can control which view the user sees by setting the document.location property, (although using the history API might give you more precise control).
On the other hand, if the address is always the same, you probably can't rely on as much help from the browser to set a particular state, but if the change to "page 2" used an AJAX request to the server, then you can send a similar request to reproduce a similar state.
In either case, the state you get (from the browser's history API or the server's AJAX response) will probably not exacly match the state you want because the user has already made some changes to "page 2". You are already capturing some user-entered information: the id parameter of your rinnova function presumably represents something the user entered. Once you have captured any such information you need, you will trigger the reset of "page 2", then add the finishing touch by
restoring the captured values into whatever page elements they were captured from.
For example, let's imagine that the earlier code said:
const cardID = ("#card-id").val();
rinnova(cardID);
Now that you have reset "page 2", you would repopulate the #card-id element by doing something like:
$("#card-id").val(cardID);
A small caveat about making your changes directly in the browser:
Seeing a change in the URL (when the user's view changes) does means that the browser knows about the change, but it doesn't guarantee that the browser was directly responsible for the change. Using the browser to navigate between views is appropriate in a "single-page application" website where such navigation is generally handled on the client side (i.e. by the browser). But if your site is making these changes from the server side via AJAX, your reset of "page 2" should also be done via AJAX so the server always knows what you're doing.
Related
This is going to be a strange one if I'm honest so please bare with me.
Im currently working on a project that requires me to call python scripts that are part of a webserver that is running a HTML webpage from the page itself i.e You move a slider on the webpage and it calls the python script and passes the value of the slider and an ID value that the script requires to pass the value to its relevant end point. In this case its a monitor ID and the slider value is the brightness value that the brightness must be set to.
Currently I have achieved this with a form submission action but I don't want the webpage to reset once a new value is sent and so JavaScript is my next best option using Ajax requests and while I have made some progress I am basically a noob with web development and have hit a brick wall.
Here is the script I have attempted and the python script that it calls.
<script>
slider.oninput = function (event, ui)
{
var slider_val=event.target.id;
console.log(slider_val);
$( "#"+slider_val ).val( ui.value );
$( "#amount_"+slider_val ).val( $( "#"+slider_val ).slider( "value" ) );
changeBrilliance();
}
function changeBrilliance(value, monid)
{
$.ajax({
type: "POST",
url: "/brilliancechange",
data: { mydata: value, mon: monid }
});
}
</script>
Python:
#app.route('/brilliancechange', methods=['POST'])
def brillchange():
userinput = request.form['mydata']
selectedMon = request.form['mon']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
DATA = "A6" + selectedMon + "0000000401C0"
DATA += hex(int(userinput)).lstrip("0x")
check = checksum(bytes.fromhex(DATA))
DATA += hex(int(check)).lstrip("0x")
dataarray = hextobyte(DATA)
s.sendall(dataarray)
s.close()
What should the javascript look like if i want to call this method with a different ID and value each time without it reloading the webpage everytime?
It looks like changeBrilliance() accepts two parameters but when called nothing is getting passed. I'm not too familiar with the Python framework being used, but as long as it accepts content-type: application/json in POST body you could do:
// not totally sure which value/id combo you need but just pass the necessary ones here
changeBrilliance(slider_val, ui);
function changeBrilliance(value, monid)
{
var myObj = { 'myData': value, 'mon': monid };
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
});
}
Then if you want something in the browser to change, you'll have to callback on done if successful or fail if something goes wrong, and always callback for some behavior that should always happen:
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
}).done(function(data) {
// do something
}).fail(function(jqXHR, textStatus, err) {
// handle error
}).always(function(data) {
// always callback
});
jQuery AJAX seems to be sending two requests at once when I use the onclick event with JavaScript in a tag. I click once, and that seems ok, but when I change the id value to an invalid id value, it sends two requests to the PHP file. I think the problem may be caused by the browser caching JavaScript code.
Here's is the JavaScript code I'm using to generate the query:
function unlike_image(id, image_id, obj) {
var url_unlike_image = base_url + 'profile/unlike_image';
$.ajax({
type: "POST",
data:
{
user_id: id,
image_id: image_id
},
url: url_unlike_image,
success: function(data) {
if (data.status=='error_exists') {
alert('This image not exists');
}
if (data.status=='success') {
//like = like - 1 for view
var str = $(obj).next().text();
var n = str.length;
str_like = str.substring(1, n-1);
var number_likes = parseInt(str_like) - 1;
$(obj).next().text('('+number_likes+')');
//change event click unlike
$(obj).text('Like');
$(obj).attr('onclick', 'like_image('+id+' ,'+image_id+ ',this); return false');
}
}
});
}
After changing the true id to the wrong id, I check the website traffic, I see two instances where unlike_image is called. The first is with the true id, and the second is with the wrong id.
I wrote a little chat plugin that i'll need to use on my site. It works with a simple structure in HTML, like this:
<div id="div_chat">
<ul id="ul_chat">
</ul>
</div>
<div id="div_inputchatline">
<input type="text" id="input_chatline" name="input_chatline" value="">
<span id="span_sendchatline">Send</span>
</div>
There's a 'click' bound event on that Span element, of course. Then, when the user inserts a message and clicks on the "Send" span element, there's a Javascript function with calls an Ajax event that inserts the message into the MySQL database:
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
}
});
}
And, in case the message is successfully inserted into DB, it calls a function to read new lines and put them in HTML structure i posted before:
function function_get_newchatlines()
{
$.ajax
({
type: "POST",
url: "ajax-chat-loadnewlines.php", //1: ok, 0: errore
data: '',
dataType: "text",
cache: false,
success: function(ajax_result) //example of returned string: 'message1>+<message2>+<message3'
{
//explode new chat lines from returned string
var chat_rows = ajax_result.split('>+<');
for (id_row in chat_rows)
{
//insert row into html
$('#ul_chat').prepend('<li>' + chat_rows[id_row] + '</li>');
}
$('#span_sendchatline').html('Send');
}
});
}
Note: 'ajax_result' only contains html entities, not special chars, so even if a message contains '>+<', it is encoded by the php script called with Ajax, before being processed from this JS function.
Now, comes the strange behaviour: when posting new messages Opera, Firefox and even IE8 works well, as intended, like this:
But, when i open Chrome window, i see this:
As you can see, in Chrome the messages are shown multiple times (increasing the number each time, up to 8 lines per message). I checked the internal debug viewer and it doesn't seem that the "read new lines" function is called more than one time, so it should be something related to Jquery events, or something else.
Hope i've been clear in my explanation, should you need anything else, let me know :)
Thanks, Erenor.
EDIT
As pointed out by Shusl, i forgot to mention that the function function_get_newchatlines() is called, periodically, by a setInterval(function_get_newchatlines, 2000) into Javascript.
EDIT2
Here's is a strip of the code from the PHP file called by Ajax to get new chat lines (i don't think things like "session_start()" or mysql connection stuff are needed here)
//check if there's a value for "last_line", otherwise put current time (usually the first time a user logs into chat)
if (!isset($_SESSION['prove_chat']['time_last_line']) || !is_numeric($_SESSION['prove_chat']['time_last_line']) || ($_SESSION['prove_chat']['time_last_line'] <= 0))
{
$_SESSION['prove_chat']['time_last_line'] = microtime(true);
}
//get new chat lines
$result = mysql_query("select * from chat_module_lines where line_senttime > {$_SESSION['prove_chat']['time_last_line']} order by line_senttime asc; ", $conn['user']);
if(!$result || (mysql_num_rows($result) <= 0))
{
mysql_close($conn['user']); die('2-No new lines');
}
//php stuff to create the string
//....
die($string_with_chat_lines_to_be_used_into_Javascript);
Anyway, i think that, if the problem was this PHP script, i would get similar errors in other browsers, too :)
EDIT4
Here's the code that binds the click event to the "Send" span element:
$('#span_sendchatline').on('click', function()
{
//check if there's already a message being sent
if ($('#span_sendchatline').html() == 'Send')
{
//change html content of the span element (will be changed back to "send"
//when the Ajax request completes)
$('#span_sendchatline').html('Wait..');
//write new line
function_write_newchatline();
}
//else do nothing
});
(Thanks to f_puras for adding the missing tag :)
I would do one of the following:
option 1:
stop the timer just before the ajax call in function_write_newchatline() and start the timer when the ajax call returns.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
stop_the_timer();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
},
complete: function() {
start_the_timer();
}
});
}
option 2:
Not call function_get_newchatlines() at all in the success event of the ajax call. Let only the timer retrieve the chat entries.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
// do nothing
}
});
}
I think there is some race condition between the function_get_newchatlines() that is called after a chat entry is added by the user and the periodical call of function_get_newchatlines() by the timer.
option 3:
Use setTimeout instead of setInterval. setInterval can mess things up when the browser is busy. So in the end of the setTimeout function call setTimeout again.
Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.
I am trying to get everyone's total clicks on a button. I was thinking about POST function with ajax but it would make lots of PHP request on the server. I want to do something like that:
<script>
document.getElementById('buttonToClick').onclick = function() {
var totalClicks = ???; // get total clicks number from the server somehow and
// assign it to var totalClicks;
document.getElementById("totalClicks").innerHTML = totalClicks;
??? = ??? + 1; // add 1 to total clicks number and save it to server.
};
</script>
<input id="buttonToClick" type="submit" name="button" value="enter"/>
<a>The button is clicked <a id="totalClicks"></a> times!</a>
Is it possible to make this with Javascript?
You would have to use AJAX to POST the data to the server, since you are using jQuery you can use the $.ajax function.
As an example:
$(document).on("click", "#buttonToClick", function() {
uploadClickCount();
});
function uploadClickCount()
{
var userId = $("#UserId").val(); // Get the user id first
var totalClicks = $("#totalClicks").val();
$.ajax({
url: 'YourWebsite/ClickCounter',
type: "POST",
data: { user: userId, clickCount: totalClicks },
success: function() { }
error: function() { alert('Unable to connect to the server'); }
});
}
An alternative to save on calls to the server would be to attempt to send the total clicks when the user leaves the page or closes the page using the window.unload method, however this may be unreliable.
You could also look at storing the click count in HTML 5 local storage and then upload it when the user returns/once the DOM is ready, i.e.. $(document).ready(function() { });
It would also be best practice to store when the user last attempted to contact the server, you can then use this to invoke the AJAX call after a 10 second delay which would prevent mass requests server side.