I don’t know what the problem is. I have an ajax which sends username to the controller:
function my_profile(username){
$.ajax({
url: "member/my_profile",
type: "get",
data: "username="+username,
success: function(){
window.location.href = 'member/my_profile';
}
});
}
And this is my controller:
function my_profile(){
$username = $this->input->get('username');
$data['username'] = $username;
$this->load->view('my_profile' , $data);
}
I have already echo the $username to test that it can alert(msg) from the ajax. It works just find. Problem is nothing is shown in my view:
<h1>My Profile</h1>
<?php
echo $username;
?>
I don’t know why. I tried initialized $data['username'] = 'adam' and this works.
The problem is your window.location.href = 'member/my_profile';. This will redirect you to the profile page without any username value.
You probably want to do:
window.location.href = 'member/my_profile?username='+username;
Though, I still don't understand why you have that AJAX call there. Couldn't you just do:
function my_profile(username){
window.location.href = 'member/my_profile?username='+username;
}
Your AJAX call is loading the page then discarding the contents, I don't think you need it here.
$.ajax({
url: "member/my_profile",
type: "get",
data: "username="+username,
success: function(){
window.location.href = 'member/my_profile';
}
});
Should be :
$.ajax({
url: "member/my_profile?username=" + username,
type: "get",
success: function(){
window.location.href = 'member/my_profile';
}
});
Related
I am trying to get the fc_id of the immunization then past it in profiling but the problem is the redirect() doesn't work. I successfully transfer my fc_id but the problem is i can't go to profiling view when i click the button.
Here some photo to understand my question clearly
So here's my code.
View:
$(document).on("click", "#view_profile", function(e){
e.preventDefault();
var view_id = $(this).attr("value");
$.ajax({
url: "<?php echo base_url(); ?>immunization/view_profile",
type: "post",
dataType: "json",
data: {
view_id: view_id
}
});
});
View Profile
Immunization Controller:
public function view_profile(){
$this->load->helper('url');
$this->load->library('session');
if ($this->input->is_ajax_request()) {
$view_id = $this->input->post('view_id');
$this->session->set_tempdata('view_id', $view_id);
redirect('profiling/index');
}
}
Profiling Controller:
public function index(){
$this->load->helper('url');
$this->load->library('session');
$this->load->view('profiling');
}
You are trying to redirect in an ajax request and thats not gonna work. Just post back some message if everything is ok and in ajax succes check that message and redirect from there with location.href = yoururl like:
In your php:
$this->session->set_tempdata('view_id', $view_id);
echo json_encode('msg' => 'ok');
js:
$.ajax({
url: "<?php echo base_url(); ?>immunization/view_profile",
type: "post",
dataType: "json",
data: {
view_id: view_id
}
success: function(resp){
if (resp.msg == 'ok') location.href = 'profiling/index';
}
});
I have the following link to make my ajax call in yii2:
echo Html::a('Load more','ajaxShowMoreProducts', [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: 'ajaxShowMoreProducts',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Then I have an action in my SiteController:
/**
* #return string|\yii\web\Response
*/
public function actionAjaxShowMoreProducts() {
var_dump('in');die;
$params = [];
$productModel = new Product();
$params['products'] = $productModel->getAll();
$this->renderPartial('partialProductItem', $params);
}
However when I click the link,the correct controller action does not seem to be called. Its still calling site/index. Any ideas what I have to do to get this working? Have i forgotten some sort of annotation or maybe I have to define my new action somewhere?
When I look in the console, it looks correct:
Request URL: http://localhost:8080/site/ajaxShowMoreProducts
In yii2 you should use the proper notation for action url (in url calling si not used the camelNotation but the words are separated by - (minus)
echo Html::a('Load more','ajax-show-more-products', [
and in ajax url too
url: 'ajax-show-more-products',
or try using Url Helper
use yii\helpers\Url;
....
echo Html::a('Load more', Url::to(['/site/ajax-show-more-products']), [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: '" . Url::to(['/site/ajax-show-more-products']) . "',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.
I want the success on ajax post to go to the home page. For some reason I keep doing it wrong. Any idea what I should do to fix this?
window.APP_ROOT_URL = "<%= root_url %>";
Ajax
$.ajax({ url: '#{addbank_bankaccts_path}',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
dataType: "json",
data: 'some_uri=' + response.data.uri ,
success: function(APP_ROOT_URL) {
window.location.assign(APP_ROOT_URL);
}
});
success: function(response){
window.location.href = response.redirect;
}
Hope the above will help because I had the same problem
You can return the JSON from server with redirect status and redirect URL.
{"redirect":true,"redirect_url":"https://example.com/go/to/somewhere.html"}
And in your jQuery ajax handler
success: function (res) {
// check redirect
if (res.redirect) {
window.location.href = res.redirect_url;
}
}
Note you must set dataType: 'json' in ajax config. Hope this is helpful.
Not sure why, but window.location.href did not work for me. I ended up using window.location.replace instead, which actually worked.
$('#checkout').click(function (e) {
e.preventDefault();
$.ajax('/post/url', {
type: 'post',
dataType: 'json'
})
.done(function (data) {
if (data.cartCount === 0) {
alert('There are no items in cart to checkout');
}
else {
window.location.replace('/Checkout/AddressAndPayment');
}
});
});
EDIT
Ok, so I can login fine but when I enter false info I'm redirected to the login page, what I need is to stay on the same page and show the error message e.preventDefault(); doesn't seem to work.
$(function() {
$("#login-form").submit(function(e) {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
e.preventDefault();
},
success: function(){
document.location = '/';
}
});
return false;
});
});
Your not actually doing anything with the form, ill try commenting your code to talk you through whats happening.
I'm guessing your using PHP server side for this code.
In PHP you want to check the user credentials and then tell the browser. If the login was successful send back "y", and if it failed "n".
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
},
success: function(data) {
if (data == "y") {
//Login was successful. Redirect statement here?
} else {
//Failed login message here
}
}
});
return false;
});
});
</script>
Edit
Try adding this in your success function. Please let me know what you get for a successful login and a failed login.
success: function(data) {
console.log(data);
}
Edit 2
This is because your ajax call is successful, just that the login failed. This is why your success handler is called.
To sort this you'll need to see what is being returned from the server, is it nothing? In which case try:
success: function(data) {
if (data == "") {
e.preventDefault();
} else {
//Login successful, redirect user.
}
}
You should add:
success: function(data){
/* Validation data here, if authentication answer is correct */
if(data == 'ok')
document.location = '/';
else
/* show error here */
}
the success occur when URL is found and accessible.
and error occur when URL is not found.
if you want check the callback MSG you must print it in the URL page & check data in success.
like this:
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
success:function(data){
if(data=="true"){
alert("success");
}else{
alert("faild")
}
}
});
return false;
});
});
</script>
in login.php
<?php
//check if for true...
echo "true";
//and if it is not true...
echo "false";
?>
the data parameter in success is a string which get back the html content of "/login"