Pass json decode variable to php - php

I have a JQuery login request as follow using Json encode / decode:
$('#btn_signin').click(function(){
var parameters = $('#signin_form').serialize();
$.ajax({
url: baseurl + 'site/loginRequest',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(output_str){
if(output_str.usertype == "a"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_a');
}else if(output_str.usertype == "b"){
var sess_email = output_str.email;
window.location.replace(baseurl + 'site/page_b');
}else{
$('#result_msg').html(output_str);
}
}
});
});
As seen on the script with var sess_email how can I pass it to php variable?
Any advise? thanks.

I'm not sure whether I understand this right, but if you want to assign the value of a PHP variable to a Javascript variable you could do something like this:
var sess_email = <?php echo $someVar ?>;
If your looking for the other way around, passing a var from Javascript to PHP, then this is the way to go:
Send it to the server using an AJAX request (I usually JSON encode it then).
JSON decode it on the server and assign it to a PHP variable
Example:
In your case you sended the javascript variable 'parameters' to the server. Then server side you would do this in PHP:
$parameters = $_POST['parameters'];

You can't pass javascript variable to PHP variable. But some workarounds available.
What you are trying to do exactly?

Related

ajax / json output must be an other format

Hi for an jquery map I get the values over ajax. The format for the map must be
var new_sample_data = {"af":"16.63","al":"11.58","dz":"158.97",...};.
I have tested it with var new_sample_data = {"af":16.63,...}; and all works good. But If I take it over jason. It doesn't work. What I must change?
The php testcode:
$sample_data[] = array("de","$de");
echo json_encode($sample_data);
The javascript code:
$.ajax({
type: "POST",
url: '../mail/assets/includes/geodata1.php',
data: {datum1: Date.today().add({days: -29}).toString('yyyy-MM-dd'), datum2: Date.today().toString('yyyy-MM-dd')},
dataType: 'json',
success: function(data)
{
var new_sample_data = data;
In Firebug I see the response is [["de","4"]]. But how I can change it to the format the map need?
You need to create an associative array in PHP:
$sample_data = array("de"=>"$de");
Then encoding it should result in a proper JSON String that can be parsed into a JavaScript Object.
To see the proper content of new_sample_data in JavaScript, use console.dir(new_sample_data);, it will list the object's attributes.
You can access the value of your new attribute this way in JavaScript:
console.log(new_sample_data.de);
Your php array should set the index of de to the variable like such:
$sample_data[] = array("de" => "$de");
That wasy $sample_data["de"] will = "$de";
$sample_data['de'] = $de;
it will work as you expected

Jquery set PHP $_GET array

Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

How to unserialize a serialized array sent to the server using GET method with a jQuery Ajax call?

I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.

Use $_GET, $_SERVER variables in Javascript (jQuery / AJAX)

So, heres a super simple jQuery / AJAX comment system step one. Step two is the PHP to insert the data into the DB. I need the $_GET['variable'] for the page / a $_SERVER['variable'] to store into the DB. How can I get these in the jquery. I can't just say $spot = $_GET['spot'] or $url = $_SERVER['FILE_SCRIPTNAME'] in the PHP. It won't pick it up. I has to be sent through the jQuery / AJAX. How can I do this?
$(document).ready(function() {
$('#submit_comment').click(function() {
var comment = $('#place_comment').val();
// Somewhere here set the $_GET['variable'];
$.ajax({
type: 'POST',
url: 'http://localhost/app/comment/comment.func.php',
data: 'comment='+comment,
success: function(data) {
$('#replies').html(data);
}
});
});
});
If I understand what you are trying to do correctly, you can try something like this to use server-side PHP variables in your client-side javascript.
var comment = $('#place_comment').val();
var myVariable = '<?php echo $_GET['variable'] ?>';
You can't do this like this : javascript is client-side and PHP $SERVER array is server-side.

$.post() jQuery and PHP

Here is a piece of code :
$username="anant";
$name="ana";
echo $username;
echo $name;
Now if using jquery $.post() i want to retrieve $username and $name ,how would I do it ?
Thanks!
I assume the code is your php based response to the $.post call. If all you are returning are values then the easiest thing to do is to return a json response. For example...
PHP Script:
$values = array(
'username' => 'anant'
'name' => 'ana'
);
header('Content-type: application/json');
echo json_encode($values);
JS $.ajax call:
$.ajax(
url: '/path/to/script.php',
type: 'post',
dataType: 'json',
success: function(data){
alert('Username: '+data.username);
alert('name: '+data.name);
}
);
Or if you wanna stick with $.post then follow kovshenin's answer for the syntax using $.post. But be sure you use my php code witht he header() call to properly set the content type of the http response. I just prefer to use the long hand.
I'm not a php expert but try something like:
php
$username="anant";
$name="ana";
echo json_encode(array("username"=>$username,"name"=>$name));
js
$(function() {
$.get('test.php', function(data) {
alert(data.username + ':' + data.name);
});
});
I hope this helps!
You will be better off with json_encode which javascript will understand just fine:
$res = array('username' => 'anant', 'name' => 'something');
echo json_encode($res);
Then use the following code in jQuery to retrieve the values:
$.post('/something', function(response) {
alert("Username is: " + response.username + " and name is: " + response.name);
}, "json");
Cheers.
Now that I know what you are trying to do post expects a fourth parameter the encoding type. If you set it to JSON you would encode your data like so
echo '{"username": ".'$username.'", name":"'.$name.'"}'; //Json may not be perfect
you can access it in jQuery using
data.username
First thing is you have to do a GET not a POST. You may need to change your server side code a little bit so that front end had a clue of how to identify different values (JSON will be better) but a simple , should work fine.
$username="anant";
$name="ana";
echo "$username,"
echo "$name";
your output will be then something like Anant001,Anant your username, name.
Then use a simple jQuery call to get it and split it by , and here is an example..
$.get('/getnames', function(data){
var tokens = data.split(",");
var username = tokens[0];
var name = tokens[1];
});

Categories