hi everybody i have the following function for ajax call. I need to replace the image with the ajax call image. I need to clear my cache before i call the shownewimage function. Thankyou..
function drawImg(idx)
{
var imp = document.getElementsByName("img_pan");
fn = fnArr[parseInt(idx)];
path = 'designs/' + fn;
$("#img_pan").html('<img id="imgView" src="'+path+'"></img>');
$("#state_info").show();
var url="newimage.php?fn="+path+"&act='getcolors'";
httpRequest("GET", url, shownewimage); // i need to clear cache before the shownewimage function executes.
request.send("");
}
Thing is you can't clear browsers cache from javascript, so what you need to do is to make sure that responses from your server for this newimage.php never get cached.
try this for PHP:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: 0');
Alternatively you could always generate randomized Url like /newimage-12345677, you'd just need the server to map it to the actual php script.
Related
I'm having an issue with session not passing through an Ajax call. The app works perfectly fine as standalone web application. But once I use it in iframe, I can see that session is not used properly.
Here's an Ajax call from my main file
var sessionId = "<?php Print(session_id()); ?>";
$.post('ajaxget.php', { sessionId: sessionId},
function(result){
console.log(result);
}, "json").fail(function(j) {});
In ajax.php I have this
$sid = session_id();
$senddata['callerSession'] = $_POST['sessionId'];
$senddata['ajaxSession'] = $sid;
$senddata['session'] = $_SESSION;
header('Content-Type: application/json');
echo json_encode($senddata);
exit();
Running this provides a result where "callerSession" and "ajaxSession" are different ids, though they should be the same. And therefore $_SESSION variable is empty in ajax.php.
I've tried these solutions
https://forum.codeigniter.com/thread-25591.html - didn't work
Persistent session_id inside an iframe - unable to alter codeigniter's session.
Been stuck on this for quite a while now and I'm lost. I think the problem might be with cookie with session id information not passing correctly but that's just my blind guess. Perhaps there's a way how I could set the session having the needed session's id (tried searching for that but found no ways of doing that)? Any help is appreciated
I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s
I put JavaScript code in a view file name product/js.blade.php, and include it in another view like
{{ HTML::script('product.js') }}
I did it because I want to do something in JavaScript with Laravel function, for example
var $path = '{{ URL::action("CartController#postAjax") }}';
Actually everything is work, but browser throw a warning message, I want to ask how to fix it if possible.
Resource interpreted as Script but transferred with MIME type text/html
Firstly, putting your Javascript code in a Blade view is risky. Javascript might contain strings by accident that are also Blade syntax and you definitely don't want that to be interpreted.
Secondly, this is also the reason for the browser warning message you get:
Laravel thinks your Javascript is a normal webpage, because you've put it into a Blade view, and therefore it's sent with this header...
Content-Type: text/html
If you name your file product.js and instead of putting it in your view folder you drop it into your javascript asset folder, it will have the correct header:
Content-Type: application/javascript
.. and the warning message will be gone.
EDIT:
If you want to pass values to Javascript from Laravel, use this approach:
Insert this into your view:
<script type="text/javascript">
var myPath = '{{ URL::action("CartController#postAjax") }}';
</script>
And then use the variable in your external script.
Just make sure that CartController#postAjax returns the content type of javascript and you should be good to go. Something like this:
#CartController.php
protected function postAjax() {
....
$contents = a whole bunch of javascript code;
$response = Response::make($contents, '200');
$response->header('Content-Type', 'application/javascript');
....
}
I'm not sure if this is what you're asking for, but here is a way to map ajax requests to laravel controller methods pretty easily, without having to mix up your scripts, which is usually not the best way to do things.
I use these kinds of calls to load views via ajax into a dashboard app.The code looks something like this.
AJAX REQUEST (using jquery, but anything you use to send ajax will work)
$.ajax({
//send post ajax request to laravel
type:'post',
//no need for a full URL. Also note that /ajax/ can be /anything/.
url: '/ajax/get-contact-form',
//let's send some data over too.
data: ajaxdata,
//our laravel view is going to come in as html
dataType:'html'
}).done(function(data){
//clear out any html where the form is going to appear, then append the new view.
$('.dashboard-right').empty().append(data);
});
LARAVEL ROUTES.PHP
Route::post('/ajax/get-contact-form', 'YourController#method_you_want');
CONTROLLER
public function method_you_want(){
if (Request::ajax())
{
$data = Input::get('ajaxdata');
return View::make('forms.contact')->with('data', $data);
}
I hope this helps you... This controller method just calls a view, but you can use the same method to access any controller function you might need.
This method returns no errors, and is generally much less risky than putting JS in your views, which are really meant more for page layouts and not any heavy scripting / calculation.
public function getWebServices() {
$content = View::make("_javascript.webService", $data);
return (new Response($content, 200))->header('Content-Type', "text/javascript");
}
return the above in a method of your controller
and write your javascript code in your webService view inside _javascript folder.
Instead of loading get datas via ajax, I create js blade with that specific data and base64_encode it, then in my js code, I decode and use it.
I registered a GET route for laravel.dev/test. The corresponding controller for the route would distinguish whether the request is ajax or not.
When I type laravel.dev/test on the browser, Laravel detect that it's not an ajax request and uses return View::make() to generate the page. Then Backbone.js code on the page make an ajax request to laravel.dev/test and Laravel uses return Response::json to return a JSON.
It's all fine until when I try to navigate away from the page and then use the browser button to navigate back to laravel.dev/test that it print out the json as the response, which is not what I expect since I'm not making an ajax request.
Definitely a caching issue. Just to try and get some results, add this to your controller (ajax and non-ajax) to force-disable caching:
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
And see if chrome still fetches from the cache on the back button.
This is not a laravel or backbone, but a chrome issue! Check this out too.
The solution that worked for me is to put
return Response::json($this->data)->header("Vary", "Accept");
Good luck!
This is in Laravel 5.1, but the principle should work for all previous versions as well.
The way I handled it was with two routes pointing to the same method, but with one ending in a .json extension:
get('items', ['as' => 'items', 'uses' => 'ItemsController#index']);
get('items.json', ['as' => 'items', 'uses' => 'ItemsController#index']);
Then inside my index() method:
$data = []; // your collection
if ($this->request->ajax()) {
return response()->json($data); // replace with actual JSON data
}
return view('items.index', compact('data'));
This allows for a dedicated URL for JSON responses, uses the same method and data, and never interferes with my back button.
I have this jquery script to call an external file. So far so good. The script is working fine, but as always IE makes what he wants. The external file that I load with this script (weather.php) is a file with real-time weather conditions data in it. Whit this script, I can refresh the div inside which is my weather.php file. And obviously I don't want IE to cache the data in this file. I want when someone click on button "REFRESH", the included page to be reloaded with the new data in it. In IE this doesn't happens because of the cache.
How can I change this script to not cache the div's content, or how can I say to my included file (weather.php) to do not cache it self?
This is the script:
function ajax_request() {
$('#column_weather').html('<img src="../images/home/ajax-loader.gif" width="16" height="11" style="vertical-align:middle;"/><b> Loading...</b>');
$('#column_weather').load("../includes/home/weather.php");
}
`
And that's how I call the script:
Refresh`
Put a random variable on your query String
$('#column_weather').load("../includes/home/weather.php?myRand=" + guid());
I would make random var return a guid
function s4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function() guid{
return s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4();
}
Can't you just have proper caching instructions inside this weather.php file (to say not to cache it)
I would attach the current date and time as a GET parameter. Internet Explorer (and other browsers) view this information as critical to loading the page, just as any function returns a different value with different parameters. The trick is that you don't have to use the parameter. :)
$('#column_weather').load("../includes/home/weather.php?t=" + date());
Adding a random parameter to the end of the query URL will help, but try adding this to the beginning of weather.php:
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>