JSONP PHP Array Empty - java

im trying to get data via JSONP from my Webpage with a php script :
//connection and query above
...
while($r=mysqli_fetch_array($result)){
//Add the fetched vale to $json array
$json[] = $r;
// Content type
header("Content-type: application/json");
echo "$callback({email: 'Message from Server.php'});";
}
// Content type
header("Content-type: application/json");
//JSONP - Make it as JSONP object
echo $_GET['callback']."(".json_encode($json).")";
my echo "$callback({email: 'Message from Server.php'});"; <--- works
but my
echo $_GET['callback']."(".json_encode($json).")"; <--- returns null
when i call the script on my webpage like "page/callback.php"
i get following outputs in my Browser :
({email: 'Message from Server.php'});([{"0":"3","ID":"3","1":"dome","username":"dome","2":"vjvhrOWZYTq3qbrYfoE13A==","passwort":"vjvhrOWZYTq3qbrYfoE13A==","3":"mii#googlemail.com","email":"mii#googlemail.com","4":"0","active":"0","5":"hu","loc":"hu"}]
)
It contains -> "[" and "]"
my Java script is GWT :
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.requestObject(URL.encode("http://webpage/callback.php?callback=test_clbk"), new AsyncCallback<JSONreceiver>() {
public void onFailure(Throwable throwable) {
System.out.println(throwable.getMessage());
}
#SuppressWarnings("unused")
public void onSuccess(JSONreceiver result) {
System.out.println(result.getResult());
}
});

You still do not have any answer.
Here is one solution :
1) Remove EVERY SINGLE echo / print / var_dump.
2) Initiate the json class with a callback
3) Forge your JSON with Simple JSON for PHP
4) Send your json at the end of the file
The results :
<?php
include('../includes/json.php');
// Set a callback
$json = new json('callback', 'mycallback');
// Forge your data
$json->add('email', 'message sent from Server.php');
while($r=mysqli_fetch_array($result)){
$answer[] = $r;
}
// Forge your data
$json->add('data', $answer);
$json->add('status', '200');
// Send
$json->send();
?>

Related

curl post not working to send json data using REST API developed in java

I am trying to send json data from my php file using a REST API which is developed in java to store data into database.
This is my code.
$p_name = $_POST['p_name'];
$tick = $_POST['tick'];
$url3 = 'http://myipaddress:port/myurl/';
$cookie_file =dirname(__FILE__).'\cookiefile.txt';
$form_data = array(
'p_name' => $p_name,
'tick' => $tick
);
$str = json_encode($form_data);
$ch = curl_init($url3);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch,CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: '.strlen($str)
) );
// set cookie
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
// use cookie
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
$response3 = curl_exec($ch);
}
$responseHTTP = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result3 = json_decode($response3);
var_dump($responseHTTP);
This is the code of java section.
#POST
#Path("/mypath")
#Produces("application/json")
#Consumes("application/json")
public String savePortFolioRecords(MyObject list_myobject){
String return_string=null;
try{
mydataManager dataManager=new mydataManager();
dataManager.setup();
dataManager.insertRecordsApi(list_myobject);
dataManager.exit();
Gson gson=new Gson();
return_string=gson.toJson("successfully insert the data");
}catch (Exception e) {
// TODO: handle exception
System.out.println("Giving Exception due to: "+e);
}
return return_string;
}
While i am testing the API using postman, it works perfectly and insert data into database, but in response box shows a text like Unexpected 's' .
But while i am trying to send value from my php file using curl, it does not store data into database. I don't understand whether my function in php
does not send data or can't receive json data in java section.
Moreover, when i am using CURLINFO_HTTP_CODE and print the corresponding response using var_dump, it shows int(404).
I have followed these links to solve my problem, but can't get any solution.
cuRL returnin 404 error
https://stackoverflow.com/questions/17476828/curl-returns-404-while-the-page-is-found-in-browser
https://davidwalsh.name/curl-post
Can any one tell me what's the problem here? I can't understand whether it is problem in my php file or in the java file.

How to extract data from a JSON array to variables and pass variables to a PHP function

I have a Java Program that sends a HTTP POST request to a PHP file. I need the PHP script to extract the JSON data to some variables and call a PHP function with those variables (parameters). Please find the PHP code below.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"), true);
var_export($data);
}
else
{
var_export($_SERVER['REQUEST_METHOD']);
}
?>
The JSON Object created in Java
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
Please help me understand how to extract the JSON array data to variables And how to make the call.
Once you've run json_decode(), $data is just a "normal" php array with "normal" php values in it.
So, e.g.
/*
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
=>
*/
// $input = file_get_contents("php://input");
$input = '{"name":"Dash","num":100,"balance":1000.21}';
$data = json_decode($input, true);
$response = array(
'name_rev' => strrev($data['name']),
'num_mod_17' => $data['num'] % 17,
'balance_mul_2' => $data['balance'] * 2
);
echo json_encode($response, JSON_PRETTY_PRINT); // you might want to get rid off JSON_PRETTY_PRINT in production code
prints
{
"name_rev": "hsaD",
"num_mod_17": 15,
"balance_mul_2": 2000.42
}
two more tips:
You should test whether $data contains all the elements you expect, before accessing them, see http://docs.php.net/isset , http://docs.php.net/filter et al
a java Double() called balance. A java double is a 64-bit IEEE 754 floating point. And you might hit at one point (if not the range than) the precision limit, see What is the best data type to use for money in java app?

Error parsing JSON Object from PHP web service

I seem to be getting an incomplete JSON object from my PHP web service. My PHP codes are as follows:
<?php
define('IEM_PATH', '../admin/com');
require_once('../admin/includes/config.php');
require_once('../admin/com/lib/IEM.class.php');
require_once ('../admin/com/lib/IEM/DBFACTORY.class.php');
require_once ('../admin/com/lib/IEM/baseAPI.class.php');
require_once ('../admin/com/lib/API/USERS.class.php');
require_once ('../admin/com/lib/IEM/baseRecord.class.php');
require_once ('../admin/com/lib/record/Users.class.php');
function GetLists($userid = 0, $getUnconfirmedCount = false) {
$userid = $_REQUEST['userID'];
if (!$userid) {
trigger_error('User object has no user id as parameter.', E_USER_NOTICE);
return false;
}
if (!$userid) {
$userid = $this->userid;
}
require_once('../admin/functions/api/lists.php');
$listapi = new Lists_API();
$returnA = $listapi->GetListByUserID($userid, $getUnconfirmedCount);
$returnResult1 = array();
foreach ($returnA as $key => $value) {
//$lists[] = $key;
$returnResult["contactList"][] = array("listID" => $returnA[$key]['listid'], "name" => $returnA[$key]['name']);
}
$returnResult["success"] = 1;
echo json_encode($returnResult);
}
GetLists();
However when I try to retrieve the results my logcat only shows:
E/JSON Parser: Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
W/System.err: org.json.JSONException: No value for success
By doing a logging, my android returns my JSON object as follows
D/Returned JSON: {"androidid":"1"}
from these codes
// getting JSON response from PHP web service
JSONObject returnedJSONObj = listsJSONParser.makeHttpRequest(Constant.URL
+ "RetrieveList.php", "GET", params);
Log.d("Returned JSON ", String.valueOf(returnedJSONObj));
success = returnedJSONObj.getInt("success");
I don't understand why there is no value for success when my PHP does return a JSON Array as well as the success value according to the code, but the android studio java codes does not detect these values in the JSON object. What am I doing wrong here?
you should modify your android code
success = returnedJSONObj.getInt("success");
to
success = returnedJSONObj.getInt("androidid");
The problem is that there is a problem with your php file, so instead of returning a JSON object, it returns a string with the error.
You need to make sure you are sending the correct POST or GET values to the URL if you are or you check for database errors. try logging the inputstream coming from the php server to see the full error it is sending

java.lang.Integer cannot be converted to JSONObject

I am fetching status from PHP in JSON format, but always getting:
org.json.JSONException: Value 43 of type java.lang.Integer cannot be converted to JSONObject
My way of reading result from JSON
int strUserID;
......
strUserID = jsonObject.getInt("UserID");
And in php i am using:
$user_id = mysql_insert_id();
echo $user_id;
if(!$objQuery)
{
$arr['StatusID'] = "0"; // unable to create user
}
else
{
$arr['StatusID'] = "1"; // user created successfully
$arr['UserID'] = $user_id; // passing user id to android app
}
JSON sample on web:
46{"StatusID":"1","UserID":46}
But on Android side not getting data into json format, because facing exception
may i know where i am doing mistake ?
While returning the data from PHP you should encode it in JSON.
use below function
echo json_encode($arr);
In your php file remove
echo $user_id;
and use this after your else condition
echo json_encode($arr);

java spring boot pass array of strings as parameters inside json for ajax call

In my application I need to pass an array of parameters form client side to server side. I tried the following code but its not working.I need to get data from checkbox list and pass it to server side.
My code for the client side
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "GET",
url : '/rest/my/rest/mysql/controller',
data : {
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
monitoring : monitoring,
nonMonitoring: nonMonitoring,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
if(data=='success'){
// loadChannels();
location.reload();
}else{
alert("failed to upload");
}
}
});
})
My code for the server side.
#RequestMapping("/rest/my/rest/mysql/controller")
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength,#RequestParam(value="monitoring",required=true)List<String> monitoring,#RequestParam(value="nonMonitoring",required=true)List<String> nonMonitoring){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
System.out.println("Monitoring=>" +monitoring);
System.out.println("Monitoring=>" +nonMonitoring);
Somehow this is not working.What is the error in this? Please help
In Request parameter change List to array
i.e.
#RequestParam(value="monitoring",required=true) String[] monitoring, #RequestParam(value="nonMonitoring",required=true) String[] nonMonitoring

Categories

Resources