I write my scripts in PHP, and there are HTML and javascripts inside. What I want is when I click a button(in HTML), it calls a javascript function, the function should visit a url like "http://localhost/1/2" And the page stays as before. Is it feasible?
I just want it work, no matter in js or php. Thanks.
Since the page is on the same domain, you may use an Ajax request:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send(null);
Note that this does not do any error-checking, however. If you need that, there are a multitude of available tutorials easily found with a search.
And since you ask, for pages not on the same domain, using an <iframe> is sometimes possible:
var frame = document.createElement("iframe");
frame.src = url;
frame.style.position = "relative";
frame.style.left = "-9999px";
document.body.appendChild(frame);
This is commonly known as AJAX (being able to send a request to the server and receive a response back without navigating away from the page).
AJAX is supported in ALL modern browsers, but sometimes there are inconsistencies, so it is best to use a javascript framework such as JQuery, YUI or another framework.
I tend to use YUI, so here's a quick example on how to send an AJAX request using YUI. This uses the IO Utility:
// Create a YUI instance using io module.
YUI().use("io", function(Y) {
var uri = "http://localhost/1/2";
// Define a function to handle the response data.
function complete() {
Y.log('success!');
};
// Subscribe to event "io:complete"
Y.on('io:complete', complete);
// Make an HTTP request to 'get.php'.
// NOTE: This transaction does not use a configuration object.
var request = Y.io(uri);
});
Related
I want to transfer the varible "content" to php and then a mysql database, but everything I have tryied fails. The data is comming from a iframe and the code looks like this
function getContentFromIframe(Textfield)
{
var myIFrame = document.getElementById("Textfield");
var content = myIFrame.contentWindow.document.body.innerHTML;
if (content != "")
{
alert('bla, bla, bla ' + content);
content = 'The inside of my frame has now been saved';
myIFrame.contentWindow.document.body.innerHTML = content;
}
else{
alert('bla bla bla ');
}
}
Sending data from the browser to the web server is not such a simple task. I would suggest you read up on AJAX. Basically AJAX will allow you to send asynchronous request to the server from you JS code. The data you want sent is added as POST body or as query parameters in the URL you request, depending on the size of the data.
Also using AJAX without some extra library (Prototype/JQuery/etc) is not very easy, due to cross-browser issues. Check those out too.
Save javascript data in hidden field and get hidden field in php code
You will need to perform a request that interfaces with your server in some way. You can use a form submission, or put the variable in the query string of a URL and navigate to it (using window.location). Or an AJAX request.
I needed recently to set some $_SESSION vars from onSelect on a select menu. So basically, transferring Javascript value to PHP.
It's totally doable through AJAX, and I use the simple object inited in Javascript (no JQuery or other new fancy tools for cool programmers :))
You can actually do an AJAX request, via POST or GET (read docs on AJAX), and then in the .php file on which you do the request, init a $_SESSION var (with start_session() on) which you can then access in your PHP current page.
Basically, to shed some more light, when you trigger a Javascript event, that event triggers a POST / GET request on an external .php file which can save into a database or assign a $_SESSION var, but this is all done asynchronously, and quick, so the current PHP variables are still in effect :)
cheers
you can pass javascript variable like this
if (content != "")
{
var url = "your phpfile ?content="+content;
$.ajax({
url : url,
type: "post",
success:function(response)
{
document.getElementById("your field").innerHTML = response;
}
});
}
You can use Jquery to invoke a post request to a php page using AJAX and process it.
i want to pass a javascript string to php ... WHICH is RIGHT after the code .. in the script.
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
this does not work.
What should i do ?
When someone visits a website, this is generally what happens:
Their browser sends a request to the server.
The server evaluates that request.
The server realizes, "Egad, the page they're requesting has PHP!"
The server evaluates the PHP, and only sends the results to the browser.
The browser parses the content that it receives.
The browser realizes, "Egad, the page I received has JavaScript!"
The browser evaluates the JavaScript, entirely on the client's machine.
So PHP and JavaScript are basically at different ends of the process. Only the server handles PHP, and only the client handles JavaScript.
To "give" a string to PHP, you'd have to make a request of the PHP page, sending that string as a GET variable:
http://www.yourdomain.com/some_php_page.php?myvar=mytext
There are a few ways to do this with JavaScript.
If you only care about making that request on the PHP page, and you don't need to worry about receiving any information back, you can just create an image and use the URL as the source:
var fakeImg = new Image();
fakeImg.src = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext';
Even though you're requesting an image, the server doesn't know that, and will process your request by calling the PHP evaluating it, etc.
You can make an actual AJAX request. Start by creating an XMLHttpRequest object:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
There are some issues in IE with cached responses on AJAX requests, so make the url unique:
var url = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext&unique=whatever';
Tell your XHR where you want it to go, and how you want it to get there:
xhr.open('GET', url, true);
// The "true" parameter tells it that we want this to be asynchronous
Set up a method that will check for when a response is received:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status < 400) {
success(xhr.responseText);
}
};
And finally, send the request:
xhr.send(null);
// We set "null" because some browsers are pissy
Some notes to keep in mind:
You have to build the success function yourself, to handle the string that your PHP page will return.
You can pass that function xhr.responseXML if you want, but that's usually just a hassle for me.
Using onreadystatechange the way I have will (I believe) introduce memory leaks in some versions of IE
PHP is executed server side while javascript is client side, so that means that the PHP is already executed when you're sending your javascript code.
You might want to look into AJAX instead.
You should get the difference between client side and server side code clear. The variable you are introducing in the php code isn't assigned before because that variable is set at the client. So your code example is in essence wrong. If you want a value that is present at the client (javascript) to be available at the server (php), you need to do something with the xmlhttprequest object of javascript (also know as ajax).
You can do the other way around though...print a php value in javascript. This is because the script is than created server side and send to the client before it is being processed by the browser.
Not sure what you are trying to reach but maybe this helps a bit.
Your example is somewhat confusing:
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
Because if I do this:
<script type="text/javascript">
<?php $myvar = "mytext"; ?>
var myvar = "<?php echo $myvar; ?>" ;
</script>
Then it sets the JavaScript value of myvar to the PHP value of $myvar so they both stay the same. If you're trying to do something else you need to expand your example.
i tried these two codes but it is not functioning.. i only want to ask for the data output from another domain from http://vrynxzent.info/hello.php
first code
$.post("http://vrynxzent.info/hello.php",function(e){
alert(e);
});
second code
alert(askData());
function askData()
{
var strUrlList = "http://vrynxzent.info/hello.php";
var strReply = "";
jQuery.ajax({
url:strUrlList, success:function(html){strReply = html;}, async:false
});
return strReply;
}
is there another way for this? or is it posible to do this? i want the "Hello World!" output to store in a variable in javascript..
Same old same origin policy.
The most common way to solve this is to do query in back-end (php in your case). I.e., browser sends ajax request to your host, which sends requests to other domain, receives response and sends it back to browser.
There're also some options if you own that other domain. JSONP, for example.
edit
Forgot to tell, this jquery plugin allows cross-domain requests through YQL. Tried myself.
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
It doesn't work in all cases (in particular, if webmaster has banned robots from his site), but it's still fairly simple and usable.
Because of same origin policy you cannot make ajax requests like this to some other domain,.
i would suggest using a proxy in between,.
for that what you have to do is have a script proxy.php on your own domain and then your ajax request will be
$.post( 'proxy.php' )
then proxy.php would send a request to http://vrynxzent.info/hello.php using curl and send you back the response
By default this does not work because of the "Same Origin Policy."
There are workarounds... see: http://www.ajax-cross-domain.com/
I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");
I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.