I'm using ajax to send values to another form. There, I insert in DB and return the table as html to update instantly. So far it's a simple ajax refresh the table.
The problem is, I check the session to be logged in and do that things. when i delete the cookie (the session timeout) the login page shows in the partial form that should shows the returned table.
I checked... it seems has the "303 see other!" error.
I need it to redirect to login page when the session is times out.
Here is my ajax code:
function save(){
var value = {
//values
};
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
});
}
I check the session in the admin controller.
You can try to use jQuery ajax() statusCode handler like so:
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
statusCode: {
303: function() {
...do stuff you want to do when 303 happens...
}
}
});
Related
I have a HTML page through which I need to pass two variables through post method to a PHP page which accept those two variables and call an API to fetch the result from those two variables.
Now, my requirement is to get the API result back to first page.
I am not able to get it.
From index.html, I am calling another page with -
$.ajax({
url: "data.php",
type: 'POST',
data: {
difficulty: term,
cr : country
},
success: function (res) {
console.log(res);
}
In data.php, I am taking parameters through POST method and calling API,
$(document).ready(function(){
var data;
$.ajax({
url: "https://key***.co*/api?key="+api_key,
dataType: "json",
data: {
difficulty: <?php echo $diff; ?>,
cr : <?php echo $cr; ?>
},
success: function (res) {
data = difficulty;
}
});
}
Here the api_key is defined above. How to fetch the data back to index.html?
You should remove the Javascript from the data.php page, and use php to make the request.
You can refer this:
PHP cURL GET request and request's body
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I tried to redirect the user after he click on a button.
But the redirection is not working.
This is my js code for handling the button click.
$('#MyButton').click(function() {
$.ajax({
url: '<?php echo Url::to(['configurator/compare']) ?>',
type: 'POST',
data: {
Ref : Ref,
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
}
});
The http request image
The request is executed but i'm not redirected to the url.
I stay on the same page when i click in the button.
The code you have posted does not perform a redirect.
All it does is make an ajax POST request to the url: ('configurator/compare') and passes the parameters in data:
To perform a redirect you could do it in the success: callback, e.g.
success: function (data) {
window.location.href = 'http://google.com';
}
You can either hardcode the URL in above, or base it on the output of the script you posted to, which is available by accessing data inside the success callback.
If you don't want return any data to you 'success' function, than in your controller 'configurator', in method 'compare', after handling your data you can make redirection to 'view' which you want:
$data = Yii::$app->request->post();
// do what you want with data
return $this->redirect(['controller/action']);
Try Below way.
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"POST",
data:{id:id},
url : '<?php echo Yii::$app->getUrlManager()->createUrl("/property/favourite"); ?>',
success: function(response){
window.location.href = '<?php echo Yii::$app->getUrlManager()->createUrl("/site/chat"); ?>';
}
});
});
</script>
You can set the path in the controller and send the url back to the page.
public function actionAjaxMethod() {
//my logic
//if everything is successfulget the url path you want to redirect to.
$url = Yii::$app->getUrlManager()->createUrl("/controllerName/methodName");
return \yii\helpers\Json::encode([
'status' => true,
'url' => $url,
]);
}
In your view page all you do is
success: function (data) {
if (data.status) {
//redirect the page to url.
window.location.href = data.url;
}
},
I have the below code in page1.jsp.
$.ajax({
type: "post",
url: "page2.jsp",
data: newdata,
success:function(msg){
return msg;
}
})
Even after POST request, the page remains in page1.jsp and doesn't navigate to page2.jsp. I am seeing statusCode as "200 OK" when I did inspect element. How should I pass the control to page2.jsp if the AJAX call is success. If I am missing some code please correct me.
If you want to navigate to the page you made the post to if the post success, you need to navigate in the success function
$.ajax({
type: "post",
url: "page2.jsp",
data: newdata,
success:function(msg) {
window.location = "page2.jsp";
}
})
hi i am calling a php file using ajax after an interval of time. In my php file i simply echo a text line. But it didnt show me any output after time interval..
here is my ajax code form where i am calling my php file..
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"}, });
}, 5000);
});
</script>
code inside the process.php file
<?php
echo "hello testing";
?>
You aren't handling the response from php script. You need to get it by success parameter in ajax. Try this:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: 'x=1&y=2', // data here! use query strings like this or;
// data: { x: '1', y: '2' }
success: function(response) { alert(response); } // alert the response text
// returns 'hello testing'
error: function(){ alert('error while posting data'); }
});
}, 5000);
});
User the success and error function of ajax. for eg
$.ajax ({
url: 'process.php',
type:'post'
data:data1,
success: function (response) {
//alert response here you will get the value hello testing
alert (response);
},
error {
alert ('error');
}
});
You should modify your code to use the response.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
success:function(str){
$("#YOUR_ELEMENT").html(str);
}
});
}, 5000);
});
Just change your JQuery script to show the response after successful request it can be done with done() or success functions.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: { token: "your_token"}}).done(function(msg){
$("#response").append(msg);
};
}, 5000);
});
This will append reponses to #response every 5s when ajax request is successful.
the success block, which handles the data returned from remote script is present in your code. you may need to add something like this .
JS CODE:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
}).done(function( data) {
//data received from remote script
});
}, 5000);
});
Happy Coding :)
Timeout is not the culprit here.
We need to make sure that you have a server where process.php resides and its running fine.
Make sure the path for the file process.php is right. You can use browser's developer tools. When the request is made you will see a new entry under "Network" tab of the developer tools. Exploring it you can get the url at which it the file should be available.
I would suggest using Google Chrome's "postman" extension to test the ajax call before implementing it in your code.
Also you need to have a callback that will run in case of request success or failure. Once you get the string in success response, you can do whatever you intend to do with it.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"} //removed the comma from last argument
}).done(function(serverResponse) {
alert( "Success: " + serverResponse ); //Will show success alert with concatenated text string if the request is successful
}).fail(function(serverResponse) {
alert( "Error: " + serverResponse.message); //Will show error alert with concatenated error message
});
}, 5000);
});
</script>
the php page sends the string "hello testing", and you have to manage it.
take a look here for an example: click me