php array in url from json - php

Here is what I want to do:
I have some json like this
var foo = {
format:"json",
type:"test",
id:"26443"
};
and I awant to put that in a url like this
'http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:4:"test";s:2:"id";s:5:"26443";}'
which I will then put into ajax call but everything I have tried results in error 501 BAD URI could someone tell me how to do this
I've tried this
EDIT:
after looking again and alerting the results of this function it IS build the results correcty they just arrn't being used propler either by ajax or the browser
function js_array_to_php_array(a) {
var a_php = "";
var total = 3;
for (var key in a){
total;
a_php = a_php + "s:" + String(key).length + ":\"" + String(key) + "\";s:" + String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total +":{" + a_php + "}";
return a_php;
}
when I use http fox it get this back
http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:4:%test%22;s:2:%22id%22;s:5:%2226443%22;}
which i find odd because it ecodes everything but the last curly bracket

Why not just use a "normal" query string?
http://example.com/?type=test&id=26443
$type = $_GET['type'];
$id = $_GET['id'];
Unless I am missing something?

There is a jQuery function for this already! Use it and love it.
http://api.jquery.com/jQuery.param/

so as it turns out there is nothing wrong with the function js_array_to_php_array it did exactly as I needed it to the problem was that I needed to use JSONP instead of JSON when running my ajax call as I was going cross domain which also explains why the code worked in the url but not when I ran ajax
thank you all for your help

http://example.com/a:3:{s:6:"format";s:4:"json";s:4:"type";s:5:"test";s:2:"id";s:5:"26443";}
501 is right — that's not a valid URL. URLs definitely can't have quotes in them, or (for most part) curly brackets.
If you really have to submit a PHP literal structure in a URL without doing it as normal set of query parameters, you would have to URL-encode the invalid characters, which you can do like:
url= 'http://example.com/'+encodeURI(js_array_to_php_array(foo));
resulting in:
http://example.com/a:3:%7Bs:6:%22format%22;s:4:%22json%22;s:4:%22type%22;s:5:%22test%22;s:2:%22id%22;s:5:%2226443%22;%7D
incidentally this:
String(key)
is superfluous: object keys are always strings in JS, even if you put them in as numbers;
"\"" + String(a[key]) + "\""
is going to go wrong if the value can contain a quote or backslash, and
total;
there should surely be an increment here?

On the PHP end, you could use urlencode(json_encode($obj)) to convert an object to a string that can be used in a URL.
After I posted this, I realized you're trying to convert a JavaScript variable to a URL string after I saw var foo = {. Duh.

Related

Adding multiple variables in the page URL using javascript

Since I'm relativly new to the use of php and javascript I ran into this problem while trying to add multiple variables in a URL
I use the following script:
<script>
function refresh() {
var PCWDE = document.getElementById("PC");
var NMWDE = document.getElementById("naam");
var VNMWDE = document.getElementById("voornaam");
var ONDWDE = document.getElementById("onderneming");
var BTWWDE = document.getElementById("btwnummer");
var LNDWDE = document.getElementById("land");
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value "&nm=" + NMWDE.value "&vnm=" + VNMWDE.value "&ond=" + ONDWDE.value "&btw=" + BTWWDE.value "&lnd=" + LNDWDE.value;
}
</script>
That's beeing activated trough the following html code:
<?php
$pc = $_GET['PCS'];
echo '<input type="text" name="pc" id="PC" onblur="refresh()" value="'.$pc.'">'
?>
The main reason for the use of this html code was that I needed to execute a query without submitting the form, while still beeing able to hold the value of the text box even when the page would refresh. The above html code is used multiple times with the use of different ID's.
The problem I face while trying to do this is that my code only works when only adding 1 variable to the URL like so:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value;
Otherwise it does not work. Either the 'onblur' event fails to work, or the script fails to run.
Is there a way to add the multiple variables to the URL in a similiar way to what i'm doing now?
You forgot plus signs. That's a syntax error and you should see the error message if you open the error console. (on firefox you press control-shift-j)
Shoule be:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value + "&nm=" + NMWDE.value + "&vnm=" + VNMWDE.value + "&ond=" + ONDWDE.value + "&btw=" + BTWWDE.value + "&lnd=" + LNDWDE.value;

How to access javascript variable in php

This is my code:
In A Function:
var daaa=document.getElementById('da').value= year+ "-" +month+ "-" +day;
document.form1.bookingsession.focus();
var coords = {
"lat": daaa
};
$.get('bs.php', coords, function () {
alert('data sent');
});
and my php code is:
<?php
$output = isset($_GET['lat']) ? $_GET['lat'] : 0;
print("$output");
?>
And when i print $output i get the value as 0, but actually have to get the value which is on tha variable daaa. Let me know where i made mistake....
Thank you in advance
Try to change
var daaa=document.getElementById('da').value= year+ "-" +month+ "-" +day;
to
var daaa=document.getElementById('da').value + "-" + year+ "-" +month+ "-" +day;
Anyway in such cases yours "number one" action should be check if variable is really set on client side. You can do it through alert(daaa) or console.log(daaa);
change this
var coords = {
"lat": daaa
};
to
var coords = {
lat: daaa
};
you misplaced the double quotes.
http://api.jquery.com/jQuery.get/
example from jquery
//$.get("test.php", { name: "John", time: "2pm" } );
First of all do the action #coramba mentioned,
then modify your javascript code like this:
$.get('bs.php', coords, function (dataThatPhpPrints) {
alert(dataThatPhpPrints);
});
..you will see that it actually returns the value that you have sent to PHP script and PHP scripts returns the print of that.
In order to assure yourself that your scripts prints something modify PHP code to like below:
<?php
$output = isset($_GET['lat']) ? $_GET['lat'] : 0;
print("$output - is response from the PHP!!!");
?>
Now when you run yor javascript, you will get an alert message like
ActualValueOfLATYouSentToPHP - is response from the PHP!!!
Bear in mind, if you want to test your PHP whether it works or not, you cant just simply open it in browser and wait for some magic to happen, as it uses $_GET to get some value meaning you need to provide it as a QueryString with the key being 'lat' :
yourhost/bs.php?lat=someTestValue

Dynamic URL too long (2568 characters), trying to make it shorter

i'm working with a javascript on a drupal website, but the saving function seems to work only as soon as i click 2 times on the "save" button. the code that fires the function is:
var param ="&usuario="+usuario+"&nivel="+nivel+gano+porc_gano+gasto+porc_gasto+tengo+porc_tengo+debo+ porc_debo+plazo_debo;
var s = document.createElement("script");
s.type = "text/javascript"; s.async = true;
s.src = server_direction +"setMisDatos?callback=respuestaGuardarMisDatos&param="+encodeURIComponent(param);
var h = document.getElementsByTagName("script")[0];
h.parentNode.insertBefore(s, h); //or h.appendChild(s);
the chrome console tells me the error is in the last line i copied, but i don't undertand what kind of error it is.
using chrome console (specifically the "network" one), i see that it's written in red, status/text "failed", type "undefined" size/content "13 B / 0 B"; when it works it's: status/text "200/OK", type "text/json", size/content "256 B/ 38B". i'm not an expert with this, is there some more information that could be useful?
the code fires a netbeans function, that stores data to a postgresql database, so i have like 100 variables that has to be stored when i click on the "save button".
The variables are written like this (in the js file):
var plazo_debo_casa1 = (getValor("plazo_debo_casa1"));
var plazo_debo_casa2 = (getValor("plazo_debo_casa2"));
var plazo_debo_casa3 = (getValor("plazo_debo_casa3"));
var plazo_debo_prestamo1 = (getValor("plazo_debo_prestamo1"));
var plazo_debo_prestamo2 = (getValor("plazo_debo_prestamo2"));
var plazo_debo_prestamo3 = (getValor("plazo_debo_prestamo3"));
var plazo_debo ="&plazo_debo_casa1="+plazo_debo_casa1+"&plazo_debo_casa2="+plazo_debo_casa2+"&plazo_debo_casa3="+plazo_debo_casa3+"&plazo_debo_prestamo1="+plazo_debo_prestamo1+"&plazo_debo_prestamo2="+plazo_debo_prestamo2+"&plazo_debo_prestamo3="+plazo_debo_prestamo3;
and then together in the "param" variable. Is it clearer now?
I installed httpfox in firefox, then i checked what happens, and finally i think i got the error: it says NS_ERROR_NET_RESET. Is it the actual error? what can i do to solve it?
I have been searching around the internet and probably my problem is that the URL is too long,
http://www.mirodinero.com:8080/mirodinero-war/setMisDatos?callback=respuestaGuardarMisDatos&param=%26usuario%3DIsa%20Mirodinero%26nivel%3D109%26gano_sal_neto%3D211113.45%26gano_sal_prof%3D2480%26gano_monet%3D0%26gano_renta_fija%3D0%26gano_renta_vble%3D0%26gano_inmuebles%3D2226.75%26gano_otros%3D2223.73%26gano_otros_ing%3D2411.12%26porc_gano_monet%3D0%26porc_gano_rentaf%3D0%26porc_gano_rentav%3D0%26porc_gano_inm%3D2%26porc_gano_otros%3D2%26porc_gano_otros_ing%3D1%26gasto_casa1%3D1306.46%26gasto_casa2%3D2402.38%26gasto_casa3%3D3999.57%26gasto_prestamo1%3D93475.58%26gasto_prestamo2%3D7325.88%26gasto_prestamo3%3D34090.9%26gasto_tarjetas%3D29443.2%26gasto_ibi%3D5670%26gasto_imp_otros%3D6780%26gasto_seg_inm%3D1320%26gasto_seg_pens%3D3451.22%26gasto_seg_vida%3D2330%26gasto_seg_plan%3D34230%26gasto_seg_medico%3D21220%26gasto_seg_coche%3D220%26gasto_luz%3D620%26gasto_agua%3D4550%26gasto_gas%3D320%26gasto_telef_f%3D22320%26gasto_telef_m%3D2350%26gasto_internet%3D20%26gasto_tv%3D3450%26gasto_hogar%3D20%26gasto_comida%3D20%26gasto_cenas_copas%3D20%26gasto_viajes%3D20%26gasto_vacaciones%3D220%26gasto_mobiliario%3D220%26gasto_ropa%3D2320%26gasto_transp%3D230%26gasto_otros%3D3620%26gasto_colegios%3D240%26gasto_univ%3D340%26gasto_master%3D2230%26gasto_otros_gastos%3D7323433%26porc_gasto_tarjetas%3D0%26porc_gasto_ibi%3D0%26porc_gasto_trib%3D0%26porc_gasto_seg_inm%3D0%26porc_gasto_seg_pens%3D0%26porc_gasto_seg_vida%3D2%26porc_gasto_seg_plan%3D2%26porc_gasto_seg_med%3D0%26porc_gasto_seg_coche%3D0%26porc_gasto_sum_luz%3D2%26porc_gasto_sum_agua%3D2%26porc_gasto_sum_gas%3D0%26porc_gasto_sum_teleff%3D0%26porc_gasto_sum_telefm%3D0%26porc_gasto_sum_int%3D0%26porc_gasto_sum_tv%3D0%26porc_gasto_nivel_hogar%3D0%26porc_gasto_nivel_comida%3D0%26porc_gasto_nivel_cenas%3D0%26porc_gasto_nivel_viajes%3D0%26porc_gasto_nivel_vacac%3D0%26porc_gasto_nivel_mob%3D0%26porc_gasto_nivel_ropa%3D20%26porc_gasto_nivel_transp%3D30%26porc_gasto_nivel_otros%3D30%26porc_gasto_colegios%3D2%26porc_gasto_univ%3D0%26porc_gasto_master%3D0%26porc_gasto_otros_gastos%3D23%26tengo_casa1%3D1231.11%26tengo_casa2%3D10000%26tengo_casa3%3D22240%26tengo_otras%3D23560%26tengo_monetario%3D1212.34%26tengo_planpensiones%3D23230%26tengo_otros%3D23330%26porc_tengo_casa1%3D1%26porc_tengo_casa2%3D0%26porc_tengo_casa3%3D2%26porc_tengo_otras%3D0%26porc_tengo_monet%3D0%26porc_tengo_plan%3D0%26porc_tengo_otros%3D0%26debo_casa1%3D4340%26debo_casa2%3D23450%26debo_casa3%3D23430%26debo_prestamo1%3D23330%26debo_prestamo2%3D6871.11%26debo_prestamo3%3D11340%26debo_tarjetas%3D61340%26porc_debo_casa1%3D30%26porc_debo_casa2%3D10%26porc_debo_casa3%3D12%26porc_debo_prestamo1%3D1%26porc_debo_prestamo2%3D12%26porc_debo_prestamo3%3D1%26porc_debo_tarjetas%3D4%26plazo_debo_casa1%3D230%26plazo_debo_casa2%3D450%26plazo_debo_casa3%3D122%26plazo_debo_prestamo1%3D3%26plazo_debo_prestamo2%3D12%26plazo_debo_prestamo3%3D4
I counted it, it's 2568 characters. So I tried to split it in two parts, since there is "what i earn", "my debts", etc. Problem is, that if my function only saves some columns, then it simply deletes the remaining one in postgres. How can this problem be solved?
since my webpage has different parts where to put the data, i thought that a good idea would be to create smaller function for parts of variable, for example putting 30 variables and the do the callback. I did like this:
function guardaLoQueGano(){
var nivel = parseInt(document.getElementById('progreso_nivel_total').style.marginLeft);
/*idUsusario*/
var usuario = miGetElementsByClassName('title', document.getElementById('block-user-1'))[0].innerHTML;
/*gano*/
var gano_sal_neto = getValor("gano_sal_neto");
var gano_sal_prof = getValor("gano_sal_prof");
var gano_monet = getValor("gano_monet");
var gano_renta_fija = (getValor("gano_renta_fija"));
var gano_renta_vble = (getValor("gano_renta_vble"));
var gano_inmuebles = (getValor("gano_inmuebles"));
var gano_otros = (getValor("gano_otros"));
var gano_otros_ing = (getValor("gano_otros_ing"));
/*gano porcentajes*/
var porc_gano_monet = getValor("porc_gano_monet");
var porc_gano_rentaf = getValor("porc_gano_rentaf");
var porc_gano_rentav = getValor("porc_gano_rentav");
var porc_gano_inm = getValor("porc_gano_inm");
var porc_gano_otros = getValor("porc_gano_otros");
var porc_gano_otros_ing = getValor("porc_gano_otros_ing");
var param = "&usuario=" + usuario + "&nivel=" + nivel + "&gano_sal_neto=" + gano_sal_neto + "&gano_sal_prof=" + gano_sal_prof + "&gano_monet=" + gano_monet + "&gano_renta_fija=" + gano_renta_fija + "&gano_renta_vble=" + gano_renta_vble + "&gano_inmuebles=" + gano_inmuebles + "&gano_otros=" + gano_otros + "&gano_otros_ing=" + gano_otros_ing + "&porc_gano_monet=" + porc_gano_monet + "&porc_gano_rentaf=" + porc_gano_rentaf + "&porc_gano_rentav=" + porc_gano_rentav + "&porc_gano_inm=" + porc_gano_inm + "&porc_gano_otros=" + porc_gano_otros + "&porc_gano_otros_ing=" + porc_gano_otros_ing;
var s = document.createElement("script");
s.type = "text/javascript"; s.async = true;
s.src = direccion_servidor + "setMisDatos?callback=respuestaGuardarMisDatos&param=" + encodeURIComponent(param);
var h = document.getElementsByTagName("script")[0];
// adesso h.appendChild(s);
h.parentNode.insertBefore(s, h);
alert("Datos de lo que gano actualizados correctamente");
}
This kind of function works perfectly, but has a big problem: it changes the values of the columns of this function, but deletes the remaining ones. How can I create different smaller function, in a way to save only on some columns without changing the others? Shall I write the netbeans function setMisDatos to make it more clear?
New finding:
I've been searching in the internet, and maybe found that my problem is that i might change the GET method to a POST protocol, so that it could take any kind of length.
On my page there is a php code to call the javascript function that is:
<div id="lo_que_gano" class="mis_datos" style="display:none">
<div class="generic todo_izq">
<div class="ancho_lado_izq generic">
<div class="texto_form generic">Salario neto</div>
<div class="generic">
<input class="numero" id="gano_sal_neto" type="text" value="0" onchange="calculoGano()" onkeypress="tecla('gano_sal_prof', event);"/></br>
</div>
</div>
//all the values that has to be stored
</div>
<div class="generic botonGuardar">
<input type="button" value="Guardar" onclick="return guardaTodo()"/>
</div>
</div>
how can i convert the GET method to POST? Shall it be implemented in the javascript or in the php code? I'm sorry i'm really not an expert on this.
I tried to change &usuario= with &u=, and it works, but then when i try to change "gano_sal_neto" (i changed &gano_sal_neto= with &gsn=), it will delete the corresponding value in the postgres table (a NULL value). Where is the error now? I'm sorry but i'm really not an expert on this.
And I have an observation: why do i get error after 30 seconds, but not in that in interval?
the change i did, based on the answer i got, from "gano_sal_neto" to "gsn" in:
the javascript file that is loaded by the source code of the page;
the php code of the drupal page;
the netbeans files;
i created a new column named "gsn" in the same table as where the data are stored.
what am i missing to make the new URL work?
Better explanation of what is happening now:
i have 2 types of error:
in the netbeans log file, it tells me:
Code:
error:
java.lang.NullPointerException
at com.mirodinero.web.calculos.Calculos.getTotalGano(Calculos.java:182)
at com.mirodinero.web.calculos.CalcularSegmentos.ejecutar(CalcularSegmentos.java:65)
at com.mirodinero.web.servlets.setMisDatos.actualizarSegmentos(setMisDatos.java:543)
where getTotalGano at those lines is:
public float getTotalGano() {
float res = user.getGanoMonet() + user.getGanoRentaFija() + user.getGanoRentaVble() + user.getGanoInmuebles() + user.getGanoOtros() + user.getGanoSalNeto() + user.getGanoSalProf() + user.getGanoOtrosIng();
return res;
}
and ejecutar() is:
public void ejecutar() {
boolean existe = true;
DatosUsuario datosUser = datosUsuarioFacade.findById(atributosUsuario.getIdUsuario());
if (datosUser != null) {
List<Cartera> lc = carteraFacade.findByIdUsuario(atributosUsuario.getIdUsuario());
Calculos c = new Calculos(datosUser, accionesDatosFacade, fondosDatosFacade, bonosDatosFacade, lc);
ahorroLiquido = c.getTengoDisponible() / c.getTotalGasto();
ingresoAnual = c.getTotalGano(); /*this is line 65 */
diferenciaGanoGasto = c.getSupDefTotal();//indica lo que gano menos lo que gasto
modificarAtributos(c, datosUser);
}
on the postgres log file, i get:
2012-05-22 11:10:46 CESTLOG: could not receive data from client: Unknown winsock error 10061
2012-05-22 11:10:46 CESTLOG: unexpected EOF on client connection
2012-05-22 11:19:12 CESTLOG: CreateProcess call failed: Unknown winsock error 10004 (error code 1115)
2012-05-22 11:19:12 CESTLOG: could not fork autovacuum worker process: Unknown winsock error 10004
but i don't know what does it mean. Maybe is there something i should do with pgadmin to "upgrade" the database to the changes:i added a column named gsn -real and default 0 like gano_sal_neto-, without deleting the gano_sal_neto (that still has stored the data of the users).
still nobody able to help me with this? i don't what's the problem with changing columns name in postgres, maybe a procedure i'm missing?
The answer was to change the settings in glassfish HTTP service listenings: I changed the timeouts to a bigger interval, and now it works!
Because what you are doing is constructing a <script src=...> element, with the src attribute dynamically generated, it's not possible to use POST. All HTTP requests use GET. What you may be able to do instead is encode your querystring to make it shorter. The server-side processing can decode it to send the right script file.
For example, you don't need &usario= when you could call that &u= because your server-side process shouldn't need it to be called usario. You've saved five bytes just by doing that.
You could encode the values to make them shorter, and decode them server-side. I've no idea what the data actually is; this may not be practical.

Flash AS2 using getUrl to POST variables?

I have been tyring to figure this out for a while now and no luck. I have some AS2 code below which works:
on(release)
{
var sendText = "../Flash/uploadVoteandFeed.php?";
sendText += "B=" + _root.JudgeBtext;
sendText += "&C=" + _root.JudgeCtext;
sendText += "&D=" + _root.JudgeDtext;
sendText += "&vote=";
if(_root.NowJudging == 'B') sendText += 2;
if(_root.NowJudging == 'C') sendText += 3;
if(_root.NowJudging == 'D') sendText += 4;
getURL(sendText, "_self");
stop;
}
As I said, this code IS WORKING. But I would liek to modify to send "sendText" as post variables. I just don't like seeing the extralong url with all the variables in it. AS2 should be able to send this as a post var right? I need the flash to open up "uploadVoteandFeed.php" on release in the same window/page, in order to show the user that their vote and feedback was successful and do other things with PHP at that point. (this is currently working with:)
getURL(sendText, "_self");
But like I sadi I get a huge ugly URL and I just think it looks unprofessional. the sendText variable string can end up being almost 264 chars, whcih is also the limit for URLs if I remeber correctly. From everything I've read, AS2 should be able to do what I want, but I cant seem to figure it out.
Thanks all.
You can specify method in a getURL call:
getURL(url, "_self", "POST");
If I remember it right (haven't done AS2 in a while) it will send all variables that are defined in the current scope, so you could try something like this:
on(release)
{
var B = _root.JudgeBtext;
var C = _root.JudgeCtext;
var D = _root.JudgeDtext;
var vote = 1 // TODO: the check of _root.NowJudging
getURL("../Flash/uploadVoteandFeed.php", "_self", "POST");
stop;
}
See the documentation here:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/2/help.html?content=00000564.html

PHP MySQL string showing up as an integer

I have a field called 'score' in a database table that an ajax call is adding values to.
The query below causes it to add values of 1 and 2 under 'score'. It should be looking for "$usrscore1" and "$usrscore2" in my ajax call but it seems to just see the integers (1 and 2) in $us and incorrectly post them as the values under 'score'.
for ( $counter4 = 1; $counter4 <= 2; $counter4 += 1) {
$mess4 = $messages + $counter4;
$us = $usrscore + $counter4;
mysql_query("INSERT INTO messages" . $counter4 . " (`score`)
VALUES ($us)",$dbconn);
}
If I change:
$us = $usrscore + $counter4;
to
$us = $usrscore1;
it correctly looks for $usrscore1 in my ajax call and puts the correct value in the database field under 'score'. But I need it to work in the for loop so just writing it out as $usrscore1 won't work, even though it reads it correctly that way.
Just in case it helps to see it, here's what the ajax call looks like:
$('#rateplugin' + instance).raty({
half: true,
start: totalavgRounded,
click: function(score){
$.ajax({
type: 'POST',
url: 'backend.php',
data: "usrscore"+instance+"="+score+"&action=postmsg",
success: function(xml) {
$.fn.raty.readOnly(true,'#rateplugin' + instance);
}
});
return false;
} // end click
}); // rat
Update:
I may have not been very clear. I set the loop up to only make 2 database tables, but I did that really just for testing purposes. In reality, once this is live, there could be thousands of these to create which is why I'm doing it with a loop. Would the URL variable still be a good solution here? I'm not exactly sure how I would implement it.
My main point of absolute confusion here is that that no matter how I broke up the variable integer from $usrscore it would always ignore the $usrscore part and only see the integer and then just use that as the final value which will always be wrong. Is there something weird about the VALUE MySQL bit that does this? Does anyone have any ideas as to why it is doing that and how to get around it? If that URL variable idea might work, could you please give me some direction into its application here?
from what i can see, you only have limited $usrscore1 and $usrscore2. i suggest you put a single variable $usrscore and populate it based on the parameter in the url.

Categories