How to parse JSON object? - php

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

Related

How to submit data from an Angular2 form (along with image) to PHP using formdata method?

The form has text input and file-input. I studied the tutorial from here.
This is my add.component.ts file:-
import { AdminPage } from '../../../_models/admin.page.model';
import { AdminPageService } from '../../../_admin_service/admin.page';
import { ImageUploadService } from '../../../_common_service/image.upload';
export class AddComponent implements OnInit, AfterViewInit {
.............
.............
adminPageModel = new AdminPage('', '', '', '','');
constructor(private route: ActivatedRoute,
private router: Router,
private _adminPage: AdminPageService,
private _imageUpload: ImageUploadService,
fb: FormBuilder,
private _flashMessagesService: FlashMessagesService) {
this.addPageFormGroup = fb.group({
'title' : [null, Validators.compose([Validators.required])],
'meta_keyword': [null, Validators.required],
'meta_description': [null, Validators.required],
'image':[],
'desc': [null, Validators.required]
});
}
formImageUpload(event){
this._imageUpload.onFileChange(event,this.addPageFormGroup);
}
submitAddPage(value:any){
this.addPageFormGroup.get('desc').setValue($('.Editor-editor').html());
const adminPageModule = this._imageUpload.prepareSave(this.addPageFormGroup);
this._adminPage.postAdminPageAdd(adminPageModule).subscribe(
data => {
this.responseStatus = data;
if(this.responseStatus.status == 1)
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 2000 });
}
else
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
}
},
err => {
console.log(err)
},
() => {}
);
this.status = true;
}
}
This is the image.upload.ts service file, where we are setting the formdata from the form:-
#Injectable()
export class ImageUploadService {
constructor() {}
onFileChange(event, formHasImage:any) {
if(event.target.files.length > 0) {
let file = event.target.files[0];
formHasImage.get('image').setValue(file);
}
}
prepareSave(formHasImage): any {
let input = new FormData();
input.append('image', formHasImage.get('image').value);
input.append('title', formHasImage.get('title').value);
input.append('desc', formHasImage.get('desc').value);
input.append('meta_keyword', formHasImage.get('meta_keyword').value);
input.append('meta_description', formHasImage.get('meta_description').value);
console.log(input);
return input;
}
}
This is the admin.page.ts service file where we are hitting the API. This is made by referring to this answer here.
#Injectable()
export class AdminPageService {
http : Http;
actionUrl : string;
admin_page_add_url: string;
postAdminPageAddData: AdminPage;
adminPageAddResponse:Object= [];
constructor(public _http: Http) {
this.http = _http;
this.admin_page_add_url = 'http://localhost/angproject/phpscript/adminpage2.php';
}
// The form Data is being sent as parameter
postAdminPageAdd(postAdminPageAddFormData: any) {
let headers = new Headers();
headers.append('enctype', 'multipart/form-data');
headers.append('Accept', 'application/json');
this.actionUrl = this.admin_page_add_url;
return this.http.post(this.actionUrl,
{ postAdminPageAddFormData },
{ headers: headers })
.map(res => res.json()).share();
}
}
This is the server side php file where we are sending the data. This is made on the accepted answer here:-
<?php
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: Content-Type, enctype");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header('Content-Type: application/json; charset=utf-8');
header('enctype: multipart/form-data');
include('connection.php');
$error = array();
if(isset($_FILES['image']))
{
$image = 'Image Exists';
}
else
{
$error[] = "Image was not entered";
$image = '';
}
if(isset($_POST['title']) && !empty($_POST['title']))
$title = $_POST['title'];
else
$error[] = "Title was not entered";
if(empty($error))
{
$response['status'] = 1;
$response['message'] = $image;
$response['error'] = $conn->error;
}
else
{
$response['status'] = 0;
$response['message'] = "Parameter missing";
$response['error'] = $error;
}
$respond = json_encode($response);
echo $respond;
exit;
?>
My issue is, I am always getting this json response:-
{
"status": 0,
"message": "Parameter missing",
"error": [
"Image was not entered",
"Title was not entered"
]
}
It seems like the formdata aren't being sent to the server end. What am I doing wrong here? Mind it, I have other process too, to submit the form. But in that case, I can send data to server successfully by not using formdata and hence, I can't implement file-upload in that method.
Note: When I do console.log(input), I get this:-
You have two problems with your AdminPageService's postAdminPageAdd method.
First, Headers.append() does not mutate the Headers object, it returns a new Headers object with the original headers and the new one. So you need to do something like:
let headers = new Headers();
headers = headers.append('enctype', 'multipart/form-data');
headers = headers.append('Accept', 'application/json');
Second, the FormData object in the post should not be surrounded with curly brackets - it should work if you do:
return this.http.post(
this.actionUrl,
postAdminPageAddFormData,
{ headers: headers }
).map(res => res.json()).share();
Try appending file directly to FormData object.
#Injectable()
export class ImageUploadService {
file: File;
constructor() {}
onFileChange(event, formHasImage:any) {
if(event.target.files.length > 0) {
file = event.target.files[0];
}
}
prepareSave(formHasImage): any {
let input = new FormData();
input.append('image', this.file);
input.append('title', formHasImage.get('title').value);
input.append('desc', formHasImage.get('desc').value);
input.append('meta_keyword', formHasImage.get('meta_keyword').value);
input.append('meta_description', formHasImage.get('meta_description').value);
console.log(input);
return input;
}
}

AngularJS $resource can't deserialized array into an object

I'm working with php Tonic and AngularJS. So I have angular that call a rest resource. The code of the rest is like this:
/**
* #method GET
*/
public function getData(){
$response = new Response();
$response->code = Response::OK;
$response->body = array("one","two");
return $response;
}
On backend, code return a Response object with an array in the body.
From angular I use $resource service to call backend:
return {
getBackData : function(){
var call = $resource('/table_animation_back/comunication');
call.get(function(data){
console.log(data);
});
}
}
The result of console.log is this:
Resource {0: "A", 1: "r", 2: "r", 3: "a", 4: "y", $promise: d, $resolved: true}0: "A"1: "r"2: "r"3: "a"4: "y"$promise: d$resolved: true__proto__: Resource
I tried to use:
call.query(function(){...})
but Response in php is an object and not an array, so in this way I got a javascript error.
I can't access to the array.
Where wrong?
You need to serialize your array to JSON before sending to client:
public function getData(){
$response = new Response();
$response->code = Response::OK;
// Encode the response:
$response->body = json_encode(array("one","two"));
return $response;
}
I think that you forgot encode data before return it to client. In the server-side, it should be:
$response->body = json_encode(array("one","two"));
return $response;
In client, I think that we should use $q.defer in this case. For example:
angular.module('YourApp').factory('Comunication', function($http, $q) {
return {
get: function(token){
var deferred = $q.defer();
var url = '/table_animation_back/comunication';
$http({
method: 'GET',
url: url
}).success(function(data) {
deferred.resolve(data);
}).error(deferred.reject);
return deferred.promise;
}
};
});

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

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

can't access php with ajax

I've got the Problem that I can't reach my php file with my $.ajax() call. I always get
a jqXHR.status of 0. This is my code:
function with $.ajax() call:
function updateClubInfo(text) {
var data = text;
$.ajax({
type: 'POST',
dataType: 'json',
url: '../php/updateInfo.php',
data: {
infoText: data,
action: "update"
},
success: function() {
// do nothing
alert('success');
},
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.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}
I've build this request similar to others in my project, but this one is the only one
that doesn't work. Here the PHP file I want to reach:
php code snippet (updateInfo.php):
<?php
$action = $_POST['action'];
$text = $_POST['data'];
myLog($action);
myLog($text);
echo "hello";
/*
* Writes entry in Logfile
*/
function myLog($data) {
$text = #file_get_contents('log.txt');
$text = $text . "\n" . $data;
#file_put_contents('log.txt', $text);
}
?>
When I try to reach this PHP file in the URI the echo is outputted. So I think the
Problem should be in the ajax call.
Does someone has an Idea what I'm doing wrong? I'm grateful for any help.
Thx alot for your help
Cris
You have a copy/paste error in your PHP file. It should be :
$action = $_POST['action'];
$text = $_POST['infoText'];//instead of $_POST['data']
UPDATE
Because your AJAX request asks for JSON data, but you are writing only text in your PHP file. Therefore, the AJAX request interprets the answer as void, then HTTP status = 0
Solution
dataType option is not about the type of data you are sending to the server, but the type or data you are expecting back from the server. Change dataType: 'json', to dataType: 'html', or symply remove it to let JQuery chose the appropriate mode.
$action = $_POST['action'];
$text = $_POST['data'];
myLog($action);
myLog($text);
$arr[] ='hello';
echo json_encode($arr);
/*
* Writes entry in Logfile
*/
function myLog($data) {
$text = #file_get_contents('log.txt');
$text = $text . "\n" . $data;
#file_put_contents('log.txt', $text);
}
json data fetch only in array

Categories