Getting particular data from json_encode response - php

I have a file ajax.php which I am using to process data passed through jquery. I have this particular line of code called on successful form verification:
$.post("/ajax.php",{'request': 'emailLogin', 'loginmail': mail, 'loginpass': pass}, function(data) {} );
data in my case is: {"valid":true}{"auth":false}which is returned as a response from ajax.php, but I can't seem to file the correct way of defining "auth" and a variable with value "false".
My ajax.php is just checking if login and password are in the database and than echo json_encode(array('auth' => false)); or echo json_encode(array('auth' => true)); depending on the result. But it has also contain these lines:
if( isset($_POST['loginmail'])) {
$usermail = htmlspecialchars($_POST['loginmail']);
if (!filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$response = array('valid' => false, 'message' => 'You did not enter a correct email address.');
} else {
// All good
$response = array('valid' => true);
}
}
echo json_encode($response);

Don't echo json_encode($response) separately from the authentication result, you need to combine them. After you do the authentication, do:
$response['auth'] = $result_of_authentication;
then do
echo json_encode($response);
Once you do this, you should be able to access data.auth in Javascript. You should tell $.post that it's returning JSON:
$.post("/ajax.php",{
'request': 'emailLogin',
'loginmail': mail,
'loginpass': pass},
function(data) {
alert(data.auth);
},
"json");

Based on your PHP code you should be able to access the valid attribute like so:
$.post("/ajax.php",{'request': 'emailLogin', 'loginmail': mail, 'loginpass': pass}, function(data) {
var auth = data.valid;
if (auth) {
// do something!
} else {
// do something else!
}
});
Also there is a bug in your PHP code, you need to set up a default value for $response like so:
$response = array('valid' => false, 'message' => 'Email address is required');
if( isset($_POST['loginmail'])) {
$usermail = htmlspecialchars($_POST['loginmail']);
if (!filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$response = array('valid' => false, 'message' => 'You did not enter a correct email address.');
} else {
// All good
$response = array('valid' => true);
}
}
echo json_encode($response);
Otherwise if $_POST['loginmail'] is not set your app with throw an undefined variable exception
EDIT:
As Barmar pointed out in his answer, you should only echo a response back once time to avoid creating an invalid response. Any data you need should be sent back in a single array. I don't see you doing that in your PHP code but you do make mention of echoing another array ['auth' => false] which will not work the way you want it to

Related

PHP JSON redirect

I have a registration form,i want to redirect the user after register success (200) response to "location" => "home.php" or display errors on 400 (bad request) via json
I only know few basics of php so how should this look like
--> register.php ?
Combined with the examples below?
// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage
$errors = []; // collect errors in here
// do whatever you need to do with the $_POST / $_FILES data...
// capturing errors example...
if ($_POST['cpassword'] != $_POST['password']) {
$errors[] = "Passwords do not match!";
}
// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
if (count($errors)) {
header("Content-type: application/problem+json");
http_response_code(400);
exit(json_encode([
"message" => "Invalid form data or something",
"errors" => $errors
]));
}
header("Content-type: application/json");
exit(json_encode(["location" => "home.php"]));
}
// just a normal request, respond with redirects or HTML
// ...
foreach ($errors as $error) : ?>
<div class="error"><?= $error ?></div>
<?php endforeach;
The client can navigate to home on success or display error information otherwise
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {
accept: "application/json", // let PHP know what type of response we want
},
body
})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})
Please understand that im new and i have trouble resolving this,
a complete php answer would help & mark as resolved
You have no ok element in the JSON when it contains the redirect location. So change
exit(json_encode(["location" => "home.php"]));
to
exit(json_encode(["ok" => true, "location" => "home.php"]));

Why my echo json_encode($data) actually displays something on my pages and how to avoid that ( ajax/php form validation )

EDIT : I resolved my issue as I had a forgotten "require" operator messing up in the code. Sorry for not being aware of this earlier and thanks for your time.
I'm kinda new to web developpement and it's the second time only I use AJAX on a website.
It's just about a contact form validation using ajax and php client side validation.
Here is the problem : my code is actually working as expected for the validation part as everything works fine but I don't understand what I'm missing or doing wrong cause I get a line on top of my website (on each page, not only the contact page btw ) that I don't want obviously
I understand that it comes from my php code actually echoing my json_encode($data) but i don't get why and how to do to avoid this
Here is my code :
JS :
let resultMessage = $('#resultMessage')
let form = $('#contact_form')
form.submit(function(e){
$('span.error').empty()
e.preventDefault()
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if(response.success == true){
resultMessage.html('Message sent succesfully')
} else {
resultMessage.html('Fail')
if (response.errors.nom != null) {
$('#name_error').html(response.errors.nom);
}
if (response.errors.email != null) {
$('#email_error').html(response.errors.email);
}
if (response.errors.message != null) {
$('#message_error').html(response.errors.message);
}
}
},
error: function(){
console.log('error')
}
})
})
PHP
$success = false;
$errors = [];
// inputs validation
$errors = textInputValidation($errors, $name, 'name', 2, 50);
$errors = emailValidation($errors, $email, 'email');
$errors = textInputValidation($errors, $message, 'message', 10, 5000);
// if there is no error =>
if (count($errors) == 0) {
// code actualy sending the message
$success = true;
}
$data = array(
'errors' => $errors,
'success' => $success
);
header('Content-type:application/json');
echo json_encode($data);
So this code is working but the problem is that I get this line on top of my website
{"errors":{"name":"please fill this field","email":"please fill this field","message":"please fill this field"},"success":false}
It's on each page, not only the contact page, and it's not even changing when the validation is okay and there is no errors in the form or anywhere.
I'm probably missing something very basic, sorry for that.
Thanks for your help

Ionic 2 giving wrong response while making post request with php and mysql

I'm doing login from an app using php and mysql. When I put the URL on the browser with credentials appended with it, if the credentials are valid, it prints correct response like success:true. If credentials are not valid, it prints success:false. But when I put do ionic serve and do a login from the app, it prints success:true on console all the time, even if the credentials are not valid.
This is my IONIC-2 code:
var headers = new Headers();
headers.append("Accept",'application/json');
headers.append('Content-Type','application/json');
let options = new RequestOptions({headers:headers});
let postParams={
username: logincreds.username,
password: logincreds.password,
}
this.http.post("http://vaishalishaadi.com/AppLogin.php", postParams, options)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
});
Following code is of PHP:
header('Content-type: application/json');
if($check){
session_start();
$_SESSION['u_id'] = $check->u_id;
$_SESSION['u_name'] = $check->u_firstname;
$login_response=["success"=>"true"];
//print(json_encode($login_response));
//echo $check->u_id;
$data[] = array(
'pram'=$username
'id' => $check->u_id,
'fname' => $check->u_firstname,
'lname' => $check->u_lastname,
);
$result = "{'success':true, 'data':" . json_encode($data) . "}";
}
else{
$result = "{'success':false}";
}
echo($result);
Found Solution Over It
Just changed the way I was passing parameters and also removed 'options' argument from post request.
let params = new URLSearchParams();
params.append('username',logincreds.username);
params.append('password',logincreds.password);
this.http.post(url, params)
.subscribe(data=>{
console.log(postParams);
console.log(data);
/*if(data.json().success=="success"){
}
else{
} */
}, error => {
console.log(error);
})
Use URLSearchParams instead of using array to collect parameters being passed to server

Error Sending multiple json messages

I have an issue with json,
I have a function that send a json array
public function repondMessage($etat=true,$message)
{
$msg = array($etat,$message);
return '{"msg":'.json_encode($msg).'}';
}
and I get the Json array correctly when just one error sent
like this one:
if(a=1)
{
echo respondeMessage(false,'Error');
}
and jQuery:
console.log(data);
var resp = jQuery.parseJSON(data);
console.log(resp);
I Get the result which is fine for me:
{"msg":[false,"Error"]}
but when I get two messages at the same time , when I make a test like that
if(a=1)
{
echo respondeMessage(false,'Error');
}
if(b=1)
{
echo respondeMessage(false,'Error2');
}
this what happen : (I don't how to separete the two Json)
{"msg":[false,"Error"]}{"msg":[false,"Error2"]}
Uncaught SyntaxError: Unexpected token {
As per my comment, you cannot send multiple responses, instead add the responses to and array and send them all at once
public function respondMessage($message)
{
$msg = array('msg'=>$message);
//Always send the correct header
header('Content-Type: application/json');
echo json_encode($msg);
//and stop execution after sending the response - any further output is invalid
die();
}
$errors=[];
if($a=1)
{
$errors[]=[false=>'Error'];
}
if($b=1)
{
$errors[]=[false=>'Error2'];
}
if(!empty($errors){
respondMessage($errors);
}
By invoking your respond function you are responding multiple times. From your code, I believe the intent is to respond as follows:
{"msg":[false, "Error", "Error2"]}
If that is the case, my recommendation would be the following structure in your invoking context to provide those results:
$errors = [];
if($a=1){
$errors[] = 'Error';
}
if($b=1){
$errors[] = 'Error2';
}
if( count( $errors ) ){
respondMessage( true, $errors );
}

Cannot read property JQUERY array data

I'm trying to verify data.announce but i'm getting this error "Uncaught TypeError: Cannot read property 'announce' of null"
So here is my code
php file:
$return = array("msg" => "You'll recive an email with instructions!");
return json_encode($return);
jquery:
$("form[id='common-handler/register'] #submit").click(function(e) {
e.preventDefault();
if(locked == 1)
return false;
locked = 1;
var _form = $(this).closest('form').attr('id');
$.post("/"+_form, $(this).closest('form').serialize(), function(data) {
if(!isEmpty(data.announce))
$("#search_bar").html(data.msg).fadeIn("slow");
else
$("form[id='" + _form + "'] p.msg").text(data.msg);
}, "json");
});
function isEmpty(str) {
return (!str || 0 === str.length);
}
You cannot return data in a PHP file, unless you're including it somewhere in another PHP file, so you will need this to get your $.post(), working via JSON output:
echo json_encode(array("msg" => "You'll recive an email with instructions!"));
exit(0);
try this:
return $return = json_encode( array( "announce" => array("msg" => "You'll recive an email with instructions!") ) );
You don't have "announce" as one of the keys in the array you are returning, only "msg"
You want:
array("msg" => "You'll recive an email with instructions!", "announce"=>"My announcement");
Try changing:
if(!isEmpty(data.announce))
to:
if(null == data.announce)

Categories