views:

92

answers:

5

I'm trying to get a javascript script (running in a Safari extension, to be exact) to send a number of strings to a PHP script on my server. I got it working by constructing a URL with the variables in it, but I'd like to do it using POST to be more secure and incase one of the variables being passed through has an '&' in it.

Is there a way I can do this? Thanks!

A: 

Use Ajax.

http://www.w3schools.com/ajax/default.asp

sheeks06
A: 

XmlHttpRequest

alex
A: 

Yes, and you do not need to use AJAX. You can use an HTTP POST request. That's basically a HTML form. Of course, if you want the data to be passed to PHP without the webpage visitor having to click something, you'll need to use Javascript to submit the form (could be with hidden elements), or use AJAX (xmlhttprequest). Feel free to ask a more specific question.

sims
+1  A: 

A couple of things:

First off, you can send data through a URL safely by using the escape() function from javascript:

window.location="myscript.php?company=" + encodeURIComponent("Ben & Jerry's Ice Cream");

and then you can decode the value in PHP using the urldecode() function:

$company = urldecode( $_GET["company"] );

and then you will have the value exactly as it was entered.

It is important to realize that you will have to encode the data whether you send the data through POST or GET. They are formatted the same, with both using & signs to separate key/value pairs.

Your second option is to use Ajax (as many others have proposed). This has the effect where it will not refresh the page. This may or may not be ok, but that is what will happen.

If you don't want to use an Ajax call, you third option is that you can simply place a form on the page:

<form name="myform" method="POST" action="MyPhpScript.php">
    <input type="hidden" name="value1" />
    <input type="hidden" name="value2" />
</form>

Then, from javascript, set the hidden form values and submit the form.

Pick your poison--you have plenty of options :)

Stargazer712
Instead of escape you can/should use encodeURIComponent and don't have to worry about decoding on server side.
Rafael
@Rafael, good point about escape() (never knew that), but you will most definitely still have to use decode() on the back end (unless you want %20 instead of " ")
Stargazer712
I'm not sure if it's always the case, but $_GET (PHP) on my server holds decoded space characters.
Rafael
A: 

one different solution, i used it in one of my project: use cookie

set cookie from javascript reload page and get it in php

Simer
Interesting! How would one create/set a cookie using JS?
sims