How to send an array via the url in javascript/jQuery - php

I am trying to send a javascript array via the url.But it fails
function viewReport(mode,someid){
if(mode==0){
var para= new Array();
para['para1'] = 'para1'||0;
para['para2']= 'para2' || 0;
console.log(para);
window.open('somePDFView/'+para,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
window.open('somePDFView/'+para,'_blank');
}
}
On if part(mode=0), the para array is not sending any more and on else part (mode=1) the
para is sends like this:
somePDFView/[object Object]
Which shows the error:
The URI you submitted has disallowed characters
How can we send an array via url.I can't use Ajax (because its a popup window) or session or storing in a temporary table.Also how can we retrieve this value in the controller.
Edit:
I miss an important thing that I am using codeigniter. Then I think it disallows special characters like - &,=,[,],etc..So if any other methods available for sending data as an array?..

To send an array of params via URL from Javascript to PHP/Codeigniter, you need to follow 2 steps:
Convert your params array to JSON String and send that as a single query param.
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
Decode the query string param (i.e JSON string) at your controller
$params = json_decode($_GET['params']);
Now you can use all the params at your controller by accessing through $params.
Your code block becomes:
function viewReport(mode,someid){
if(mode==0){
var para= new Array();
para['para1'] = 'para1'||0;
para['para2']= 'para2' || 0;
console.log(para);
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
para = JSON.stringify(para);
window.open('somePDFView?params='+para,'_blank');
}
}
Try this out and let me know if you still faces this issue.

You can also use Json here. Use JSON.stringify().
Note:
Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.
function viewReport(mode,someid){
var json;
if(mode==0){
var para= new Array();
var paraelements={
para1:'para1'||0,
para2:'para2'||0
};
para[0]=paraelements;
json = JSON.stringify(para);
window.open('somePDFView/'+json,'_blank');
}else{
var para=[];
var paraelements={
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
para[0]=paraelements;
json = JSON.stringify(para);
window.open('somePDFView/'+json,'_blank');
}
}
If you are using php, use json_decode() to convert json into PHP variable.Also refer,
http://php.net/manual/en/function.json-decode.php

You can try to pass them as individual parameters:
var para1 = '1';
var para2 = '2';
var para= new Array();
para.push('para[]=' + para1 || 0);
para.push('para[]=' + para2 || 0);
var url = para.join('&');
alert(url)
Returns para[]=1&para[]=2. Note that this solution does not require jQuery.

Use jQuery.param() and change your data structure :
var para = {
para1:'anotherpara1'||0,
para2:'anotherpara2'||0
};
window.open('somePDFView/'+jQuery.param(para), '_blank');
The Demo jsFiddle

Related

convert string to array dynamically in jquery

I have working with amcharts (line charts). Set data dynamically with ajax and get the data from php code in JSON format.
Problem comes string is not changed to array dynamically.
if i have add this string static in jquery code
code:
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
Thats working fine.
if i have set this code dynamically. line charts shows undefined.
i have use this function
ajax return code
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}]
i have just pass this on this function. like
var ajaxString = [{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
and call this funciton
lineChart(ajaxString);
function lineChart(data) {
var chart;
var chartData=data;
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 45; // this line makes category values to be rotated
categoryAxis.gridPosition = "start";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
// valueAxis.title = "Visitors from country";
valueAxis.axisAlpha = 0;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.colorField = "color";
graph.balloonText = "<b>[[category]]: [[value]] Users</b>";
graph.type = "column";
graph.lineAlpha = 0.2;
graph.fillAlphas = 0.9;
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.zoomable = false;
chartCursor.categoryBalloonEnabled = false;
chart.addChartCursor(chartCursor);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
}[![undefined message][1]][1]
But thats not working.
Thank You in advance
The ajaxString that you are passing to your function is simply an string and not a json object , so what your function lineChart might be expecting is json object so try to convert your ajaxString into valid json object before sending it to your function using
JSON.parse(ajaxString);
This looks like you are attempting to set a JSON string to chartdata instead of a javascript object array.
In this case, you should try to parse your string gotten through the ajax call like so : JSON.parse(dataelement) before setting it to chartdata.
You can create the code dynamically in PHP and covert the array in json via json_encode.
encoded json can be used later in the jquery.

Get json from php session instead of json file

I have this jquery function
function updateStatus(){
$.getJSON("<?php echo $_SESSION['filnavn']; ?>", function(data){
var items = [];
pbvalue = 0;
if(data){
var total = data['total'];
var current = data['current'];
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$("#progressbar").progressbar({
value:pbvalue
});
}
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 500);
}
});
}
Is it possible to get the JSON from a PHP session variable instead of a json file?
As I have understood I can get the session data from the session like this:
//json test
var jsonstr = $_SESSION['json_status'];
//parse json
var data = JSON.parse(jsonstr);
But I do not know how I can do that with out the getJSON function?
You're reading too much into it. .getjson is just a $.ajax() call that EXPECTS to get a json reponse from the server. That's all.
It doesn't matter WHERE PHP gets data from, as long as it spits out json text.
Whether that json text was just retrieved from a file/db, or dynamically generated with json_encode(), as long as the browser receives json text, things will "work".
Your best bet here is to create a php file that can act as the target of getJSON that returns the json from your session.
<?php
session_start();
if (isset($_SESSION["filnavn"])){
echo $_SESSION["filnavn"];
// Or, if the key contains an object instead of a json string, use
// echo json_encode($_SESSION["filavn"]);
} else {
// echo the json you want here if the session variable is not set
echo "{}";
}
?>
Then in your jquery code change the getJSON to this
$.getJSON("/path/to/php/file.php", function(data){...});

jquery building array isn't working

I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";

searching within text of api

I'm trying to use an api and I'm just learning how to actually implement an api using php, hopefully I'll learn to incorporate jquery. I know how to create a simple search feature through mysql and its data with php, but is there a way to create search within the api? with API, there's json/xml responses, and they're all strings, so I was wondering if the user was able to search those strings?
Thanks
First you have to send the json data to php via AJAX. Something like this:
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}
// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];
alert(msg);
}
}
You then can call the variable that javascript creates by calling the $_GET['json'] variable.
strstr($_GET['json'] , $whatEverYourSearchingFor);

Flash calling a PHP function

is it possible to call a PHP function from flash and have it execute right away?
If so how could I go about doing that, because I am trying to call a PHP function that will update a users facebook status, but thus far I have been unsuccessful, so I am kind of at the end f my rope.
Any help would be appreciated, thanx!
My idea would be something similar to the following:
function updateFBStatus(newStatus)
{
// create two new instances of LoadVars, one to send and one to receive data
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
// define what should happen when the response is received,
// using 'this' to refer to dataIn and get data from it
dataIn.onLoad = onReturn;
dataOut["newStatus"] = newStatus;
dataOut.sendAndLoad(serverURL+"setFBStatus.php", dataIn, "POST");
}
You then define the setFBStatus.php file on your server to read $_POST['newStatus'] and do whatever you would normally do in php to set the facebook status. That php file can optionally echo some return values in url request format (i.e, paramName1=param1&paramName2=param2&) for your onReturn function to read, if you need to.
Have a look at AMF PHP!
Save the PHP function in facebookFunction.php and call it using a URLLoader.
var urlLoader:URLLoader = new URLLoader();
var data:URLVariables = new URLVariables();
//you can use dot syntax and/or [] syntax to add data.
data.user = "kiele";
data["someThingElse"] = "something else";
var req:URLRequest = new URLRequest("facebookFunction.php");
req.data = data;
urlLoader.load(req);
At the php side, you can read the values from the global get variable.
$user = $_GET["user"]
The way I would do it is in the flash actionscript is call a javascript function using getURL("javascript:someFunction(var-1, var-2, var-n)") http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001180.html
That javascript function can then do an ajax request to a php script.
EDIT:
you could just post data directly without using AJAX:
var firstName:String = "Gus";
var lastName:String = "Richardson";
var age:Number = 92;
getURL("http://www.adobe.com", "_blank", "POST");
Why you are not using a Flash API for Facebook: http://code.google.com/p/facebook-actionscript-api/ ?

Categories