I want to invoke a php program from javascript and send relevant info by $.getJSON from the js side to be processed to the php module through $_GET.
Thankful for any helpful suggestions
Cheers, Nisse
I start out with functioning legacy code looking like:
onestr='?q=valuezero';
$.getJSON(onestr ,function() {
console.log("Be here now:");
}
)
On the server side, I get _GET:
{"view":"app","q":"valuezero"}
which is what I want.
I then want to augment onestr with the content of two objects:
clientside (js):
my_obj1={property1:"value1",property2:"value2",propery3:"value3"};
my_obj2={property4: "value4", property5: "value5", propery6: "value6"};
scr_str1=JSON.stringify(my_obj1).substr(1).slice(0,-1);
scr_str2=JSON.stringify(my_obj2).substr(1).slice(0,-1);
//the substr and slice breaks everything down to one level
//
onestr='?q=valuezero'+'&'+scr_str1+'&'+scr_str2;
$.getJSON(onestr ,function() {
console.log("Be here now");
}
)
On the server side, I now get :
_GET: {"view":"app","q":"valuezero","\"property1\":\"value1\",\"property2\":\"value2\",\"propery3\":\"value3\"":"","\"property4\":\"value4\",\"property5\":\"value5\",\"propery6\":\"value6\"":""}
whereas the desired result would have been:
{"view":"app","q":"valuezero","property1":"value1","property2":"value2","propery3":"value3","property4":"value4","property5":"value5","propery6":"value6"}
It initially looked trivial to append something like .replace(/\\/g,'').replace(/'""'/g,'"'); to the def of scr_str1 and scr_str2 but then I realized that the backstrokes appear on the server side; also tried replacer function in stringify and other stuff but I just cant transfer _GET to an associative array of the desired structure.
If you need to compose an url having as GET parameters the property values coming from an object, this could be the strategy to get there:
Warning! I'm not escaping the property names/values that may need to pass through encodeURIComponent
my_obj1 = {property1:"value1",property2:"value2",propery3:"value3"};
my_obj2 = {property4: "value4", property5: "value5", propery6: "value6"};
const params = {...my_obj1, ...my_obj2};
let url = buildUrl("https://host.com/path/to/action", params);
console.log(url);
function buildUrl(baseurl, params){
const queryParams = Object.entries(params)
.map(([key, value]) => `${key}=${value}`)
.join('&');
return `${baseurl}?${queryParams}`;
}
I'm currently using jQuery's $.get() to process IDs entered in a text field with a database. It currently works quite well, especially the PHP which can handle multiple comma-separated entries.
The issue I'm having is with jQuery; more specifically, JSON parsing. The PHP file returns an array of arrays, which is used to manipulate a <table>. While it works with single entries, i.e. "12346", it doesn't work with multiple entries, such as "123456,789101".
The error is specifically thrown at Line 77: var serverData = $.parseJSON(data)[0];
Here's the stack trace
Uncaught SyntaxError: Unexpected token s in JSON at position 2
at Function.parse [as parseJSON] (<anonymous>)
at Object.<anonymous> (myScript.js:77)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Here is what my code looks like so far:
PHP:
$sql = "SELECT * FROM students";
$stmt = $pdo->prepare($sql);
$stmt->execute();
//Database access is arbitrary
while ($row = $stmt->fetch()) { //iterate through db results
$student_array[$row['sid']] = array(
'name' => $row['name'],
'advisory' => $row['advisory']
);
}
$json_params[] = array(
"students" => $student_array, /* The array of arrays */
"success" => "n students were checked in, nice!" /* generic message */
"failure" => "m students couldn't be accessed"
);
echo json_encode($json_params);
jQuery:
$.get("check-in.php", {value: inputValue}).done(function(data) {
var serverData = $.parseJSON(data)[0];
if (serverData.success) {
$.each(serverData.students, function(sid, tableValues) {
/* Create a <tr> based on the information (using the key as the SID,
* name, and advisory, and insert that <tr> into a table */
});
}
}
This might be the culprit, which is the JSON text causing the issue:
[{
"students": {
"245680":{"name":"John Doe","advisory":"9"},
"135791":{"name":"Jane Smith","advisory":"7"}
},
"success":"2 students were checked in!"
}]
I'm quite puzzled as it's been working fine with single number entries. I've looked at solutions to "parsing JSON arrays of arrays" on this site, but I've tried all the suggestions for those. Any help is greatly appreciated!
I don't see the need to make $json_params as an array. It is stored outside of looping and executed only once. Just remove [] part. THe code will look like this.
$json_params = array(
"students" => $student_array, /* The array of arrays */
"success" => "n students were checked in, nice!" /* generic message */
"failure" => "m students couldn't be accessed"
);
In your jQuery, you can simply retrieve JSON result without having to access key array. [0] isn't necessary as [] in $json_params is removed.
var serverData = $.parseJSON(data);
Your code has this:
var serverData = $.parseJSON(data)[0];
but it's failing because data is already an object (not a json string that needs to be parsed).
Try this:
var serverData = data[0];
i'm entirely new to this site, so i'm sorry in advance if my post is not formatted properly.
Anyway, i have what i expect to be a fairly simple question. I'm extracting values from a "request body"-array-thingy, and i got most of what i need by using these 4 lines of code:
$payment_id = strval($callback_json->id);
$order_id = strval($callback_json->order_id);
$currency = strval($callback_json->currency);
$card_brand = strval($callback_json->metadata->brand);
My problem now is that i've run out talent when trying to get the "amount" value that seems to be a "sub-variable" to "operations".
I've tried doing it like this, but neither of them work:
$amount_total = strval($callback_json->operations[amount]);
$amount_total = strval($callback_json->operations->amount);
So my question now is; How do i format this line to get the value "69500".
I really hope someone out there can help me! :-)
{
"id":9256797,
"order_id":"23322651466",
"accepted":true,
"type":"Payment",
"text_on_statement":null,
"branding_id":null,
"variables":{},
"currency":"DKK",
"state":"new",
"operations":[{
"id":1,
"type":"authorize",
"amount":69500,
"pending":false,
"qp_status_code":"20000",
"qp_status_msg":"Approved",
"aq_status_code":"20000",
"aq_status_msg":"Approved",
"data":{},
"callback_url":"http://requestb.in/105y8k81",
"callback_success":null,
"callback_response_code":null,
"created_at":"2015-12-05T12:40:40+00:00"
}],
"metadata":{
"type":"card",
"brand":"visa",
"last4":"0008",
"exp_month":11,
"exp_year":2016,
"country":"DNK",
"is_3d_secure":false,
"hash":"6f976a4e388928beb4ad3OrQHCS2LDGNAFZVK3i54p6q8heV0RRci",
"number":null,
"customer_ip":"2.110.77.40",
"customer_country":"DK",
"fraud_suspected":false,
"fraud_remarks":[]
}
use
$amount_total = strval($callback_json->operations[0]->amount);
because [ in json is an open tag for an array.
{'foo':[{'bar':"A"},{'bar':"B"}]}
$val->foo[0]->bar; # A
$val->foo[1]->bar; # B
Hope that helps.
EDIT#4: json_decode is failing and returning null on a seemingly valid json string. See below for more info
I am new to JSON/JSONP and I'm running into constant trouble accessing the values in the returned JSON with PHP. I have stripped the JSONP callback without issue using code I found on this board. I am getting a JSONP result from http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=love and struggling to access the first result for the meaning. It's a quite complex result, and I need to access the first meaning (in the node "text") from the below JSON result.
http://pastebin.com/hBTeBTUL
My best attempt was:
if (isset($json->primaries[1]->entries[1]->terms[1]->text))
The above was the best I could do, I just keep getting errors trying to return that text node saying it is undefined. I'd prefer to work with objects rather than associative arrays too, if possible, so please avoid telling me to set it to return assoc array.
Any help would be greatly appreciated. I'm really stuck :P
EDIT:
$json->primaries[1]->entries[1]->terms[0]->text didn't seem to work either. Here is the complete script. Ignore the $params array as it is not used, was going to use it to generate the query.
The script has been edited since when I first posted, I had an invalid JSON object, but the error seems to be fixed as it will now parse through JSON formatters.
The error i'm getting trying to print the value out is
PHP Notice: Trying to get property of non-object in /home/outil2/Plugins/GDefine.php on line 23
EDIT#2: added json_decode which was in my original solution, but got lost in the second version
<?php
class GDefine extends Plugin {
public static $enabled = TRUE;
public function onReceivedData($data) {
if ($data["message"][0] == ".def") {
$params = array (
"callback" => "a",
"sl" => "en",
"tl" => "en",
"q" => $data["message"][1]
);
$jsonp = file_get_contents(
"http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=" . $data["message"][1]);
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
var_dump($json);
print_r($json->primaries[1]->entries[1]->terms[0]->text);
if (isset($json->primaries[1]->entries[1]->terms[0]->text)) {
$text = $this->bold("Google Definition: ");
$text .= $this->teal($json->primaries[1]->entries[1]->terms[0]->text);
$this->privmsg($data["target"], $text);
} else {
$this->privmsg($data["target"], "error error error");
}
}
}
}
EDIT #3: this is the string I'm trying to json_decode, after using substr to remove the callback function, but am getting a NULL value returned on var_dump($json)
{"query":"love","sourceLanguage":"en","targetLanguage":"en","primaries":[{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Noun","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loves","language":"und","labels":[{"text":"plural"}]}]},{"type":"meaning","terms":[{"type":"text","text":"An intense feeling of deep affection","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"babies fill parents with intense feelings of \x3cem\x3elove\x3c/em\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e their country","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A deep romantic or sexual attachment to someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it was \x3cem\x3elove\x3c/em\x3e at first sight","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"they were both \x3cb\x3ein \x3cem\x3elove\x3c/em\x3e with\x3c/b\x3e her","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we were slowly \x3cb\x3efalling in \x3cem\x3elove\x3c/em\x3e\x3c/b\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A personified figure of \x3cem\x3elove\x3c/em\x3e, often represented as Cupid","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A great interest and pleasure in something","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"his \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e football","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we share a \x3cb\x3e\x3cem\x3elove\x3c/em\x3e of\x3c/b\x3e music","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Affectionate greetings conveyed to someone on one\x27s behalf","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A formula for ending an affectionate letter","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"take care, lots of \x3cem\x3elove\x3c/em\x3e, Judy","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A person or thing that one \x3cem\x3eloves\x3c/em\x3e","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"she was \x3cb\x3ethe \x3cem\x3elove\x3c/em\x3e of his life\x3c/b\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their two great \x3cem\x3eloves\x3c/em\x3e are tobacco and whiskey","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A friendly form of address","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it\x27s all right, \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Used to express affectionate approval for someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"don\x27t fret, there\x27s a \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"(in tennis, squash, and some other sports) A score of zero; nil","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"\x3cem\x3elove\x3c/em\x3e fifteen","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"he was down two sets to \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]}]},{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Verb","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loved","language":"und","labels":[{"text":"past participle"}]},{"type":"text","text":"loves","language":"und","labels":[{"text":"3rd person singular present"}]},{"type":"text","text":"loving","language":"und","labels":[{"text":"present participle"}]},{"type":"text","text":"loved","language":"und","labels":[{"text":"past tense"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Feel a deep romantic or sexual attachment to (someone)","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"do you \x3cem\x3elove\x3c/em\x3e me?","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Like very much; find pleasure in","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"I\x27d \x3cem\x3elove\x3c/em\x3e a cup of tea, thanks","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"I just \x3cem\x3elove\x3c/em\x3e dancing","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"a fun-\x3cem\x3eloving\x3c/em\x3e girl","language":"en"}]}]}]}]}
I json_decode that and it returns NULL :(
You're trying to access an object that doesn't exist. Your code:
if (isset($json->primaries[1]->entries[1]->terms[1]->text)) // Doesn't exist
There's no terms[1] in entries[1] in primaries[1]. There's just 1 item; terms[0]. I think this will work for example:
if (isset($json->primaries[1]->entries[1]->terms[0]->text))
The first item in the array is indexed by 0 not 1, maybe that's your mistake.
Edit:
You also need to decode the JSON, change:
$json = substr($jsonp, 2, strlen($jsonp)-12);
to:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
Edit:
You need to escape some unescaped characters in the JSON as well. Add this to your code:
Change:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
to:
$json = substr($jsonp, 2, strlen($jsonp) - 12);
$json = str_replace("\\", "\\\\", $json);
$json = json_decode($json);