Error Sending multiple json messages - php

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

Related

How to return validation errors back to swift from php or segue on success

I am using alamofire to post data to a php script which inserts data into a mysql database. This part is working fine but I have some validation on the server like checking for a valid email address for example. So, here is the swift code:
Alamofire.request(url!, method: .post, parameters: parameters)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
Here is the php that handles the inserting.
if($booking->create($conn)) {
$response['status'] = "200";
$response['message'] = "Success";
} else {
$response['status'] = "400";
$response['message'] = $booking->errors;
}
echo json_encode($response);
In swift, the response in console for failed validation is:
SUCCESS: {
message = (
"Invalid email address",
"Contact number required"
);
status = 400;
}
If there are no errors, I actually want to segue to another view controller and if there are errors, I want to display them in labels perhaps.
But, initially I just wanted to say if there are any errors, print them and if there are no errors, then segue. But if I try to put an if statement into the response I get an error.
case .success:
if response == "200" {
// segue
}
Binary operator '==' cannot be applied to operands of type
'DataResponse' and 'String'
I am hoping someone will show me a better way to do this but I have made some progress and it is working. My understanding of the Alamofire documentation is that if you get a response that means it will always be a 200 response no matter what your server sends back. So, the only way I could work around that was to parse the response as json using codable and then do something based on that data, like this:
Alamofire.request(url!, method: .post, parameters: parameters)
.responseJSON { response in
let data = response.data
let jsonDecoder = JSONDecoder()
do {
let serverResponse = try jsonDecoder.decode(PhpResponse.self, from: data!)
if serverResponse.status == "200" {
print("Success")
} else {
print(serverResponse.message)
}
} catch {
debugPrint(error.localizedDescription)
}
}
So, I post the data from swift to the server, do some form validation using php and then using php's json_encode, I send that back to swift in json format and do something based on that response.

Getting particular data from json_encode response

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

How to parse JSON object?

I'm try to get data from php web-service through the java-script.In my project error occurred when parse the JSON.
My PHP web service like this
<?php
header("Content-Type:application/json");
try {
if(!empty($_POST['mobile_number']))
{
$number = $_POST['mobile_number'];
$number = $_POST['user_type'];
deliver_response(200, "success", $number);
}
else
{
deliver_response(400, "no parameter", $number);
}
} catch (Exception $e) {
echo("message".$e->getMessage());
}
function deliver_response($status,$status_message,$data)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
//$response['data'] = $data;
$json_response = json_encode($response);
echo $json_response;
}
?>
And Im try to call above webservice like this
function logingAuth(){
var mnumber= $("#uname").val();
var utype= $("#pword").val();
try{
$.post("http://192.168.1.55/rest/signup.php", { mobile_number: mnumber,user_type:utype }, parseResults);
}
catch(err)
{
alert(err.message);
}
function parseResults(json){
var obj = jQuery.parseJSON(json);
alert(obj.status);
}
}
but this one not working because of var obj = jQuery.parseJSON(json); line.
If I call like this Its working
function parseResults(json){
alert(json.status);
}
What is this problem?
jQuery will automatically recognise the response type for you and act appropriately. In this case it will automatically deserialise the JSON to an object, so your call to parseJSON will cause an error as you are trying to deserialise an object. Simply remove that line:
function parseResults(json){
alert(json.status);
}

My JSON isn't being decoded by PHP

My PHP script is having a problem decoding the JSON that I'm sending to it via AJAX.
The jQuery:
$.ajax({
url : 'admin/modifyPermissions',
type : 'post',
data : {
'JSON' : JSON
},
success : function(msg){
if(msg == '1') {
alert('Permissions saved successfully');
} else {
alert(msg);
}
}
});
The PHP script:
public function modifyPermissions(){
if(isset($_POST['JSON']) && !empty($_POST['JSON'])) {
$json = json_decode($_POST['JSON'],true);
if($json !== NULL && $json !== FALSE) {
} elseif($json === NULL){
die('The string passed is not a valid JSON object and cannot be decoded.' . "\n" . $_POST['JSON']);
} else {
die('There was an error with the JSON string');
}
} else {
die('No JSON string was sent!');
}
}
The JSON that gets passed looks well formed to me:
{"martin":{3,5},"user2":{3,4,5}}
And PHP is returning null. I have PHP 5.2.7 installed on my server, so I can't use json_last_error()
{"martin":{3,5},"user2":{3,4,5}}
Not valid JSON. Valid JSON may look like this:
{"martin":[3,5],"user2":[3,4,5]}
You're not sending valid JSON, thus the error. Look at the comment #Matt added.
So that you won't reproduce the same error, before sending it over to PHP, don't try to make your own JSON string, use what JS offers you. Example:
var obj = { key: val, okey: oval }
objJSON = JSON.stringify(obj)
// objJSON is ALWAYS going to be valid json
Your JSON is invalid.
The {} notation denotes key/value pairs, where as you're using it as an array.
Your JSON should be,
{"martin":[3,5],"user2":[3,4,5]}

JSON and PHP issues

I'm new to JSON and AJAX, and as such have searched for solutions and experimented for a few days before resorting to asking here.
I am using AJAX to process a PHP page on submit. It is saving the information fine, but I also need the PHP page to pass back the inserted ID. Here is what I have so far.
In the success:
success: function(){
$('#popup_name img').remove();
$('#popup_name').html('Saved');
$('#fade , .popup_block').delay(2000).fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
$.getJSON(pathName, function(json){
alert('You are here');
alert("Json ID: " + json.id);
});
});
}
Then, the PHP script calls this method to insert the info and return the inserted id:
public static function doInsertQuery($sparamQuery="",$bparamAutoIncrement=true,$sparamDb="",$sparamTable=""){
//do the insert
$iReturn = 0;
$result = DbUtil::doQuery($sparamQuery);
if(!$result){
$iReturn = 0;
}
elseif(!$bparamAutoIncrement){
$iReturn = DbUtil::getInsertedId();
}
else{
$iReturn = DbUtil::getInsertedId();
}
//log the insert action
//if not a client logged in- cannot log to client db
if(Session::get_CurrentClientId() > 0){
if($sparamTable != LogLogin::table_LOGLOGINS()){
$oLog = new LogDbRequest();
$oLog->set_Type(LogDbRequest::enumTypeInsert);
$oLog->set_Request($sparamQuery);
$oLog->set_RowId($iReturn);
$oLog->set_TableName($sparamTable);
$oLog->set_Before("NULL");
$oLog->set_After(serialize(DbUtil::getRowCurrentValue($sparamDb,$sparamTable)));
$oLog->insertorupdate_LogDbRequest();
}
}
echo json_encode($iReturn);
return $iReturn;
}
I hope this makes sense. I'm at a complete loss here. Any help at all would be greatly appreciated!
~Mike~
It's simple really. The success function accepts an argument corresponding to the response from the server.
Client side:
$.ajax({
'url':'/path/to/script.php',
'dataType':'json',
'success':function(response){ //note the response argument
alert(response.id); //will alert the id
}
});
Server side:
<?php
//...previous stuff here...
$response = array('id' => $id); //where $id is the id to return to the client
header('Content-type: application/json'); //Set the right content-type header
echo json_encode($response); //Output array as JSON
?>

Categories