jQuery ajax add updated variable in data on every/any ajax request - javascript

So i have the below code to add the additional data to any ajax request made by my app, but the problem is it's working only first time when the page loads , as the application is single page ajax based application , i want to use the updated variable value inside ajaxSetup to make sure all the things work as expected but somehow it takes the old value , i know ajaxSetup setups the data for ajax call on page load. here is what my ajaxSetup looks alike:
var token = 'b62e0352ae559ae1d1e98f0d26604630'; // this variable updates every minute.
setInterval({
var token = $('meta[name=token]').attr('content'); // the updates the token variable every 1 minute
},1000*60*1);
$.ajaxSetup({
data: {
token: token
}
});
as there is predefined token, after every minute it does update , and i just want to pick the updated value of meta tag and then use it for any ajax request made on page.
if there is any another way or correction of this code it will be very helpful.

Request the token when needed so it will be up to date each time.
$.ajaxSetup({
data: {
token: function(){
return $('meta[name=token]').attr('content');
}
}
});

Related

Data loss when request get cancelled using AJAX in Laravel

I'm sending a big amount of data with POST using ajax in Laravel.
When I send request rapidly and redirect the page to another page then data is getting lost when ajax call is canceled or aborted.
I've mentioned the process below:
Send ajax request rapidly
Then before responding to latest request of ajax call by browser I redirect to another page
Then I check the data which is storing when ajax call happen. I found the data is lost.
Below is the code
<script>
var cssData = $('.css-textarea').val();
$.ajax({
url: '/save-data',
type: 'POST',
data: {cssData: cssData},
success:function(response){
//do something after success
}
});
</script>
PHP/Laravel Code
public function saveCssData(){
$data = Input::get();
$cssData = $data['cssData'];
//Do something to save data
$db->cssData = $cssData;
$db->save();
}
Please do not assume the exact code because I've given an example.
This code works fine but when I send rapid calls by ajax and before getting a response, I redirect to another page then the data is lost. I've set enough post_max_size and other configurations but still, it's not fixed
Example of Input which I am sending by ajax request
{
"testCss":
" #class{background:#fff}../*big amount data */...
#testDiv{color:#000}
"
}
Example of The Output which I am receiving in database which is lost
{
"testCss":
" #class{background:#fff}../*big amount data */...
#testDiv{col
You can see the data is lost in output. This issue is appearing at sometimes but I noticed that when I request rapidly with ajax and abort the requests by redirecting to another page then it's appearing but don't know how to fix this.

Prevent javascript code to be reset and start over after page refresh

I have a rails app where in my application.js I have a setInterval() and inside of it an AJAX call that send a post request every minute to my controller in order to perform a create action.
setInterval(function(){
$.ajax({
type: "POST",
url: "/post",
data: { parameter: value },
success: function (data) {
//some logic
}
});
}, 60000);
My problem is that if the client refresh its page every 30 sec (for exemple) the setInterval() set for 1 minute will never be triggered.
Is there a way to make my javascript code not dependent of any page refresh so that if different users arrive at different time they get to see the same thing. I guess it has to do with cookies or local storage but I have no idea how to implement that in a reliable way.
In other word, I would like my js code to be run server side without being disrupted by page refreshes or client request which keep reseting my code.
Thank you for your guidance.
You can use https://github.com/javan/whenever
every 1.minute do # 1.minute 1.day 1.week 1.month 1.year is also supported
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end

Load a Page with Ajax and sent Data to the Page

I have a page where I generate a javascript Array and I want to send it to the berechnungsauswertung.php page and load that page. And than I want to use the data at this page in php.
$.ajax({
type : 'post',
url : 'berechnungsauswertung.php',
data : {
marker : JSON.stringify(data),
homemarker : JSON.stringify(datahome)
},
complete : function(data){
$('body').load( "berechnungsauswertung.php" );
}
});
on the next page I want to get the Variables
$marker = json_decode($_POST['marker']);
$homemarker = json_decode($_POST['homemarker']);
but it does not work. How can I load a Page like this?
This is what you are doing:
Make Ajax request with POST data
Ignore the response
Make Ajax request without any data
Include the content in the page
It doesn't work because you don't have the data from 1 when you are loading the new content in 4.
Replace your complete function with a success function. Do something with the data you get (the first argument to the success function) such as passing it to jQuery('something').html(data).
Don't use load at all.

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

How to avoid values not to display with the url while using window.location.href to pass values from one page to other?

In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!

Categories