problems with parsing arguments jquery: $getJSON --> php:$_GET - php

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

Related

Read POST data in AJAX call

I have some Session values that I am constantly changing via Ajax calls. I can't seem to get a handle on the POST data to process it and set the values.
What I am passing to it here is an array of strings like is shown in my code below.
Here is where AJAX calls:
var sessionValues = [];
str = {"PID": "1", "Level": "Main", "MenuName": "Kitchen", "State": "CHECKED"}
sessionValues.push(str);
var postObj = {"sessionData": sessionValues};
$.ajax({
type: 'POST',
data: {'data': postObj},
url: 'setSession.asp'
}).done(function(response){
console.log(response);
})
I have this working fine in a PHP version of the program but my ASP version is not grabbing the data. Here is my PHP ver and the ASP ver as best as I could convert it.
<-- php setSession.php works fine -->
$data = $_POST['data'];
foreach ($data['sessionData'] as $key => $value) {
$projectProduct = "1";
$level = $value["Level"];
$menuName = $value["MenuName"];
$state = $value["State"];
$_SESSION['PID:'.$projectProduct][$level][$menuName]['menu_state'] = $state;
echo "[PID:".$projectProduct."][".$level."][".$menuName."][".$state."]<br>";
}
0 =>>>>> Array<br>[PID:1][Main][Kitchen][CHECKED]
Here I want to do the same thing in ASP
' setSession.asp
data = Request.Form("data")
For Each part In data("sessionData")
projectProduct = part("PID")
level = part("Level")
menuName = part("MenuName")
state = part("State")
Session("PID:" & projectProduct).Item(level).Item(menuName).Remove("menu_state")
Session("PID:" & projectProduct).Item(level).Item(menuName).Add "menu_state", state
response.write("[PID:" & projectProduct&"]["&level&"]["&menuName&"]["&state&"]<br>")
Next
outputs blank
It looks like it never has any data but doesn't throw any errors. Am I reading the POST object correctly?
[edit]
Here is the RAW POST data captured from Fiddler:
data%5BsessionData%5D%5B0%5D%5BPID%5D=1&data%5BsessionData%5D%5B0%5D%5BLevel%5D=Main&data%5BsessionData%5D%5B0%5D%5BMenuName%5D=Kitchen&data%5BsessionData%5D%5B0%5D%5BState%5D=CHECKED
here I used a URL Decode on that string-
data[sessionData][0][PID]=1&data[sessionData][0][Level]=Main Level Plan&data[sessionData][0][MenuName]=Kitchen&data[sessionData][0][State]=CHECKED
This looks like I should be able to loop through the strings now by using
For Each part In Request.Form("data[sessionData]")
but nothing happens. I added a simple loop to look at the request.form and here is what it is seeing:
for each x in Request.Form
Response.Write(x)
Next
' outputs -> data[sessionData][0][PID]data[sessionData][0][Level]data[sessionData][0][MenuName]data[sessionData][0][State]
I guess what this comes down to is just reading through and processing that string correctly, or multiple if more than one is sent. Correct?
The RAW output definitely helps work out what is going on.
What is happening is jQuery is translating the JSON structure into HTTP POST parameters but during the process, it creates some overly complex key names.
If you break down the key value pairs you have something like
data[sessionData][0][PID]=1
data[sessionData][0][Level]=Main Level Plan
data[sessionData][0][MenuName]=Kitchen
data[sessionData][0][State]=CHECKED
As far as Classic ASP is concerned the this is just a collection of string key and value pairs and nothing more.
The correct approach to work out what these keys are is to do what you have done in the question, but with some minor alternations.
For Each x In Request.Form
Response.Write(x) & "=" & Request.Form(x) & "<br />"
Next
Which when outputted as HTML will look similar to the break down shown above.
Armed with the knowledge of what the keys are you should be able to reference them directly from the Request.Form() collection.
Dim pid: pid = Request.Form("data[sessionData][0][PID]")
Response.Write pid
Output:
1

Communication between Javascript and MYSQL

I am working on some code using Google Maps API. To sum up shortly, I have MySQL database with a table of information used to generate markers on the map. I connected to the database and am using PHP to draw out the necessary attributes and communicate with my Javascript code using XML.
What I'm currently attempting to do is go in the other direction, I'm trying to send a string of information (for example "1,2,3,45,18") from my Javascript code to MySQL to be set as a session parameter (call it #sparam). What is the process behind passing this value to MySQL?
Would I be able to access a MySQL variable through PHP in the same way I can access tables (for the purpose of getting a value back into Javascript)?
I'd appreciate any insight.
Thanks.
EDIT
Maybe I was unclear in my original post. What I'm asking is how would I be able to pass a string to a MySQL session variable, specifically a set of IDs directly related to the IDs in the table of the MySQL database, and then be able to work with these IDs by calling the necessary procedures in MySQL. In turn, the procedures called in MySQL would generate some output, which would then have to be passed back to the Javascript code.
I created a special JSON (JavaScript Object Notation) php pages that I would call from javascript. Then I would parse those JSON responses.
Simple example:
JAVASCRIPT:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "page_json.php?action=getsession",
type : "GET",
success : function(data) {
//Get Json and loop over it's data
if (data.length>10){
var jsonData = JSON.parse(data);
$.each(jsonData, function(Idx, Value) {
if (Idx>0){
//get values for each vehicle and then remove it's marker from the map and then add new marker on the map (thereofore update the marker)
c_latitude = Value["lat"];
c_longitude = Value["lon"];
c_name = Value["name"];
c_notes= Value["notes"];
removeMarker(c_name); //remove old marker function
addMarker(c_latitude, c_longitude, c_name); //add current marker function
}
});
}
}
});
});
}
PHP: Here I loop over my arrayList and then create a simple array with values. Then I just output it as a json string
foreach ($listOfCars->arrayList as $key => $value) {
$unit = new fleetUnit();
$unit = $value;
//create array for json output
$data[] = array('lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes);
}
echo json_encode($data);

Json Returning [object object] instead of array

I have json data being fed into a Sencha touch app. Here's the json:
http://pastie.org/2622260 - (modified for an example, of course)
When I return the "images" and console.log it, it returns the following:
images: "[object Object],[object Object],[object Object],[object Object],[object Object]"
Rather than the URLs.
My json encoder looks like this (I'm pulling the data out of a Wordpress site):
case 'posts':
foreach(get_posts('numberposts=50&category=') as $post) {
$count = 0;
$imgurl = array();
foreach( get_group('Photo', $post->ID) as $images){
$count++;
$imgurl[] = array(
'count'=>$count,
'imageurl'=>get('photo_image_file', $count, 1, false, $post->ID),
);
}
$json['posts'][] = array(
'id'=>$post->ID,
'title'=>$post->post_title,
'body'=>apply_filters('the_excerpt', $post->post_content),
'date'=>$post->post_date,
'user'=>get_userdata($post->post_author)->user_firstname,
'images'=>$imgurl
);
}
}
header('Content-type: application/json');
echo json_encode($json);
exit();
What I am looking for it to do is to return the array of image urls, rather than the [object object] that I am currently getting.
EDIT: Here is the sencha code I'm using to try to pull the imageurl out:
console.log(this.record.data);
console.log(this.record.data.images);
console.log(this.record.data.images.length);
var numberOfPages = this.record.data.images.length;
// Create pages for the carousel
var pages = [];
for (var i=0; i<numberOfPages; i++) {
pages.push(new Ext.Component({
id: 'page'+i,
cls: 'page',
tpl: '<tpl for=".">{imageurl}</tpl>',
//html:'test',
}));
}
// Create the carousel
this.carousel = new Ext.Carousel({
id: 'carousel',
title:'Gallery',
iconCls:'photos2',
defaults: {
cls: 'card'
},
items: pages,
});
Associative arrays in PHP encoded as JSON become objects in JavaScript when decoded. What you're seeing is correct and normal. Access them as you would any other object in JavaScript.
Update: Sorry, for the irrelevant example I had given
Where is your pages[i].update(this.record.data.images); ?
You can try the following -
var numberOfPages = this.record.data.length;
// Create pages for the carousel
var pages = [];
for (var i=0; i<numberOfPages; i++) {
var tmp = new Ext.Component({
id: 'page'+i,
cls: 'page',
tpl: '<tpl for=".">{imageurl}</tpl>'
});
tmp.update(this.record.data[i].images);
pages.push(tmp);
}
Found the answer, gave it to Rifat because his answer was the springboard.
I had the [object object]'s coming through as a literal string of characters. I wrote a quick test.php outside Sencha touch and was able to get the actual array to work. My first issue was the json itself - It needed to be validated. You guys were all correct and thank you for that clue.
Second, once I got the test.php document working, I realized it had to be within Sencha itself. The nagging feeling that the string of characters had something to do with it sat in my head. Finally, I went to my model and found how I was pulling the images:
{name: "images", type: "string"},
I saw string, and the aha moment hit! This fixed it and gave me my URL's:
{name: "images"},
Can't thank Ignacio and Rifat enough. You guys hung in there with me and got the answer to (eventually) appear. Thanks again, and hope this helps anyone else that may run into a similar issue.
I had a similar issue once, in the javascript backend. Here is an answer for people using JS:
Make sure to stringify your object arrays before sending them:
JSON.stringify(array[i]);
Unless ofcourse you are ONLY sending JSON, which in that case sending regular JSON should work fine :)

Passing arrays from Flash to PHP

I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]

How do I POST XML data to a URL via JavaScript in an Adobe AIR app?

I'm writing an application that downloads an XML string from a URL and POSTs that to another URL (that's set up to handle an incoming "XML" field). I've got the first part right - it downloads the XML and I can alert() it and all that, but I'm unable to figure out how to POST that data to a server.
function pull() {
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://something/something.xml');
myLoader.addEventListener(air.Event.COMPLETE, pulled);
myLoader.load(myRequest);
}
function pulled(evt) {
if (evt.target.bytesTotal>0) {
// alerting shows the full string just fine
alert(evt.target.data);
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://someplace/push.php');
myRequest.method = air.URLRequestMethod.POST;
// myVars = new air.URLVariables("xml="+evt.target.data); //
// alert(evt.target.data.toUpperCase());
myRequest.data = "xml="+evt.target.data; // myVars;
myLoader.dataFormat = air.URLLoaderDataFormat.TEXT;
myLoader.addEventListener(air.Event.COMPLETE, pushed);
myLoader.load(myRequest);
}
}
I made the 2nd server PHP echo the contents of the xml variable, but I'm just unable to get the exact contents of the XML string. There is something I'm doing wring with the myRequest.data and/or dataFormat bit.
Can someone just figure this out? I know it's probably a simple thing, but I'm at my wit's end right now.
This is my first AIR app.
Another related question (or sub-question) is that...
alert(evt.target.data); // shows an alert box with the XML
alert(typeof evt.target.data); // shows String
alert(evt.target.data.toUpperCase()); // shows the xml converted to upper case
alert(encodeURI(evt.target.data)); // shows up blank.
alert(escape(evt.target.data)); // shows up blank.
Why??
The error seems to be the way you are assigning the parameters to 'data' ... Use URLVariables.
var params:URLVariables = new URLVariables();
params.[name of parameter] = [value];
--- so like params.xml = (YOUR XML) ... from your example:
// uses the dynamic object to add the 'xml' property to 'params' at runtime.
params.xml = evt.target.data
Then Change you request.data to request.data = params;
-- The URLVariables guy is dynamic - so you can add properties as I describe above.
For a basic example - much more complete that what I have here: http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html

Categories