I'm sending data to a php page for processing through jQuery and ajax and as result I will get
success: function(data){
mydata = data;
}
my data is an url that looks like mydata = https://myurl.com. Now I want to set mydata to a php variable and use it again inside another function in the main page, means: to set $url = mydata;.
How can I do that?
Thanks,
You can do that using Post via a from, GET via a query string
or you can use cookie like in this solution
how to assign javascript variable value to php variable
You can send the mydata variable to PHP by calling an XMLHttpRequest() via AJAX.
For example
var ajax = new XMLHttpRequest(); // Create new request
ajax.open("POST", "mainpage.php"); // Open the file where you want to send it with POST
ajax.send("mydata="+mydata); // Send mydata variable to PHP
Then in PHP you can check for the variable mydata
if(isset($_POST['mydata'])){
// do something
}
PHP scripts execute when you open a file and before everything else.
Ajax calls exectue when the Javascript is completely loaded. (After php).
So you cant do it.
could you give me more detail about what do you want to do?
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 am passing variable from javascript php with the following code by using cookie.
<script type="text/javascript">
function gTest() {
var country = 'hello testing';
document.cookie = 'name=document.write(country);' ;
document.write(country);
}
gTest();
</script>
<?php
echo "<br>";
var_dump($_COOKIE['name']);
?>
it works fine if we change to
document.cookie = 'name=hello' ;
i want to pass variable value to php in same page...i don't want to send to another page.
thanks
$_COOKIE is populated with the data sent from the browser to the server.
The JS to change the cookie won't run until the response is sent back and the JavaScript is executed.
The values in $_COOKIE won't update until you make a new HTTP request.
You can use XHR.
JavaScript (using jQuery):
$.ajax('script.php', {
data: { 'name': 'hello' }
});
PHP:
var_dump($_GET['name']);
You cant.
Ok, I think I got to explain. On your page, there is the Javascript first, then the PHP code, but it doesnt execute in that order.
First the server execute the PHP code, send the page as HTML and the javascript is executed on the client side.
If you really dont want to reload the whole page, the only way to do it is to use an ajax request to a page where your PHP code is. Simply use JQuery and replace your PHP code with this :
$('#result').load('showCookie.php');
Content of showCookie.php will be your var_dump and the page will do exactly what you want, except that you have called an additional page with JQuery.
I have this javascript code
<Script>
function getGroupId(){
var group=document.getElementById("selectedOptions").value;
var groupFirstLetter=group.substring(2);
}
</Script>
I need to pass the groupFirstLetter to a PHP function which will count how many users in this group and return the value to the javascript function.
Any ideas please?
Thanks,
You can use jQuery for that to post an AJAX request. See this example taken out of jQuery documentation:
$.ajax({
type: "POST",
url: "some.php",
data: {groupFirstLetter:groupFirstLetter},
complete: function(data){
//data contains the response from the php file.
//u can pass it here to the javascript function
}
});
The variable will be available in your PHP code as $_POST['groupFirstLetter'].
You can manipulate it as you wish then echo a response to the browser again and it will be available in the data variable.
references:
jQuery AJAX
As javascript runs on user's browser you have to do an http request to a php page. POST or GET can be used to send parameters.
To make a http call with javascript refer to this: HTTP GET request in JavaScript?
Use jQuery (jquery.com).
Dynamically load the php-file sending the variable using ajax like so:
$.post("file.php", {variable_name: value}, function(returned_data){
console.log(returned_data); //or do whatever you like with the variable
});
and your php-file will access the variable as:
$_POST['variable_name'];
I'd like to use the variable bradio in the "Having" clause of my query but i don't know how to get the content of the jquery variable and passe it into my sql query. This is a fragment of my php file. Can you tell me how can I do this?
Thanks
$conn = mysql_connect("localhost","form-test","pass");
$db = mysql_select_db("form-test",$conn);
?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(function()
{
jQuery('#event_form_field-<?php echo $event_id; ?>').click(function()
{
var bradio= jQuery("input[type=radio]:checked").val()
alert(bradio); });});
</script>
<?php
$query2 = "SELECT COUNT(wp_events_answer.answer) as rep, wp_events_answer.attendee_id as idq, wp_events_question.quota as quota2, wp_events_attendee.event_id as ev, wp_events_answer.answer as answ, wp_events_question.id as qst3
FROM wp_events_answer, wp_events_attendee, wp_events_question
WHERE wp_events_answer.question_id = wp_events_question.id AND wp_events_answer.attendee_id = wp_events_attendee.id
HAVING answer =
GROUP BY answ;";
$result2 = mysql_query($query2) or die(mysql_error());
while($row2 = mysql_fetch_row($result2)) {
}
?>
You can't mix both PHP and javascript code in one page using the method above. The problem is because PHP is executed on the server, well before any javascript can be run on the client. Therefore, the two cannot speak to each other.
The solution here is to make an AJAX request to a PHP script on your server and pass the value of the radio control to it. This would then return the required data and you can then use javascript to display this on your page.
For example:
$.post(
'myScript.php',
'bradio=' + jQuery("input[type=radio]:checked").val(),
function(data) {
// process your result here
}
);
Write the query in another php file and pass the variable using an GET or POST or maybe ajax call
No you cannot pass a js variable to php in this way. The php code is executed before the page has sent to the browser while the js code is executed after: you need instead an ajax call with the bradiovalue passed along the request (get or post)
Either you need to send an POST Request and reload the page or you need to pass the variable via AJAX to the current page and change the output on the fly. Via jquery it's pretty simple to send an AJAX request via http://api.jquery.com/jQuery.ajax/
You will need to make a request from javascript ($.get or $.post) and pass value of this radio button as a parameter. Then, on PHP side you will be able to get it from $_GET or $_POST array.
Basically I have written an AJAX script using pure javascript and I have a script that basically takes in a HTTP GET REQUEST.
e.g. script.php?id=2
I want to use this id within javascript so it can be sent via AJAX to return data from my database.
How can I access the id value. It should be possible as the value should be present within the headers of the loaded page.
Thanks!
Have a look at the window.location object, the search property has the vales you're interested in.
This function will return an object which has all the variables as keys:
function queryVars() {
var q = window.location.search.slice(1).split(/&/g);
var ret = {};
for (i=0;i<q.length;i++) {
var item = q[i].split(/=/);
ret[item[0]]=item[1];
}
return ret;
}
From your page you could use it like this:
var myquery = queryVars();
window.alert(myquery.id);
This might be just what you're looking for:
http://www.netlobo.com/url_query_string_javascript.html