I'm working on a method in my class that outputs error messages for both ajax and regular post request. The PHP part works fine, but the json part doesn't seem to. Here is my method:
public $formError = false;
public $phpErrors = '';
public $jsonErrors = array();
// ------------------------------------------------------------
// ERROR PROCESSING
// ------------------------------------------------------------
private function responseMessage($bool, $msg) {
$return['error'] = $bool;
$return['msg'] = $msg;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
$this->jsonErrors[] = $return;
} else {
foreach ((array) $msg as $key => $value) {
$this->phpErrors .= $msg;
}
}
$this->formError = true;
}
I think, the problem is that no matter if it is just a single error message or multiple, the json object is always wrapped with square brackets. I couldn't find anything online that would show an example. The messages look like this:
SINGLE ERROR:
[{"error":true,"msg":"Error message 1 ..."}]
MULTIPLE ERRORS:
[{"error":true,"msg":"Error message 1 ..."},{"error":true,"msg":"Error message 2 ..."}]
Firebug shows 200 OK but my JQuery does not output any messages:
$.ajax({
type: 'POST',
url: plSubmitUrl,
data: plFormData,
dataType: 'json',
cache: false,
timeout: 10000,
success: function (data) {
if (data.error === true) {
// display error message
plResponse(data.msg, true);
...
} else if (data.error === false) {
// display success message
plResponse(data.msg, true);
...
}
},
When I was showing only one message at a time, the JQuery was working fine.
Any help would be great. Thanks
Dont use strict equality operator === since from PHP you are actually sending string, instad of:
if (data.error === true)
Use:
if (data.error == true)
Since multiple error contains more than one index, so it might not picking data.
check length for more than error.
$.ajax({
type: 'POST',
url: plSubmitUrl,
data: plFormData,
dataType: 'json',
cache: false,
timeout: 10000,
success: function (data) {
var x = data.length;
if(x == 1){
if (data.error === true) {
// display error message
plResponse(data.msg, true);
...
} else if (data.error === false) {
// display success message
plResponse(data.msg, true);
}
}else{
jQuery.each(data,function(key,val){
// do whatever you need
}
}
header('Content-Type: application/json');
Add this right before echoeing in your PHP script to let jquery know it has to parse the whole string as JSON.
And use "==" to compare instead of "==="
Related
When sending data to an ajax post call I get "NULL" returned.
I am sending a lot more data (which all works), but left it out of the snippet to make it more clear.
When I log the var in my console, it shows up. When I check the network tab if the data is properly sent, it shows up. When I var_dump the $_POST in PHP it returns NULL.
Jquery
function get_cars_ajax() {
var filterAdvertentienummer = 119005595; // is number
$.ajax({
type: 'POST',
url: '/wp/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
'action' : 'get_cars_filter',
'filterAdvertentienummer ' : filterAdvertentienummer,
},
success: function(data) {
if(data != '') {
// DO SOMETHING
} else {
// DO NOTHING
}
},
error: function(data) {
console.log(data);
}
}
PHP
function get_cars_filter() {
global $post;
$context = Timber::get_context();
var_dump($_POST['filterAdvertentienummer']); // = NULL
echo $_POST['filterAdvertentienummer']; // = empty string
if (isset($_POST['filterAdvertentienummer'])) {
$advertentienummer = $_POST['filterAdvertentienummer'];
} else {
$advertentienummer = "";
}
$queryList = '?skip='.$current_page.'&limit='.$limit.'&sort='.$sort.'&order='.$order;
if ($advertentienummer != "") {
$queryList = $queryList . "&advertentienummer=" . $advertentienummer;
} else {
var_dump($advertentienummer);
}
$args = array(
'headers' => array(
'accept' => 'application/json'
)
);
$results = wp_remote_retrieve_body(wp_remote_get('http://IP/cars'.$queryList, $args));
return $results;
}
I noticed a mistake in your ajax code.
Your code line:
'filterAdvertentienummer ' : filterAdvertentienummer,
you have added one space in the variable name so it's not gonna be readable by PHP.
Modified code :
'filterAdvertentienummer' : filterAdvertentienummer
Now PHP will read this variable as a string. You can convert strings in int with PHP.
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.😅
I am currently using Codeigniter and working on CRUD operation in one HTML form.
I am using Ajax for this create/read/update.
I have also used Transaction Management as best practices in a database query.
The Problem:
(1) I want separate Error message for Update and Insert Error. Which I did not get in the ajax error section.
(2) I have used the debugger to debug this problem but I do not get it proper.
Here is the Code of my controller.
Controller:
public function save_candidate_experience() {
$this->db->trans_start();
if(empty($postId))){
$query_staus = $this->test_model->insert_function( $data );
if($query_staus != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Inserting.');
} else{
$msg = array('message'=>'Successfully Insert');
}
} else {
$query_staus2 = $this->test_model->update_function( $data );
if($query_staus2 != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Updateing.');
}else{
$msg = array('message'=>'Successfully Updated');
}
}
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
echo json_encode ($msg);
}
else
{
$this->db->trans_commit();
echo json_encode ($msg);
}
}
This is the Model Code:
public function insert_function() {
$this->db->insert('table_name', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
public function update_function() {
$this->db->where('id', $id);
$this->db->update('test_table', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
Ajax Code in my view.
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
//doing something with ajax success
},error: function (msg)
{
alert(msg.message);
// I know I can give alert message here but.
//I don't want to give alert message here.
//I want to indicate user that the error occure whilt insert or update seperately.
}
});
You have to understand 2 things.
Form validation error and ajax error is different.
Ajax error - Is not validation error.
It means, suppose you call a function and there is php error in that function, or 404 error. At that time .error() will be called.
Ajax Success - No error(No syntax error).
So now you should write the logic in ajax success().
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
alert(response.message);// this will alert you the message which you have put in `json_encode()`
}
});
I'm trying to submit a HTML form to a server and it fails. I have several issues here.
I'm making a CORS request. It is a request by the client and I can't do anything about it.
( My app resides in localhost:3000/login.html & My server resides in http://localhost:3001/Login/auth )
The server in localhost:3001 accepts JSON requests and give back a JSON Responce.
(I have disabled the web-security in the browser to allow the CORS Requests)
So, I have created the HTML Form and tried to submit it with AJAX. Here you can see the code.
$(function(){
$("#loginform").submit(function(e){
e.preventDefault();
// var data = $("#loginform").serialize();
var data = {"username" : $("#username").val(),"password" : $("#password").val()};
alert(JSON.stringify(data));
$.ajax({
type: "POST",
url: "http://localhost:3001/Login/auth",
data: data,
contentType: "application/json",
crossDomain : true,
dataType: "json",
success: function(data) {
alert("success" + JSON.stringify(data));
},
error:function(data){
alert('error : '+JSON.stringify(data));
}
});
});
});
I have created the mock server in PHP (codeigniter). Here is the code for that.
public function auth(){
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$debug_export = var_export(file_get_contents('php://input'), true);
file_put_contents('new.txt',$debug_export . PHP_EOL, FILE_APPEND);
$user = 'admin';
$pass = 'admin';
$token = '1';
foreach($input_data as $key=>$value) {
if ($key === 'username') {
$this_user = $value;
}
if ($key === 'password') {
$this_password = $value;
}
}
if(isset($this_user) && isset($this_password)){
if($this_password === $pass && $this_user === $user){
echo json_encode(array('token'=>$token));
}else{
echo json_encode(array('token'=>'null'));
}
}
return 0;
}
When I submit a form, I get a response like this.
....
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/Login.php</p>
<p>Line Number: 77</p>
....
My 'new.txt' file has the log details as following.
''
'username=admin&password=admin'
I have really no idea what I'm doing wrong here. Can anyone help me out here?
I am using Codeigniter platform.
here is the ajax
$.ajax({
type: 'POST',
url: '/account/findpassword/exec',
data: {
'user_email': val
},
cache: false,
async: false,
success: function(result){
if(result == 'FALSE')
alert('Email does not exist.');
else if(result == 'TRUE')
alert('We sent a new password to your email.');
else
alert('There is an error.');
}
});
here is controller
function exec()
{
$email = $this->input->post('user_email');
$this->load->model('account/findpassword_model', 'findpass');
$u_data = $this->findpass->get_user_data($email);
if($u_data == FALSE)
{
$result = 'FALSE';
echo $result;
exit;
}
else
{
$this->findpass->set_user_newpass($u_data['u_id'], $new_pass);
echo 'TRUE';
}
}
here is model
function get_user_data($email)
{
$query = 'SELECT u_id, u_name FROM '.T_USER_ACCOUNT.' WHERE u_email = "'.$email.'"';
$result = $this->db->query($query)->result_array();
if(count($result) > 0)
return $result[0];
else
return FALSE;
}
It supposes to say 'email doesn't exist.' message if there is no email address.
If an email address is exist, it supposes to say the second message.
When I checked the db server, this controller and model commands worked.
However, it only says 'There is an error.' message for all types.
I checked million times, but don't know why it doesn't say right words.
As far as I can tell, you only ever intend to return TRUE or FALSE back to the client. If you're not matching either of them, the question is, what is the value of result in your success handler?
console.log(result);
in your success function should show you what you're getting back from the server, and from there is should be easy to figure out why you're not matching TRUE or FALSE.