calling php code with ajax results in an error - php

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");
}
});

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

How to make reload page function after submit data in php

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

How to use Ajax and return view al the same time

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 cant get response from json encode

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

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Categories