I have three different parts to my page. The first is a button, the second is a JS function (AJAX request) and the last one is a PHP script that is called by the AJAX request.
The PHP script is supposed to call a web service to process the data. Here is the content of the PHP script:
<?php
if(isset($_POST['forminfos'])){
$client = new SoapClient('URL');
$client->Function();
header('Location: localhost/page.php');
}
?>
The page is not redirected but when I check the console I can see that there is a GET with the localhost/page.php content.
//on button sumbit
var data=$('#forminfos').serializeArray();
$.ajax({
url: '../func.php',
data:data,
type: 'POST',
dataType: 'json',
success: function () {
},
error: function(){
}
});
I expected the page with the AJAX request to be redirected to 'localhost/page.php' but it is not.
The problem is that the file you are doing the redirect in is being called by AJAX. That means that although you are redirecting that request page, the actual page you made the ajax request from is not being redirected. The end of your ajax request results in the script you called being redirect not the page it is requested on.
If you only goal is to get to your destination in the header (localhost/page.php) then you could wait for the AJAX request to finish and do:
window.location.href = "localhost/page.php"
This uses javascript instead to redirect the page on the successful completion of your AJAX request.
Further reading:
Basic JS docs about window
Difference between window location and window replace
Related
After user's filled the input fields and has submitted I use an ajax request to complete the sign up process.In this register.php I'd like to redirect the user to another page after I inserted their info to the database. Everything is fine and nothing is outputted until header() function. The code below does not redirect and as if nothing happened the callback function of ajax request is processed. I am really stuck here, I don't know what to do.I can try javascript solutions but I'd prefer php solution over that one.
Code:
header("Location: http://localhost/profil.php", true, 307);
exit();
You can use JavaScript to redirect in the ajax success callback function:
success: function(data) {
window.location.href = 'http://localhost/profil.php';
}
It can't be done with a PHP header redirect, because that will only redirect the ajax call, not the original browser window.
Hello am implementing a jquery site and i dont want the user to wait for page reloading after every click so a use #p2 to navigate between pages. I use ajax to prevent page reloading and i get my parameter from a response.php page with $_GET method...after this i store the $_GET['value'] in a session in order to use it to the page2...but this work only if i refresh the page. Otherwise the session variable has the previous value before page reloading.
My question is simple...how to get the session latest value without page reloading...?
Or is there any way to pass parameters from page 1 to page 2 without reloading?
Thanks in advance
The code is shown below:
function send_an_article_id_to_php(an_article_id)
{alert(an_article_id);
$(document).on
(
"click", "#" + an_article_id ,function()
{
$.ajax(
{
type: "GET",
url: "../get_an_article_id.php",
data: { cmd2 : $(this).attr("id") },
success: function(response)
{
$("#response3").html(response);
}
} /*end of ajax }*/
);/*end of ajax );*/
}/*end of click event*/
);/*end of document*/
}/*end of function katigoria*/
Sessions have server side processing. You can simply sent request to server using ajax and modify or change session info there. After your desired result you can get print these values and send them back to client side.
You can print value in form of json and make html from these values on client side or simply you can make HTML in you ajax file, sent it to your client and place in your desired location using client side scripting.
I am sending an ajax request to a php login backend that varyfies the user and password, starts a session and sends a positive or negative response.
The response is then translated to a user message by jquery and if the credentioals were correct, the user is redirected to the closed part of the site via
window.location.href('mySecretSite.php')
The problem is, that I am allways thrown back to the login site on first try of the browser session, because the next php script has no session and assumes the user is not logged in.
try this
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
After a lot of headache I worked it out.
The error was mine as usual. So I share it to give others the opportunity to learn from my stupidity.
The starting site of the backend was an index.html file which led to the browser not saving the session cookie PHPSESSID passed over by the ajax response.
Changing the startpage of the "secretsite" to index.php fixed the bug entirely.
For example I have an action in Controller.
public function redirectnowAction() {
$this->_redirect( '/module/controller/action' );
}
When I call above action in normal way then it redirect successfully to desired location But when I call above action by AJAX then it does not redirect to required URL and only show desired page content in firebug.
JS code for AJAX
jQuery('.AjaxLink').live( 'click', function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html( snippets[id] );
}
});
});
How to redirect to action after AJAX request ?
Thanks
When you use a redirect, you send a header to the user's browser to fetch content at the new location.
AJAX requests are not usually setup to handle such redirects. They simply initiate a request, and return the response.
The best-case solution is to reorganize your code so a redirect is not necessary. If you cannot eliminate the redirect, you must update your Javascript to recognize the redirect status (HTTP 301, for example) and initiate a new request.
You cannot do it directly, here's what I'd do. In the action called via AJAX, include something like this:
echo Zend_Json::encode(array('redirect' => '/module/controller/action'));
This way, your AJAX call will receive a JSON object as a response. In jQuery's $.ajax() call, you can specify a success event, e.g.:
'dataType': 'json', // expects to receive a JSON-formatted response
'success': function(data, textStatus, jqXHR) {
window.location.replace('http://www.example.com' + data.redirect);
}
The ajax request itself would be subject to the redirect, not the browser window. Hence you would see the redirected content as the data returned via ajax. One solution would be to do a javascript redirect once the ajax request has been successfully run.
I have a web page with a form. When the user submits the form, I want the server to make the browser redirect to a different page from the form action. Right now, I am doing this by using PHP's header function to send a 302 status code. It works fine.
I am trying to make the page on the server redirect the browser in the same way, regardless of whether it was submitted normally (without Javascript) or via Ajax. I tried to do this by setting the window location to whatever URL is in the Location header. I am using jQuery, and doing a call like this:
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
complete: function(request) {
window.location.assign(request.getResponseHeader("Location"));
}
});
However, that didn't work. After thinking about it, I realized that this is not very surprising. In an Ajax request, the browser is supposed to transparently handle redirect responses such as 302 codes before changing the readyState. When the complete function runs, it is looking for the Location header in the final destination and not finding it.
As an experiment, I then tried sending a 200 status code with a Location header. I tried the Ajax request and it worked fine. However, when I did the non-Ajax submit, it didn't work. The browser went to the form action page and stayed there, like it was ignoring the Location header.
Is there any way to make the same page redirect in both cases, without the server having to know or care whether the request is an Ajax request?
In case this matters, I tried the form in various browsers (IE8, IE7, IE6, Firefox 3.5, Chrome) with similar results each time. Also, I am doing a post request to avoid bumping into IE's 2083-character URL length limit.
HTTP 302 response are consumed silently by XmlHttpRequest implementations (e.g. jQuery's ajax function). It's a feature.
The way I've solved this in the past is to detect for XmlHttpRequests and issue a "Content-Location" header (rather than a "Location" header). The most cross-library way of doing this is to check for the "X-Requested-With" http header in your server-side code (jQuery, Prototype, Mootools among others set this):
if (#$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
header('Content-Location: ' . $redirect_url);
} else {
header('Location: ' . $redirect_url);
}
You still need to special-case your client-side code:
$.ajax({
// ...
complete: function(xhr) {
var redirect_url = xhr.getResponseHeader("Content-Location");
if (redirect_url) {
window.location = redirect_url;
}
}
})
If the user is getting redirected regardless, why the Ajax? The whole point of Ajax like this is to make changes to the page without a page refresh, so the technique you're using seems a little like building a printer that outputs into a shredder hopper.
I'd like to know more about your use-case for this. From what I understand your trying to get your application to load a page based on the 'Location' header of an Ajax call within it? I'd ask why?
An HTTP header doesn't seem to be the right place to get that information from. Isn't your application essentially making a query that says "Where shall I redirect to?". There's no reason the Ajax response actually has to respond with a 302 and a 'Location' header. Why not just have it respond with JSON or XML which contains the new URL?
Edit: Just re-read your penultimate paragraph. I'm not sure there's a good way of achieving what you want. The concept sounds broken to me. :)
Pass additional parameter to your ajax request for easy identify type of request. When ajax - do not redirect - just send target url, then redirect client side in ajax callback via location.href
like this:
$.post('/controller/action', {formdata}, function (redirect_to) {
location.href = redirect_to;
});
Will "complete" work:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
complete: complete(xhr, status) {
window.location.assign(xhr.getResponseHeader("Location"));
}
});
Did you try using the error function instead of complete?
$.ajax({
url: this.action,
type: "POST",
data: getFormData(this),
error: function(request) {
if(request.status == 302)
window.location.assign(request.getResponseHeader("Location"));
}
});
jQuery sends any 3xx response to the error function. Maybe the 'Location' header will still be available at this stage.
Why not have your "ajax action" simply fill in the needed form fields and submit the form instead? This way you'll get exactly the same behavior as when submitting by hand.
Here is another option although you will need to do some cross browser tests:
complete: function(request) {
if(request.status == 200) {
var doc = document.open(request.getResponseHeader('Content-Type'));
doc.write(request.responseText);
doc.close();
}
}
Major drawbacks: URL in address bar doesn't change; could mess with back button/history
Although I think #crescentfresh's idea is the way to go