How to store server HTTP response header in browser? - php

In my PHP application, I get a page by Ajax request and load it into a specific div element of the page. I am sending some headers from server in response too.
How to store that headers in browser?
actually as i had mentioned above , through ajax i am loading page and browser url remains unchanged during process , and when i am clicking back button of browser it is redirecting me to very first page of application. all i am trying to do is to store name of requested page by ajax in that browser history which helps back button to navigate functionality .
what i am thinking is possible logically?

The success function called by your jQuery $.ajax request will have a jqXHR object as its third argument. You can use this object's getResponseHeader() method to get the response headers from the server's http response. See the docs for more info: http://api.jquery.com/jQuery.ajax/#jqXHR
For example:
$.ajax({
url: "...",
success: function(data, responseText, jqXHR) {
var headers = jqXHR.getResponseHeader();
// Do what you will with the headers here
}
}

Related

How to ajax call a php file hosted on remote server and receive a response?

We are trying to call from index.html on local, a simple PHP file hosted on webhost000 to receive a response. PHP file is:
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo ($name);
}
?>
We would like to simply input a character on a textbox in html.index and receive the same character as response from the php. We are using an ajax call to do this in html file:
<script>
$(document).ready(function() {
$('#name').keyup(function() {
var name = $('#name').val();
var request = $.ajax({
url: "https://nedo93.000webhostapp.com/phpdemo.php",
method: "POST",
data: { name : name },
dataType: "html"
});
request.done(function( msg ) {
alert( "Request done: " + msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
(The remaining html should not be important, it works perfectly, tested and retested)
If we try to debug this we can see that the file is found, the request is sent, but we can't receive a response: screenshot
If we use this browser function instead, we can send data and receive a response without a problem, don't know if this can help.
Thank you in advance if you can answer this question.
This is because your PHP script is hosted on a different server and your AJAX call code is on local.
For AJAX to run, there is same-origin policy. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin (means both are on same domain). Read more about same origin policy here.
The same-origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframe within a page, or by the use of JSONP, websockets, cross-domain messaging or cross-domain resource sharing.
So in short you will not be able to access the PHP request residing on a 000webhost server to be accessed using AJAX code on local.
Either you host the AJAX code on the same 000webhost domain as well or enable cross-domain resource sharing on 000webhost domain where your PHP code is running.
As far I know, 000webhost is a free server and doesn't supports these changes. So you will have to either get a better server or test this all in a local.
Also as you mentioned in your query, all HTTP requests like GET, POST, PUT works cross domain. But for AJAX, no its not so straight forward.
Hope this helps!
use json_encode
your code should be....
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
header('Content-Type: application/json'); //just used as info for your application
echo json_encode($name); //encode to JSON object
}
?>
after that do JQuery validation for checking Json reply (specially for error).

Content-disposition: attachment does not force download as attachment [duplicate]

I would like to make an async GET request that returns back a document with MIME content type and cause it to bring the browser's 'Save' dialog.
Previously, I used to make a regular HTTP (non-async) call through a link and the returned response had a 'Content-Type' and 'Content-Disposition' like so:
Content-Type: text/plain
Content-Disposition: attachment;
filename=genome.jpeg;
modification-date="Wed, 12 Feb 1997 16:29:51 -0500";
Is there a way to convert this to jQuery's $.ajax() GET request?
The $.ajax method only supports the dataTypes, "xml", "html", "script", "json", "jsonp", and "text". Would my response data-type fall into one of these categories?
My request looks like this:
$.ajax({url: myUrl,
data: params,
type: "GET",
success: function(data)
{
console.log("try to save this file!");
},
error: function(req, status, errThrown){
alert("ERROR: Something happened");
}
In the 'success' callback, I see the file contents passed back in the 'data' variable as a plain text but need the 'save' dialog to get launched on the browser.
The server IS sending back the response with the correct headers set.
There is no way I know of to get a true Ajax request to pop a save dialog up. This has nothing to do with the headers sent by the server.
If you'd like to programatically pop a save dialog box, you can use jQuery to append a hidden iframe to the page with the URL as it's src. This should pop the dialog box as necessary.
That's something the server has to do. There's nothing you can do from the client side that will force an unwilling server to set response headers.

The usage of `header("Content-type:application/json");`

I just created an JQuery ajax function to retrieve some json-encoded data from PHP, here's my code :
file name : bank.php
$('form').on('submit', function(){
var datatobesent = $(this).serialize();
$.ajax({
data: datatobesent,
url:'data.php',
type:'GET'
})
.done(function(data){
console.log(typeof(data));
});
return false;
})
and in data.php I wrote
if(isset($_GET)){
$data = $_GET;
echo json_encode($data);
header("Content-type:application/json");
}
the question is, when I delete the line of header("Content-type:application/json"); in data.php the console.log tell that the type of data returned by ajax is string.
And when I added dataType :json`` inside the ajax function in bank.php the type changes into object
so what is the function of header("Content-type:application/json"); actually?
The function header("Content-type:application/json") sends the http json header to the browser to inform it what kind of data it expects. You can see all the http headers for each request in your browser (If you are using chrome open developer tools, go to network, adjust the view and reload the page, you will see all requests made by your browser, if you click on any on any of these requests then click on headers you will see the headers of each request).
When you use this function you will notice the http header Content-Type:application/json in the response sent from the server. If you don't use it the server will send the default which most likely is Content-type:text/html; charset=UTF-8
As #Monty stated you don't need this function if you added dataType: 'json' to your AJAX as Jquery will handle the data even it is sent with text/html header.
See Also: jQuery AJAX Call to PHP Script with JSON Return
To read more about headers : http-headers-for-dummies

How to send HTTP headers from client via JQuery AJAX call to PHP script?

I'm using a device detection PHP script on the server, mobiledetect.net and normally the user's browser would make a direct call to that on the server and so obviously the detection script would get all the HTTP headers (that it uses for device detection) directly that way.
If I call the same server side PHP detection script via a JQuery AJAX call from my javascript running on the user's browser, does it receive all the HTTP headers it needs for detection, as it would with the direct method? i.e. does JQuery allow or set all the HTTP headers for the AJAX call on the script as the browser would directly?
If not, how would I achieve this please?
Headers the detection script requires are: HTTP_ACCEPT, HTTP_X_WAP_PROFILE, HTTP_X_WAP_CLIENTID, HTTP_WAP_CONNECTION, HTTP_PROFILE, HTTP_X_OPERAMINI_PHONE_UA, HTTP_X_NOKIA_GATEWAY_ID, HTTP_X_ORANGE_ID, HTTP_X_VODAFONE_3GPDPCONTEXT, HTTP_X_HUAWEI_USERID, HTTP_UA_OS,
HTTP_X_MOBILE_GATEWAY, HTTP_X_ATT_DEVICEID, HTTP_UA_CPU
Many thanks.
Yes you can set the HTTP headers in your ajax call :
$.ajax({
url: 'YourRestEndPoint',
headers: {
'header1':'xxxxxxxxxxxxx',
'herader2':'xxxxxxxxxxxxxxxxxxxx',
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'json',
data: YourData,
success: function(data){
console.log('succes: '+data);
}
});
Please find more information here :Add Header in AJAX Request with jQuery.
To get the value of the HTTP headers, use the following code :
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
More information here

Cross-domain AJAX request error on HTTP 200

I'm writing a very basic Facebook app, but I'm encountering an issue with cross-domain AJAX requests (using jQuery).
I've written a proxy page to make requests to the graph via cURL that I'm calling via AJAX. I can visit the page in the browser and see it has the correct output, but requesting the page via always causes jQuery to fire the error handler callback.
So I have two files:
Proxy, which does the cURL request
<?php
//Do some cURL requests, manipulate some data
//return it as JSON
print json_encode($data);
?>
The facebook canvas, which contains this AJAX call
$.getJSON("http://myDomain.com/proxy.php?get=stuff",
function(JSON)
{
alert("success");
})
.error(function(err)
{
alert("err");
});
Inspecting the call with Firebug shows it returns with HTTP code 200 OK, but the error handler is always fired, and no content is returned. This happens whether I set Content-Type: application/json or not.
I have written JSON-returning APIs in PHP before using AJAX and never had this trouble.
What could be causing the request to always trigger the error handler?
Recently I experienced the same issue and my problem was the fact that there was a domain difference between the webpage and the API, due to the SSL.
The web page got a HTTP address (http://myDomain.com) and the content I was requesting with JQuery was on the same domain but HTTPS protocol (https://myDomain.com). The browser (Chrome in this case) considered that the domains were differents (the first one with HTTP, the second one with HTTPS), just because of the protocol, and because the request response type was "application/json", the browser did not allowed it.
Basically, the request worked fine, but your browser did not allowed the response content.
I had to add a "Access-Control-Allow-Origin" header to make it work. If you're in the same case, have a look there: https://developer.mozilla.org/en/http_access_control.
I hope that'll help you, I got a headache myself.

Categories