How can delete Ajax Request from browser memory? - javascript

I have a simple problem, how can I delete the ajax request store into the memory. I'll try to explain what I'm will trying to get.
I have a form for edit a table into database.
All runs well the first time, but the problem is after trying again. If I don't refresh the page, it always sent the same data from the first request.
Example:
Into database I have
id
user
password
I have a form with the same parameters, and I called this form with ajax.
I edited a register from the database, and I sent the data edited, and run well, but into the browser memory, the request is stored.
I try to edit again the same register, but when I send again, the data is the same like the first time.
If the first time send:
user : 'userx'
password : 'usex1234'
When I try again to edit this register for example with:
user: 'userxx'
password : 'password1234'
at the end, the data send has these values
user : 'userx'
password : 'usex1234'
How can fix this? I suppose delete the first request, but I can't.
I want to clean the memory from browser without f5 or refreshing, because only with f5, running again well.
I tried:
request = new Request();
request = null; but not happens nothing
delete request; but is the same, nothing changes.
Who can help me please?
MY CODE:
function _update(id){
var n = Number(new Date());
var edit = new Request({
url: 'users/edit?'+new Date().getTime(),
noCache: true,
onRequest: function(){
$('dark').setStyle('display','block');
},
onSuccess: function(data){
$('dark').setStyle('display','none');
box_edit.close();
update();
},
onComplete: function(response){
console.log(response);
},
onFailure: function(){
Sexy.error("Ocurrio un error procesando su solicitud, intente más tarde.");
}
});
var box_edit = new LightFace.Request({
url: 'users/edit?'+new Date().getTime(),
draggable:true,
title: 'Editar usuario.',
request:{
method: 'post',
data: { isc_user_id: id }
},
buttons: [ { title: 'Editar', color:'blue', event: function(){
var id__ = $('isc_user_frm_id_'+id).get('value');
if (before_update(id__)){
if ( $('isc_password_'+id__).get('value')=='' && $('isc_re-password_'+id__).get('value')==''){
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
}else{
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_password='+hex_md5($('isc_password_'+id__).get('value'))+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
}
edit.send(data);
}
}
},
{ title:'Cancelar', event:function(){ this.close(); } }]
});
box_edit.open();}

The simplest solution, as your server-side should be stateless, and the variables shouldn't be cached to send to the server, so the problem is probably with how you are getting the values.
The browser may cache when it requests information from the server, which is why it was suggested to turn off caching, but that is for data coming from the server.
So, I would suggest you use the Firebug extension on Firefox and you can put in breakpoints to see if the values are changing.
For every part of setting data you should put these in variables so you can check each value easily.
I didn't create all the variables, but I wanted to show an example to help you.
var val1 = $('isc_user_'+id__).get('value');
var val2 = $('isc_password_'+id__).get('value');
var data = 'userEdit=Ok&isc_user='+$('isc_user_'+id__).get('value')+'&isc_password='+hex_md5($('isc_password_'+id__).get('value'))+'&isc_group='+$('isc_group_'+id__).getSelected().get('name')+'&isc_user_id='+ id;
You will also want to look at the value of id as you may not be appropriately changing that value when the password is changed. I expect this will be your problem.

Append a string like e.g. a timestamp to the requested url, this prevents the browser from using the cached version of the requested ressource.
In mootools there is a noCache-option for Request, set it to true.(default is false, so the cache will be used there without setting the option)

The OP wrote:
FIX
Ok, after tring a lot of ways to fix, I found a solution, which consist of creating a dynamic form. I created a random variable and sent just before to get the form with ajax, after recovery this value into the server code, I put this value like a name of the form and I have a dynamic form. With this I fixed the problem.
Example
function rand(){
return Math.floor(Math.random()*1000);
}
function _update(id){
var form_rand = rand();
...
data: { isc_user_id: id , form_rand : form_rand }
...
To get the value now:
var id__ = $('isc_user_frm_id_'+id+form_rand).get('value');
Into the html I have and hidden input like this:
<input type="hidden" id="isc_user_frm_id_<?php echo $form_rand; ?>" value="<?php echo $r; ?>" ?>

Related

How to sent data to server, remove parameter from url and reload window with new url Javascript, jQuery and PHP

I am currently stuck with a problem I can't seem to find a decent solution for.
Problem:
I have written some code that will send 2 parameters to an action within a PHP script through a url. I need these parameters sent to the action no matter what. However, after the parameters are sent, I need to remove one of said parameters from the URL and then reload the page with said new URL.
I hope I could give you a clear description of my problem. Following is the code I have written so far.
jQuery(document).ready(function() {
// Define array with the dashboard id and title as key => value pairs.
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
// Get arg01 from the server.
var arg01 = <?php echo json_encode($arg01); ?>;
// Prepare URL variable and spike it with arg01 to be sent back to the server.
var url = 'Path/To/action/Index/index&arg01='+arg01;
// Button change and function tied to it. Instead of an ajax request, we reload the page completely.
$("#idDashboards").change(function() {
// Define dashboardIndex. The -1 stands for the option tag that has already been created.
var dashboardIndex = $(this).prop('selectedIndex')-1;
// Sent parameters to actionIndex in Controller and remove dashboardIndex after the request was successful.
if (url.includes(arg01)) {
window.location.href = url+"&dashboardIndex="+dashboardIndex;
console.log("Yes i was here");
}
// window.location.href = url; <---- Here is where the problem begins.
});
});

Ajax not getting most recent version of JSON file

I'm rather new to terminology and coding in general, but I've tried to trim down my code, though it may still have redundancies. Thanks in advance for your understanding.
I'm using an ajax and php script to write some data to a file on the server called data.json. The script works fine, and opening the json file shows that it's indeed updated with the data. The json file simply contains an array of objects.
Here's the code that does this:
function writeData() {
$.ajax({
type : "POST",
url : "save.php",
async : true,
data : {
json : JSON.stringify(dataToWrite)
}
});
document.getElementById('success-box').innerHTML = "Data successfully written.";
};
...and the PHP:
<?php
$json = $_POST['json'];
$file = fopen('data.json','w+');
fwrite($file, $json);
fclose($file);
?>
The problem I'm having is this: The user can navigate to a separate HTML page, and can click a button to view the data in the json file in a nicely-formated way. This is done via another ajax script that reads the data. This latter ajax script doesn't seem to be able to "see" the newly updated json file. It instead loads the old version of the file, before it was updated with the first ajax script. I'm sure that this second ajax script is run after the above writeData() is finished, because it's actually on a separate HTML page entirely, which is loaded later, after the user clicks a button.
Here's the second ajax script that reads the data from the data.json file (it's on another, separate HTML page):
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json",
async : true,
dataType : 'json',
success : function(response) {
data = response;
document.getElementById('main').innerHTML = `
<div id='top-stuff'>
<button onClick='viewData()'>Reset Filter</button>
<button onclick="print2()">Print Worksheet</button>
</div>
<br>
<div id='left-column' class='column'></div>
<div id='right-column' class='column'></div>
`;
leftColumn = document.getElementById('left-column');
rightColumn = document.getElementById('right-column');
leftColumn.innerHTML = "<b>Sentences:</b> <br><br>";
rightColumn.innerHTML = "<b>Errors:</b> <br><br>";
//add the sentences and their errorTypes:
for (i=0; i<data.length; i++) {
var senBox = document.createElement('div');
senBox.className = 'box';
senBox.setAttribute('id', 'sen' + i)
senBox.innerHTML += data[i].text;
var errBox = document.createElement('div');
errBox.className = 'box';
errBox.setAttribute('id', 'err' + i)
errBox.innerHTML += data[i].errorType;
leftColumn.appendChild(senBox);
rightColumn.appendChild(errBox);
}
}
});
All of these files are hosted in the same directory on One.com.
The strange thing is that when I manually open the data.json file and edit its contents in any way (by deleting everything, for example), the next time the ajax call is made, it reads the version I just manually updated. This makes me think it might be something to do with the One.com server refreshing itself?
I tried adjusting the ajax between synchronous/asynchronous, and using cache: false, but these don't seem to affect anything.
I've searched around, and can't seem to find out what's going on here. Thanks for any guidance you could provide.
Thanks. I ended up using the following:
jQuery.ajaxSetup({
cache: false
});
I tried using this before, but for some reason it didn't work, not sure why. But it's working now! Thanks.
first, GET method can be cached by the browser.
second, Make sure the response is a json type
$.ajax({
type : "GET",
url : "http://eslquiz.net/ell_errors/data.json?rand_v=" + Matn.random(), // add a random try again
async : true,
dataType : 'json',
success : function(response) {
// Make sure the response is a json type
// console.log(typeof(response));
// console.log(typeof(JSON.parse(response)));
data = response;
// ...

I have passed an array in session variable. I need to pass key strokes to it to return values

I have stored the returned data from a mysql query into a session variable. I can extract what I want from using $_SESSION['info'][][].
I would like to be able to retrieve values from the array dynamically. The user will select numbers from drop downs (2 of them). One of the numbers needs to passed to the first element of the array and obviously, the second goes to the second element. And then, the result is echoed to the screen.
I need to do this all client side. So like this:
Get result of keypress a
Store it as $a
Get the result of keypress b
Store it as $b
Pass the results of to echo $_SESSION['info'][$a][$b]
I can get one key stroke and pass it to a variable and even possible the second with my limited knowledge but pass them to the session variable and printing the result escapes me at the moment.
enter code here$(document).ready(function() {
$("#pcc").keyup(function() {
var dInput = $(this).val();
$n1=dInput;
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
$(document).ready(function() {
$("#pcp").keyup(function() {
var dInput = $(this).val();
$n2=dInput
//$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
I know I could probably nest that but one hurdle at a time. I know that saves the keystrokes. I have tested it by passing the values to alerts.
Progess at last. I am using this code to pass the variables from the input fields:
$(document).ready(function(){
$("#pcp").keyup(function(){
var value = $("#pcp").val();
n1= value;
});
$("#pcp").keyup(function(){
var value = $("#pcc").val();
n2= value;
matrix('n1','n2');
});
});
And I know its getting passed to matrix() because Im dumping the variables to console from within matrix like so:
function matrix(){
// getting values from key presses
//console.log(n1, n2);
$.ajax({
url: "matrix.php",
method: 'GET',
dataType: 'json',
data: { a: n1, b: n2 },
success: function(data) {
var response = data.response;
}
$_SESSION['arrayOfMatrix'][$a][$b]= response;
});
I also know that the variables have been passed because I was getting variable undefined errors in console and now I dont. So 2 positive things.
However, thats as far as seem to be able to go. I dont seem to be getting anything back. I have tried putting console.log inside of matrix.php but I dont get anything in that either so Im guessing its just not firing and sending data to matrix.php. Is there any other testing I can do to see where its failing? I feel that Im close to nailing it.
};
What you need is AJAX. You need to create a PHP script that will take two values for $a and $b through a GET or POST request. You can then use jQuery's $.ajax to asynchronously invoke that script and get the result.
So for a start you need a PHP script (let's call it for the sake of this example: example.php).
In example.php you can do something like this:
<?php
session_start();
$a = $_GET['var_a'];
$b = $_GET['var_b'];
//do some checking of the two above variables here
$response = array(
'response' => $_SESSION['info'][$a][$b];
);
echo json_encode($response);
You can substitude $_POST with $_GET if you prefer using a POST request instead.
The next step involves quite a bit of JavaScript so, when you have both $n1 and $n2 populated you can send a POST request using $.ajax:
$.ajax({
url: <path-to-example.php>,
method: 'get',
dataType: 'json'
data: { var_a: $n1, var_b: $n2 }
}).done(function(data){
var response = data.response;
//$_SESSION['info'][$a][$b] is now in response
});
Again you can substitute 'get' with 'post' in case of a POST request

Stop jQuery from returning entire page into my div

So I've got a form that has the action of 'create_topic_parse.php', it sends the input values to that from 'create_topic.php', then they are inserted into the database. I am able to send any errors from the 'create_topic_parse.php' file to the 'message' div in my 'create_topic.php' page using the following code:
$("#submit").click( function() {
// I've tried e.preventDefault(); here ^ but it's giving the same result.
$.post( $("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html(info).css('color','#be4343');
});
$("#topic_form").submit( function() {
return false; // Not working
});
});
When the form is CORRECTLY input, and no errors are to be passed from the PHP file, the PHP script is supposed to redirect the user to 'view_topic.php?cid=".$cid."&tid=".$new_topic_id."&page=1'. If I don't include the jQuery above, this works fine.
Problem: If I include the jQuery script, it returns the entire 'view_topic.php/etcetc' page into '', which is bad.
So the question is, does anyone know how to prevent the entire page from being posted into this div, and actually redirect the user to 'view_topic.php' page when the form is correctly submitted?
Note: I've tried window.location, however I've then the issue of the concatonated variables from my PHP file that are input into the 'view_topic.php/etcetc' url. I am trying to get it to work with header('location:...'), like it does when the jQuery file isn't included.
Thanks in advance,
Richie
Solution:
jQuery + Ajax to PHP:
if($('#topic_title').val() == ''){
$('#message').html("You need to give your topic a title.");
}
Using this code I was able to check whether each data entry existed, when all of the data values were existing I'd run the AJAX script within the same file passing each value into a variable like so:
var submit = $('#submit').val();
var topic_title = $('#topic_title').val();
$.ajax({
type: "POST",
url: "create_topic_parse.php",
data: {submit:submit, topic_title:topic_title),
etc etc.
Try this one. It'll work
when form is correctly submitted then only send some string like "correct", and in jquery let you check the ouput string. if it's "correct" then redirect it to view topic via javascript.
if you want to redirect the user to an specific page sent from server, then send from server something like this in json format.
write code on server something like this.
if ($condition==true) {
$ajax_return = array(
'message' => 'correct',
'url' => 'your_redirect_url'
);
}
else
{
$ajax_return = array(
'message' => 'your user defined error message',
'url' => 'leave it blank'
);
}
$ajax_return = json_encode($ajax_return);
echo $ajax_return;
and now jquery on create_topic.php page
$("#topic_form").submit( function(e) {
e.preventDefault();
$.post(
$("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
info= JSON.parse(info);
if(info.message="correct"){
window.location=info.url;
}
else{
$("#message").html('');
$("#message").html(info).css('color','#be4343');
}
});
});
I'm sure now it'll work. If not, let me know.

Periodically autosave form

How to implement a periodical save of a form in the background? Same kinda thing that gmail does.
setInterval(function(){
var form = $('#my-form-id');
var method = form.attr('method').toLowerCase(); // "get" or "post"
var action = form.attr('action'); // url to submit to
$[method](action, form.serialize(), function(data){
// Do something with the server response data
// Or at least let the user know it saved
});
},10000); // do it every 10 seconds
If you don't want to use the method of the form, but always want to use 'post', then use:
$.post(action, form.serialize(), ... );
And, if you want to supply your own action for the autosave that is different from the action for the actual save:
$.post("/autosave/comments", form.serialize(), ... );
You would need a timed loop on the client side that would save the form every x seconds/minutes. A crude way of doing this would be to have a setTimeout javascript function that collects the form's field values and updates the model via an update (PUT in Rails' case) AJAX request.
Example
Here's a crude way of doing it (i.e. there might be a better way):
// repeat every 10 seconds
var repeatTime = 10 * 1000;
function updateModel(){
// get field values (using jQuery, etc.)
// make ajax request using these field values
//(make sure put parameters match model attribute names)
console.log('updated');
setTimeout(updateModel, repeatTime); // start call over again
}
setTimeout(updateModel, repeatTime);
I included the console.log so that you can test this out in Firebug right now and see that the updateModel executes every 10 seconds. I would recommend using jQuery to generate the PUT AJAX requests.
Why not do this purely on the client, using a local database (or whatever)? That should reduce complexity, server load and bandwidth usage.
Permanent or per-session storage -- whatever's appropriate -- and you can save after every keystroke: no need for setTimeout().
Sisyphus.js: Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.
http://sisyphus-js.herokuapp.com
Smashing Magazine article: http://coding.smashingmagazine.com/2011/12/05/sisyphus-js-client-side-drafts-and-more/
Version that works without jquery:
function urlencodeFormData(fd) {
var s = '';
function encode(s) { return encodeURIComponent(s).replace(/%20/g,'+'); }
for (var pair of fd.entries()) {
if(typeof pair[1]=='string') {
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
setInterval(function() {
var form = document.getElementById('my-form-id');
var request = new XMLHttpRequest();
request.open(form.method, form.action);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
request.send(urlencodeFormData(new FormData(form)));
}, 10000);
If you need to do something with the server response see this post: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

Categories