strange quark
strange quark

Reputation: 5205

Pass variables to PHP from javascript

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!

Upvotes: 0

Views: 294

Answers (4)

riwalk
riwalk

Reputation: 14223

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 :)

Upvotes: 1

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

set cookie from javascript reload page and get it in php

Upvotes: 0

d-_-b
d-_-b

Reputation: 6773

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.

Upvotes: 0

gianebao
gianebao

Reputation: 18918

Use Ajax.

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

Upvotes: 0

Related Questions