Android getting html response instead of json response | Value <br of type java.lang.String cannot be converted to JSONObject - java

Hi I am having a hard time figuring out what could be the cause of this error. until I tried to use the debug and found out that instead of a json response I am getting an html response. Please help me figure this out.
Check this java code :
from this point the error is triggered
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_SUBMIT_CLIENT, response -> {
Log.d(TAG, "Submission Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.d("Debug", jObj.toString());
boolean error = jObj.getBoolean("success");
if (!error) {
Toast.makeText(getContext(), "Client successfully submitted.", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
and also this is my hp script. I have it also test in some websites and found no error so I'm pretty sure that there is no problem here. I will still post it and leave it to you guys and If there is a problem please point it out.
require_once __DIR__ . '/DB_Connect.php';
$db = new DB_CONNECT();
$query = mysqli_query("INSERT INTO clientinformation(amountApplied, mop, term, lastname, firstname, middlename, birthdate, age, sex, status, marriageDate, noChildren, nationality, acr, address, cityMunicipality, province, telNo, years, offAddress, offCityMunicipality, offProvince, offTelNo, offYears, busAddress, busCityMunicipality, busProvince, busTelNo, busYears, productServiceOffered) VALUES('$amountApplied','$mop','$term','$lastname','$firstname','$middlename','$birthdate','$age','$sex','$status','$marriageDate','$noChildren','$nationality','$acr','$address','$cityMunicipality','$province','$telNo','$years','$offAddress','$offCityMunicipality','$offProvince','$offTelNo','$offYears','$busAddress','$busCityMunicipality','$busProvince','$busTelNo','$busYears','$productServiceOffered')");
$result = $mysqli->query($query);
if ($result) {
$response["success"] = 1;
$response["error_msg"] = "Application successfully made.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["error_msg"] = "Oops! An error occurred.";
echo json_encode($response);
}
and lastly here is my log
W/System.err: org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:112) W/System.err: at
org.json.JSONObject.(JSONObject.java:163)
at org.json.JSONObject.(JSONObject.java:176)
at info.androidhive.bottomnavigation.fragment.ApplicationFragment.lambda$submitClient$4$ApplicationFragment(ApplicationFragment.java:253)
at info.androidhive.bottomnavigation.fragment.-$$Lambda$ApplicationFragment$8jvL3OnFiDofc9nz50lAoSvp9ew.onResponse(Unknown
Source:4)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:873)

Related

Error when converting a string to JSONObject. What can it be caused by? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 14 hours ago.
Improve this question
When trying to convert a JSON string to a JSONObject in Java, a RuntimeError comes out
Here is my implementation of this in Java
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewError.setVisibility(View.GONE);
phone = String.valueOf(editTextPhone.getText());
password = String.valueOf(editTextPassword.getText());
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="http://192.168.0.113/microgatgets/login.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (status.equals("success")) {
Toast.makeText(MainActivity.this, "Авторизация успешна!", Toast.LENGTH_SHORT).show();
name = jsonObject.getString("name");
phone = jsonObject.getString("phone");
apiKey = jsonObject.getString("apiKey");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("logged", "true");
editor.putString("name", name);
editor.putString("phone", phone);
editor.putString("apiKey", apiKey);
editor.apply();
Intent intent = new Intent(getApplicationContext(), CardActivity.class);
startActivity(intent);
finish();
}
else {
textViewError.setText(message);
textViewError.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textViewError.setText(error.getLocalizedMessage());
textViewError.setVisibility(View.VISIBLE);
}
}){
protected Map<String, String> getParams(){
Map<String, String> paramV = new HashMap<>();
paramV.put("phone", phone);
paramV.put("password", password);
return paramV;
}
};
queue.add(stringRequest);
}
});
And here is the JSON string itself
{ "status": "failed", "message": "All fields are required" }
Stack trace
FATAL EXCEPTION: main
Process: com.example.microgadgets, PID: 25538
java.lang.RuntimeException: org.json.JSONException: Value <br of
java.lang.String cannot be converted to JSONObject at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:96)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:955)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:228)
at android.app.ActivityThread.main(ActivityThread.java:8689)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085)
Caused by: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:169)
at org.json.JSONObject.<init>(JSONObject.java:182)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:68)
at com.example.microgadgets.MainActivity$1$1.onResponse(MainActivity.java:64) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82) 
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29) 
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102) 
at android.os.Handler.handleCallback(Handler.java:955) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:228) 
at android.app.ActivityThread.main(ActivityThread.java:8689) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:613) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1085) 
I hope I added what I needed. If that's not the case, correct me, and I'm also writing all this because I just need to add some text. In response, I get a JSON string from the backend for my application

PHP if-else bodies both executing

I'm a beginner in PHP and i've got this code where both if and else parts are executed in the same "run". I know it's logically impossible but that's what I'm getting.
Here's my PHP Code:
<?php
require_once 'create_request_form.php';
$db = new create_request_form();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {
// receiving the post params
$rqTitle = $_POST['rqTitle'];
$rqMname = $_POST['rqMname'];
$rqUname = $_POST['rqUname'];
$rqBranch = $_POST['rqBranch'];
$rqText = $_POST['rqText'];
$rqMinPrice = $_POST['rqMinPrice'];
$rqMaxPrice = $_POST['rqMaxPrice'];
$rqImage = $_POST['rqImage'];
$rqCategory = $_POST['rqCategory'];
$rqDateTime = $_POST['rqDateTime'];
// check if there is a request with the same title
if ($db->checkReqTitle($rqTitle)) {
// Request already exists
$response["error"] = TRUE;
$response["error_msg"] = "Request already exists with the title: " . $rqTitle;
echo json_encode($response);
} else {
// create a new request
$request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);
if ($request) {
// request stored successfully
$response["error"] = FALSE;
$response["request"]["rqTitle"] = $request["rqTitle"];
$response["request"]["rqMname"] = $request["rqMname"];
$response["request"]["rqUname"] = $request["rqUname"];
$response["request"]["rqBranch"] = $request["rqBranch"];
$response["request"]["rqText"] = $request["rqText"];
$response["request"]["rqMinPrice"] = $request["rqMinPrice"];
$response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
$response["request"]["rqImage"] = $request["rqImage"];
$response["request"]["rqCategory"] = $request["rqCategory"];
$response["request"]["rqDateTime"] = $request["rqDateTime"];
echo json_encode($response);
} else {
// request failed to store
$response["error"] = TRUE;
$response["error_msg"] = "An error occurred while creating the request. Please try again.";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter is missing!";
echo json_encode($response);
}
?>
The required behavior (storing data in the database) is all performed well but the $response I'm getting is the error string i've assigned to when a request title already exists instead of the JSON formatted array of the stored request (Both if and else bodies are executed but i get the result of if body as a response).
A screenshot of the $response using Postman to send the request:
A screenshot from my Samsung Galaxy Note 3:
I'm also using Galaxy Note 4 for testing and it just shows me a blank Toast message and doesn't start the intent(doesn't move to home screen).
So far the only possible explanation is that the script is being executed twice, however I can't find anywhere that called it a second time.
This is the java code responsible for sending a request with required paramters to the php script above.
private void storeRequest(final String rTitle, final String rMname, final String rUname,
final String rBranch, final String rText, final String rMinPrice,
final String rMaxPrice, final String imagePath, final String rCategory) {
// Tag used to cancel the request
String cancel_req_tag = "request";
//A progress dialog message to let the user know they are being registered
progressDialog.setMessage("Please wait while we add your request...");
showDialog();
//creating a StringRequest to send the registration info to the script
// at the server for processing
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REQUEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Request Response: " + response.toString());
hideDialog();
try { //json objects must be surrounded by try catch statement
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
// Launch home activity
Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(CreateRequestActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("rqTitle", rTitle);
params.put("rqText", rText);
params.put("rqMname", rMname);
params.put("rqUname", rUname);
params.put("rqBranch", rBranch);
params.put("rqMinPrice", rMinPrice);
params.put("rqMaxPrice", rMaxPrice);
params.put("rqImage", imagePath);
params.put("rqCategory", rCategory);
params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
Any ideas?
Thanks in advance!
So turns out the problem stemmed from the Java code and not PHP (poor PHP ;P). More accurately, Volley requests have a problem with request timeouts, especially when sending requests using POST method.
So what worked for me was adding this line right before adding the request to the queue:
strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));
*Replace strReq with your request name. Basically what this line does is that it prevents volley from sending a duplicate request when the first request takes too long.
The original & more datailed answer:
The DefaultRetryPolicy.class's hasAttemptRemaining() class looks like this:
protected boolean hasAttemptRemaining() {
return this.mCurrentRetryCount <= this.mMaxNumRetries;
}
From what I can see, setting the maxNumRetries to 0 will still make that return true if it hasn't done a retry yet.
I fixed it with a
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0);
Source: Android Volley makes 2 requests to the server when retry policy is set to 0

make NodeJS function synchronus? sends json response before querying database

I am making a login/register android app UI with nodejs as the backend language. Whats happening is that whenever I click the register button, it sends the json response before querying the database (select statement to check if username exists) causing the android app to get the wrong response which causes me to click the button twice to register the correct response. For instance lets say their is a username called test in the database and I try to sign up using the username test, it will tell me that the username is already taken and if erase test and enter lets say 'bob' which does not exist in the database it still says the username is already taken even though it is not but when I click the register button again it will register the user. I am assuming this is happening because it is async(it sends the json response while or before querying the database). How can I make this synchronus or is there another way to fix this?
server file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
//connection
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database : "androidtest"
});
//use json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//declare variables to hold values entered by the user
var name;
var username;
var password;
var age;
//boolean array to let frontend know what is going on
var response;
app.post('/', function(req, res) {
//retrieve variables
username = req.body.username;
name = req.body.name;
age = req.body.age;
password = req.body.password;
//query database
//check if username is taken
var select = "SELECT * FROM users WHERE username = ? LIMIT 1";
con.query(select, [username], function (err, results) {
if (err) throw err;
//if username is taken send json string 'exists' to android app
if(results.length) {
response = {"exists" : "true"};
//if username is available send string 'success' and add the user to the database
} else {
var add = "INSERT INTO users (name, username, age, password) VALUES (?, ?, ?, ?)";
response = {"success" : "true"};
con.query(add, [name, username, age, password]);
if (err) throw err;
console.log('row inserted');
}
});
//send json
res.json(response);
//prevents the functions from being executed more than once
res.end('/');
});
//listen on port 3000
app.listen(3000);
android app java:
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUserName.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean exists = jsonResponse.getBoolean("exists");
String exists = jsonResponse.getString("exists");
if (exists.matches("true")) {
Toast toast = Toast.makeText(getApplicationContext(), "username already exists", Toast.LENGTH_SHORT);
toast.show();
}
} catch(Exception e) {
e.printStackTrace();
}
try {
JSONObject jsonResponse = new JSONObject(response);
//Boolean success = jsonResponse.getBoolean("success");
String success = jsonResponse.getString("success");
if (success.matches("true")) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
You have to put
res.json(...);
res.end('/');
after the closing bracker of the following line (after & outside the else block):
console.log('row inserted');
then it first gets executed when to query has finished.

Not able to insert record to MySQL, but showing no error

Task: sync records from android sqlite to mysql.
Problem: mysql/php is not inserting data into my table in mysql. But no errors were shown.
DB_Connect.php:
<?php
class DB_Connect {
// constructor
function __construct(){
}
// destructor
function __destruct(){
}
// connecting to database
public function connect(){
require_once 'config.php'; // defined DB_HOST,DB_USER,DB_PASSWORD here
// connecting to mysql
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
// selecting database
mysqli_select_db($con,"heart");
// return database handler
return $con;
}
// closing database connection
public function close(){
mysqli_close($this->connect());
}
}
?>
DB_Operations.php:
<?php
class DB_Operations {
private $db;
public $last_id;
public $error;
public $error_conn;
public $error_no;
// constructor
function __construct(){
require 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct(){
}
// Storing new doctor
public function storeDoctor($_id,$firstName,$lastName,$specialization,$licenseNumber,$clinicAddress,$email,$contactNum,$username,$password,$aboutMe){
$result = mysqli_query($this->db->connect(),"INSERT INTO doctor(_id,first_name,last_name,specialization,license_number,clinic_address,email,contact_number,username,password,about_me) VALUES('$_id','$firstName','$lastName','$specialization','$licenseNumber','$clinicAddress','$email','$contactNum','$username','$password','$aboutMe')");
if (mysqli_connect_errno()){
$this->error_conn = mysqli_connect_error();
}
if(!$result){
if(mysqli_errno($this->db->connect()) == 1062){
// duplicate key - primary key violation
return true;
} else{
// for other reasons
$this->error = mysqli_error($this->db->connect());
$this->error_no = mysqli_errno($this->db->connect());
return false;
}
} else{
$this->last_id = mysqli_insert_id($this->db->connect());
return true;
}
}
// getters
public function getError(){
return $this->error;
}
public function getError_no(){
return $this->error_no;
}
public function getError_conn(){
return $this->error_conn;
}
...
insertuser.php:
<?php
include 'DB_Operations.php';
// create object for DB_Operations class
$db = new DB_Operations();
// get JSON posted by Android Application
$json = $_POST["doctorsJSON"];
// remove slashes
if(get_magic_quotes_gpc()){
$json = stripslashes($json);
}
// decode JSON into Array
$data = json_decode($json);
// util arrays to create response JSON
$a = array();
$b = array();
// loop through an array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data); $i++){
// store doctor into MySQL DB
$res = $db->storeDoctor($data[$i]->_id,$data[$i]->first_name,$data[$i]->last_name,$data[$i]->specialization,$data[$i]->license_number,$data[$i]->clinic_address,$data[$i]->email,$data[$i]->contact_number,$data[$i]->username,$data[$i]->password,$data[$i]->about_me);
// based on insertion, create JSON response
$b["local_id"] = $data[$i]->_id;
if($res){
$b["server_id"] = $db->last_id;
$b["status"] = 'yes';
}else{
$b["status"] = 'no';
$b["err_no"] = $db->getError_no();
$b["error"] = $db->getError();
$b["error_conn"] = $db->getError_conn();
}
array_push($a,$b);
}
// post JSON response back to Android Application
echo json_encode($a);
?>
I have a function in java which syncs the sqlite data to mysql:
public void syncSQLiteToMySQL(Context context,String selectQuery){
dop = new DatabaseOperations(context);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String,String>> doctorList = new ArrayList<HashMap<String,String>>();
doctorList = dop.getAllDoctors();
if(doctorList.size()!=0){
String json = dop.composeJSONfromSQLite(selectQuery);
params.put("doctorsJSON", json);
Log.i("json to pass", json);
client.post("http://"+ip+":8080/changed_server_name/insertuser.php",params ,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.e("client response",response);
try {
JSONArray arr = new JSONArray(response);
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
// did something with json response here
dop.updateSyncStatus(obj.getString("local_id"),obj.getString("status"));
}
message = "DB Sync completed!";
} catch (JSONException e) {
message = "Error Occured [Server's JSON response might be invalid]!";
Log.e("JSONException",e.getMessage());
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
if(statusCode == 404){
message = "Requested resource not found";
}else if(statusCode == 500){
message = "Something went wrong at server end";
}else{
message = "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]";
Log.e("sync post failure",error.toString());
}
}
});
}
}
So, here's the response:
[{"local_id":"0","status":"no","err_no":0,"error":"","error_conn":null}]
The JSON works fine. No problem with it. I have checked and it passes correct data. Just the PHP and MySQL side. Somehow, I couldn't find the error to this code. There is no error message, error number is 0, and there was no error in connecting to DB. But the query in storeDoctor() returns false. How could this be? I have been reading about this problem on this site and others, but I have not really found something that's close to my problem.
Please enlighten me. Your help would really be appreciated. Thanks in advance.
Edit: I also tried mysqli_ping($this->db->connect()); and it returns true which means the connection is okay. So, what really is this something that makes the query fail?
Did you try using error_reporting(E_ALL);
Also inside the constructor you used
$this->db->connect();
And then in the store you used
$result = mysqli_query($this->db->connect(),
Can you post the code for connect

Decode JSON Object in php

I sending a JSON object from my android app to my web service. (using volley). Here is a part of my code.
private void sendtoDB(final String ngno){
String tag_string_req = "req_save_to_db";
final JSONObject JSONdates = new JSONObject();
for(int i = 0 ; i < dates.size() ; i++){
try{
JSONdates.put("date", dates.get(i));
}catch (Exception e){
e.printStackTrace();
}
}
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_UpdateDates, new Response.Listener<String>() {
#Override
public void onResponse(String response) { ....}
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("ngno", ngno);
params.put("JSON", JSONdates.toString());
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
dates array contains several date Strings that i want to store in my Database. Below is the output of my JSON object (JSONdates).
{"dates":["Wed Mar 30 00:00:00 GMT+05:30 2016","Thu Mar 31 00:00:00 GMT+05:30 2016"]}
My question is how do i receive this JSON object in my php and how to decode it properly and get each date value to a variable so i can execute sql query accordingly.
This is my php code.
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if(isset($_POST['ngno']) && isset($_POST['JSON']) ){
$ngno = $_POST['ngno'];
$json = json_decode($_POST['JSON'], true);
foreach($json){
$date = $json['date'];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Dates are missing!";
echo json_encode($response);
}
?>
updateDates function
public function updateDates($ngno, $date){
$stmt = $this->conn->prepare("INSERT INTO datepicker(ngno, date) VALUES($ngno, $date)");
$result = $stmt->execute();
$stmt->close();
}
I get a syntax error near forearch($json) unexcepted ')'.
Any help would be much appreciated.
EDIT 1:
changed the foreach loop in php code as following
foreach($dates as $date){
error_log[$date];
$job = $db->updateDates($ngno, $date);
if($job){
$response["error"] = FALSE;
echo json_encode($response);
}
else{
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in Updating!";
echo json_encode($response);
}
}
But now it says, PHP Warning: Invalid argument supplied for foreach()
Any help Guys? Im new to programming and not sure how to get it fixed.
change foreach($json){ to foreach($json['dates'] as $date){and delete the line $date = $json['date'];. See php manual about foreach for more info about the foreach syntax

Categories