I am using two modals forms in one page, one for login and another for register. From login form you can access the register one. I am trying to show an error based on what I echo without reload the page. Instead of echo I tried to return or print,but I got nothing.I don't receive anything from the server. In console.log show me only "Message".
Here is my code:
register.php
if ($count == 0) {
if ($check == 1)
$query = "INSERT INTO..
elseif ($check == 2)
$query = "INSERT INTO..
else {
$query = "INSERT INTO ..
}
if ($db->query($query)) {
echo "1";
} else {
echo "2";
}
} else {
echo "3";
}
My jS
$("#register").on('submit',function (event) {
event.preventDefault();
/*var $form=$(this);*/
$.ajax({
url : 'register.php',
type : 'POST',
data : $('#id02').serialize(),
success : function (data) {
console.log("Message:"+data);
$('#error-reg').text("Success").css('color', 'green');
},
error: function (msg) {
if(msg=="2") $('#error-reg').html('Error while registering.Please try again');
if(msg=="3") $('#error-reg').html('The username already exists.');
}
});
});
try your error: function with below code to check in details
error: function (xhr, err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
},
Try This :
success : function (data)
{
if(data==1)
{
$('#error-reg').text("Success").css('color', 'green');
}
else if(data==2)
{
$('#error-reg').html('Error while registering.Please try;
}
else if(data==3)
{
$('#error-reg').html('The username already exists.');
}
}
Related
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.😅
PHP
As you can see in the below PHP code I am trying the redirect the user but I am struggling to do it in jquery. what I want is if login statement is a success login_success then the user will redirect on myprofile.php but nothing happened.
if($query)
{
$num=mysqli_fetch_array($query); //fetching all matching records
if($num > 0)
{
//if record found
$_SESSION["loggedin"] = TRUE;
$_SESSION['cid']=$num['cid'];
echo "login_success";
}
else
{
echo "invalid email or password.";
}
}else
{
echo "something went wrong!";
}
Ajax:
$.ajax({
url:"sql/login_process.php",
method:"POST",
data:$('#login_form').serialize(),
beforeSend:function(){
$('#login_response').html('<span class="text-info"><i class="fas fa-spinner"></i> Loading response...</span>');
},
success:function(data){
$('form').trigger("reset");
$('#login_response').fadeIn().html(data);
setTimeout(function(){
$('#login_response').fadeOut("slow");
}, 7000);
if(data == "login_success") location.href = "http://www.example.com/myprofile.php";
}
});
I thing I am missing something here.
if(data == "login_success") location.href = "http://www.example.com/myprofile.php";
*Update
There seems to be nothing bad to echo the data as #Patrick Q mentioned below.
Could you try to trim the data received in javascript/jquery to check for unexpected whitespaces
data.trim()
If you want to add more variables you could do the solution below. (or if you prefer it)
You should not echo the result of the ajax. Instead you should return it as json
PHP file:
$ajax_result = array():
$ajax_result['success'] = false;
$ajax_result['message'] = 'Incorrect login data';
if(something)
{
$ajax_result['success'] = 'login_success';
$ajax_result['message'] = 'You were logged in. You will be redirected now.';
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($ajax_result);
That would return the result as array to the front-end and you can operate with it by selecting variables with data.success or data.message etc.
Jquery/Javascript:
$.ajax({
url:"sql/login_process.php",
method:"POST",
data:$('#login_form').serialize(),
beforeSend:function(){
$('#login_response').html('<span class="text-info"><i class="fas fa-spinner"></i> Loading response...</span>');
},
success:function(data){
$('form').trigger("reset");
$('#login_response').fadeIn().html(data.message);
setTimeout(function(){
$('#login_response').fadeOut("slow");
}, 7000);
if(data.success == "login_success") location.href = "http://www.example.com/myprofile.php";
}
});
This is the most basic use. You can modify it to have protection to be accessed only from ajax queries and etc.
Thanks for all the answers and comments above. Honestly, I like Patrick Q Idea here and here is what I accomplished so far.
Ajax
success:function(data){
if(data != null && data == "success"){ //redirect...
window.location = "http://google.com";
} else { //report failure...
$('form').trigger("reset");
$('#login_response').fadeIn().html(data);
setTimeout(function(){
$('#login_response').fadeOut("slow");
}, 7000);
}
}
PHP
if($num > 0)
{
//if record found
$_SESSION["loggedin"] = TRUE;
$_SESSION['cid']=$num['cid'];
echo "success";
}
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
I'm doing an application web for a school and I'm stuck when trying to edit a student. I want the user to click in the row of and specific student and then open a form with his data.
I have to do an ajax request, so I can call my php function (the one which makes the query on my db) and load the data in the form. This is my jQuery code for the ajax request:
//When you click in the table students, in some element whose class is edit ...
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: '../ajax/',
data: {'table': 'alumnos', 'action': 'carga', 'ids': rowID},
dataType: 'json',
success: function(result) {
console.log(result.nombre);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
The ajax request calls the method to get the data from my db:
function cargaAlumno($ids) {
require 'db.php';
$sql = "SELECT * FROM Alumnos WHERE ID=$ids";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
$row = $result -> fetch_assoc();
$nombre = $row['Nombre'];
$apellidos = $row['Apellidos'];
$telefono = $row['Telefono'];
$usuario = $row['Usuario'];
$contrasena = $row['Contrasena'];
$result = array();
$result["nombre"] = $nombre;
$result["apellidos"] = $apellidos;
$result["telefono"] = $telefono;
$result["usuario"] = $usuario;
$result["contrasena"] = $contrasena;
ChromePhp::warn($result);
ChromePhp::warn(json_encode($result));
echo json_encode($result);
}
}
This method has to return a JSON to the ajax request, but the success method is never reached because of the error: parsererror.
I've tried with dataType: 'json' (this is when I have the error) and without it (it thinks its html). I also have tried with and without contentType and in my php: header('Content-type: application/json; charset=utf-8').
My json encoded looks like this:
{"nombre":"Susana","telefono":"56765336","usuario":"susa"}
I don't know if I need some more methods because I'm doing it in Wordpress or I have something wrong in my code.
Any help would be appreciated. Thank you in advance :)
If you are doing it in Wordpress, I'd use the built in wpdb to handle the db connection and results. Like so:
function cargaAlumno() {
global $wpdb;
$ids = $_POST['ids'];
$sql = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM Alumnos
WHERE id = '$ids'
")
);
echo json_encode($sql);
exit();
}
Also remember this goes into your themes functions.php file.
Remember to hook it into the wp_ajax hook:
add_action( 'wp_ajax_nopriv_cargaAlumno', 'cargaAlumno' );
add_action( 'wp_ajax_cargaAlumno', 'cargaAlumno' );
Then in your ajax:
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl, //this is a wordpress ajaxurl hook
data: {'table': 'alumnos', 'action': 'cargaAlumno', 'ids': rowID}, // You didn't use the correct action name, it's your function name i.e. cargaAlumno
//dataType: 'json', dont need this
success: function(result) {
//Parse the data
var obj = jQuery.parseJSON(result);
console.log(obj[0].nombre); // I'm guessing nombre is your db column name
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This js file needs to be added into your theme to work in conjunction with the above reworked function()
Let me know if you need anymore help or have any other questions.
Not sure if you're only providing particular lines of your code or this is the whole thing, anyway this is definitely NOT how you should handle AJAX requests in WordPress:
You should use wp_ajax_ for actions that requires authentication or wp_ajax_nopriv_ for ones that doesn't
You should create an action for this function and send your request through admin-ajax.php using admin_url()
You should definitely secure your requests by creating nonces using wp_create_nonce() and verify it using wp_verify_nonce()
You should restrict direct access to your AJAX file while checking $_SERVER['HTTP_X_REQUESTED_WITH']
There's no need to require db.php since you're already working within functions.php and the db connection is already established.
Use the below method instead:
global $wpdb;
$query = "SELECT * FROM table_name";
$query_results = $wpdb->get_results($query);
To wrap it up, please follow the below structure:
Frontend (php file):
<?php
$ajax_nonce = wp_create_nonce("change_to_action_name");
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce);
?>
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a>
<input id="param" value="" />
Script File (js file):
$('.do_ajax').click(function () {
var ajax_link = $(this).attr('data-ajax_link');
var param = $(this).attr('data-ajax_param');
if (ajax_link && param) {
$.ajax({
type: "post",
dataType: "json",
url: ajax_link,
data: {
param: param,
},
success: function (response) {
if (response.type == "success") {
/*Get/updated returned vals from ajax*/
$('#param').val(response.new_param);
console.log('ajax was successful');
} else if (response.type == "error") {
console.log('ajax request had errors');
}else{
console.log('ajax request had errors');
}
}
});
} else {
console.log('ajax not sent');
}
});
Functions File (functions.php file):
add_action("wp_ajax_change_to_action_name", "change_to_action_name");
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name");
function change_to_action_name()
{
if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) {
exit("You think you are smart?");
}
$param = $_REQUEST['param'];
/*php actions goes here*/
$actions_success=0;
if($actions_success){
/*Query db and update vals here*/
$new_param = "new_val";
$result['new_param'] = $new_param;
$result['type'] = "success";
}else{
$result['type'] = "error";
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
die();
}
Your current code contains many security flaws, so it's very recommended that you update it and use the above method.
Cheers!
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');
}
}