What is the best way to transfer the following outputted value into a php variable?
$(document).getUrlParam("id");
Through an ajax post.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You should use JSON format to send and receive data from javascript to PHP. For example
function sendData(){
//with jquery, you can use `.post()`, `.get()` or for more control `.ajax()`
$.post(
//URL to send the data
url,
//data being sent, transformed to JSON
{dataSent: JSON.stringify(clientSideData)},
//Do something after sendind the data to server
function(dataReceived){
//transform data from json format to javascript object
var dataLog = jQuery.parseJSON(dataReceived);
//Do stuff
}
)
}
PHP:
//Receive data from POST
var phpVar = json_decode($_POST['dataSent'])
//send data back to javascript
echo json_encode(phpVar)
While all of these answers will get the value from javascript into the PHP script, I'd wonder if you need javascript at all.
From what I can see from a brief google the getUrlParam plugin is useful for getting and then breaking down the URL. Have you had a look at the variables available through $_SERVER? I'm sure you'd be able to find something suitable in there.
Related
In my php file 'login_success.php', I have a the variable $_COOKIE["user"]
Would it be possible to return that variable within a jQuery Ajax statment such as this one. ive made a guess with Var UserName =:
function StartAjax(NameID){
$.ajax({
type: "POST",
url: "login_success.php",
cache: false,
data: "name=Peter&location=Sheffield",
success: function(html, status){
$("#"+NameID).append(html);
//$('#status').append(status);
var userName =
}
});
login_success.php:
echo $_COOKIE['user'];
Ajax asks for the page, returns the output/content (what is echoed). Please note: Javascript is client side. PHP is server side. So you can't directly access PHP variables, but as done above, PHP can "give" the client the info it needs. If you're sending a lot of data, you can json_encode it for the ajax request. (you can learn about JSON on your own)
Also note, Javascript can access cookies, but I'm assuming this is just a sample question.
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'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));
i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.
I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.