I want to reload page after submitting data, but I got some problem with that, i've tried several ways but it doesn't work. here's my code :
here's the ajax :
$('#form-tambah-posisi').submit(function(e) {
var data = $(this).serialize();
$.ajax({
method: 'POST',
url: '<?php echo base_url('Posisi/prosesTambah'); ?>',
data: data
})
.done(function(data) {
var out = jQuery.parseJSON(data);
tampilPosisi();
if (out.status == 'form') {
$('.form-msg').html(out.msg);
effect_msg_form();
location.reload();
} else {
document.getElementById("form-tambah-posisi").reset();
$('#tambah-posisi').modal('hide');
$('.msg').html(out.msg);
effect_msg();
}
})
e.preventDefault();
});
here's the controller :
public function prosesTambah() {
$this->form_validation->set_rules('tgl_date', 'Date', 'trim|required');
$data = $this->input->post();
if ($this->form_validation->run() == TRUE) {
$result = $this->M_posisi->insert($data);
if ($result > 0) {
$out['status'] = '';
$out['msg'] = show_succ_msg('Add Success!', '20px');
} else {
$out['status'] = '';
$out['msg'] = show_err_msg('Add Failed!', '20px');
}
} else {
$out['status'] = 'form';
$out['msg'] = show_err_msg(validation_errors());
}
echo json_encode($out);
}
Looking forward for solution. thank's.
In PHP you can simply use this :
echo "<meta http-equiv='refresh' content='0'>";
where you want page reload
You can send headers to a customer.
header('Location: http://www.example.com/');
you can try this
location.reload(true);
you can force to reload the page from the server by setting the forceGet parameter to true. check it here
Related
I'm trying to call some php code using ajax:
$(document).ready(function() {
$("#email_address").on("keypress", function() {
request = $.ajax({
url: '../verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
//fooling around to see if this works
if(response) {
alert("valid email");
} else {
alert("invalid email");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
});
However, the request.error function runs. I'm not too sure why. Here is the php code:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
} else {
echo 'false';
}
}
?>
Thanks in advance.
ugh, noob mistake. i had set the php url to be relative to the .js file instead of to the web page. it was supposed to be:
request = $.ajax({
url: 'verify_email.php'
instead of
request = $.ajax({
url: '../verify_email.php',
i figured it out with the use of Chrome's web inspector . i learned two new things today: what the url has to be relative to and how to use Chrome's web inspector. thanks all for your help
If your url work fine, in php try to return json ;)
<?php
$return = false;
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$return = true;
} else {
$return = false;
}
}
header('Content-Type: application/json');
echo json_encode(array('result' => $return));
die;
?>
And in javascript try:
request.done(function(response) {
//fooling around to see if this works
if(response.result) {
alert("valid email");
} else {
alert("invalid email");
}
});
I have a login method in my controller where I check if there is such user in database or not. I call this method when press Submit button. I show login from view at the same time.
In my case, it doesn't show message if there is such user. I think because in my controller I load view.
How could I show this message if there is such user using Ajax and if I return view as I do in my case?
I'm using Kohana. Thanks!
My code is:
$(document).ready(function(){
$('#submit').on('click', function() {
if(username.length === 0 || password.length === 0) {
//...check if validation fails
}
else {
$.ajax({
url: "/admin/signin" ,
type: "POST",
data: {
"username":username,
"password":password
},
success: function(data) {
if(data !== 'error') {
window.location = "/admin/index";
}
else
{
alert('no such user');
}
}
});
}
});
});
public function action_signin()
{
if ($_POST) {
$is_admin = Model_Admin::signin($_POST);
print 'success';
} else {
print 'error';
}
}
$this->template->content = View::factory('admin/login_form');
}
If you want not load 'default' template try using $this->auto_render = FALSE;
also kohana controller has method is_ajax $this->request->is_ajax()
You controller code will be like this.
public function action_signin()
{
if($this->request->is_ajax()){
$this->auto_render = FALSE;
}
if ($_POST) {
$is_admin = Model_Admin::signin($_POST);
if($is_admin){
print 'success';
} else {
print 'error';
}
}else{
$this->template->content = View::factory('admin/login_form');
}
}
I am trying to get values from form with serialize function and I correctly post and save to database but after this step my codes don't work . Someone help please ?
$(document).ready(function() {
$("#kform").submit(function() {
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "yenikayit2.php",
data: data,
dataType: "json",
success: function(data) {
if (data.tip === "dosya") {
alert("tralalala d");
}
if (data.tip === "tercume") {
alert("tralalala t");
}
if (data.tip === "hata") {
alert("tralalala hata");
}
}
});
});
PHP Code
<?php
if($musteri_ekle) { //mysql control function
$musteri_id=mysqli_insert_id($baglanti);
$_SESSION[ 'musteri_id']=$musteri_id;
if ($secilen=="dosya" )
{ echo json_encode(array( "tip"=>"dosya")); }
else if ($secilen == "tercume")
{ echo json_encode(array("tip"=>"tercume")); } }
else { echo json_encode(array("tip"=>"hata")); } ?>
Modify yenikayit2.php to avoid PHP fatal error and notices. You can either use error_reporting(null);
or edit the code as below
if (isset($musteri_ekle)) { // to avoid undefined variable error
$musteri_id = mysqli_insert_id($baglanti);
$_SESSION['musteri_id'] = $musteri_id;
if ($secilen == "dosya") {
echo json_encode(array("tip" => "dosya"));
} else if ($secilen == "tercume") {
echo json_encode(array("tip" => "tercume"));
}
} else {
echo json_encode(array("tip" => "hata"));
}
Well, i realized that i forgot put this fields on form action="" and method=""
after this i changed my jquery code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
$("#kayit").click(function(event) { var data=$("#kform").serialize(); }
And this works correctly
I'm trying to make a login page that validates the users input data. If "username" and "password" does not match in the database he would receive a warning.
I'm a total newbie when it comes to this, so the code I have now is a combination of different tutorials.
my signin.php looks like this:
header('Content-Type: application/json')
$data = array(); // array to pass back data
if(!empty($_POST["action"]))
{
if($_POST["action"] == "signin")
{
...all the SQL code here...
if(!empty($result))
{
foreach ($result as $row)
{
...some SQL code here...
$data["success"] = true;
$data["message"] = "Success!";
}
}
else
{
$data["success"] = false;
$data["message"] = "Error!";
}
echo json_encode($data);
}
}
Now I want this json data to be used in a jquery submit function that uses ajax to get the data from signin.php:
<script>
$("#login-form").submit(function(event) {
$.ajax({
type : 'POST',
url : 'signin.php',
data : { 'action': 'signin' },
dataType : 'json'
}).done(function(data) {
console.log(data.success);
if(!data.success)
{
alert("ERROR");
}
else if (data.success)
{
alert("SUCCESS");
}
});
event.preventDefault();
});
</script>
no title that fits this bug but this how it goes, i have form with a submit button when pressed jquery ajax calls the controller and the form validation is done if it fails the form is redrawn if it passes the page is redirected to the home page with flash message successes and thats where the bug happens it redraws the whole page in the content(header header footer footer). i hope it makes sense seeing is believing so here is the code
side notes: "autform" is a lib for creating forms "rest" is a lib for templates.
the jquery code:
$("form.user_form").live("submit",function() {
$("#loader").removeClass('hidden');
$.ajax({
async :false,
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
success: function(data) {
$("#center").html(data);
$('div#notification').hide().slideDown('slow').delay(20000).slideUp('slow');
}
})
return false;
});
the controller
function forgot_password()
{
$this->form_validation->set_rules('login',lang('email_or_login'), 'trim|required|xss_clean');
$this->autoform->add(array('name'=>'login', 'type'=>'text', 'label'=> lang('email_or_login')));
$data['errors'] = array();
if ($this->form_validation->run($this)) { // validation ok
if (!is_null($data = $this->auth->forgot_password(
$this->form_validation->set_value('login')))) {
$this-> _show_message(lang('auth_message_new_password_sent'));
} else {
$data['message']=$this-> _message(lang('error_found'), false); // fail
$errors = $this->auth->get_error_message();
foreach ($errors as $k => $v){
$this->autoform->set_error($k, lang($v));
}
}
}
$this->autoform->add(array('name'=>'forgot_button', 'type'=>'submit','value' =>lang('new_password')));
$data['form']= $this->autoform->generate('','class="user_form"');
$this->set_page('forms/default', $data);
if ( !$this->input->is_ajax_request()) { $this->rest->setPage(''); }
else { echo $this->rest->setPage_ajax('content'); }
}
}
function _show_message($message, $state = true)
{
if($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
}else{
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
redirect(base_url(),'refresh');
}
i think it as if the redirect call is caught by ajax and instead of sending me the home page it loads the home page in the place of the form.
thanks for any help
regards
OK found the problem and solution, it seemed you cant call a redirect in the middle of an Ajax call that is trying to return a chunk of HTML to a div, the result will be placing the redirected HTML in the div.
The solution as suggested by PhilTem at http://codeigniter.com/forums/viewthread/210403/
is when you want to redirect and the call is made by Ajax then return a value with the redirect URI back to Ajax and let it redirect instead.
For anyone interested in the code:
The Jquery Ajax code:
$("form.user_form").live("submit", function(event) {
event.preventDefault();
$("#loader").removeClass('hidden');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
dataType:"html",
data: $(this).serialize(),
success: function(data) {
var res = $(data).filter('span.redirect');
if ($(res).html() != null) {
[removed].href=$(res).html();
return false;
}
$("#center").html(data);
},
error: function() {
}
})
return false;
});
The PHP Controller
function _show_message($message, $state = true, $redirect = '')
{
if ($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
} else {
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
if ( !$this->input->is_ajax_request())
{
redirect(base_url() . $redirect, 'location', 302);
}
else
{
echo '<span class="redirect">'.base_url().$redirect.'</span>';
}
}
just use individual errors
json_encode(array(
'fieldname' => form_error('fieldname')
));
AJAX
success: function(cb)
{
if(fieldname)
{
{fieldname}.after(cb.fieldname)
}
}
see this