I send from javascript 2 values to a php.
function sendValue(str,str2){
$.post("/phpfolder/updaterate.php",{ sendValue: str, sendValue2 : str2 },
function(data){
$('#display').html(data.returnValue);
}, "json");
}
My php file executes ....
and I want to send back a variable $x
<?php
...
echo json_encode($x);
?>
where and what i`m missing?
I searched for examples, but nothing...
json_encode can take an array as parameter.
You want to display data.returnValue. So construct an array like this:
...
echo json_encode( array('returnValue' => $x) );
exit()
Try to test these things
function sendValue(str,str2){
$.post("/phpfolder/updaterate.php",{ 'sendValue': str, 'sendValue2' : str2 },//add ' to the name of the variables
function(data){
alert('inside the function');//test if is getting inside the function
$('#display').html(data.returnValue);
}, "json");
}
In the php you have to return an array.
<?php
$x['returnValue'] = 'whatever';//The key of the array has to be the name used in the function(data)
echo json_encode($x);
?>
Related
I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);
I am currently trying to send a string to a to a php script which will eventually return a JSON file.
Here is code i'm using to send the string:
var str = "testString";
$.post("php/getTimes.php", str,
function(data){
console.log(data.name);
console.log(data.time);
}, "json");
In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.
You have to name attributes in POST data either with serialized string:
var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
or with map:
var data = {
str : "testString"
};
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
To handle this variable in PHP use:
$str = $_POST['str'];
In getTimes.php:
<?php
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>
Also adjust:
$.post("php/getTimes.php", str,
to
$.post("php/getTimes.php", { string: str },
The JS doesn't work with the PHP script. I get no response.
Here's the PHP script:
<?php
$a = array('data' => 'Hello');
echo json_encode($a);
?>
Here is the JQuery Script:
function getCityAndState(data, location)
{
var jsonString = {"zipCode": data};
var outR = outputResults
alert("JSON String:" + jsonString.zipCode);
if (location === "living")
{
$("#livingCityField").val("");
$("#livingStateField").val("");
alert("Inside getCityAndState: " + location);
//$.get("testfile.php",
// {zipCode: data},
// outR,
// 'text'
// );
$.getJSON("testfile.php",function(d) {
alert("JSON Data: " + d.data);
});
}
What am I doing wrong?
alert("Inside getCityAndState: " + location); does execute as expected but otherwise nothing happens. There is no exception thrown, no error message, nothing. It doesn't return any data at all.
I'm using Aptana 2 as an IDE, in case that makes a difference.
Your PHP script is missing the Header, it should be something like:
<?php
header('Content-type: text/json'); //added line
$a = array('data' => 'Hello');
echo json_encode($a);
?>
The second parameter of jQuery's $.getJSON() function isn't the callback that returns the data, it is supposed to be a map or string containing additional data to be sent to the server. The callback function is the third parameter.
I didn't test this, but it should be something along these lines:
$.getJSON('ajax/test.json', "", function(data, textStatus, jqXHR){
//In here you should have access to the data return by the server thourgh the "data" variable.
});
EDIT: As very well pointed out by #Rocket and #Tadeck, optional arguments can be omitted and "rearranged" since jQuery checks the argument's type. This is the case with the second and third arguments of the getJSON() function.
Given that, and although this shouldn't be the source of the problem, it makes sure the function receives all the arguments in the expected order, and it should yield the same result as omitting the second parameter.
Documentation: http://api.jquery.com/jQuery.getJSON/
I have a function which sends specified form data to a php processing page.
function get(){
$.post('data.php',{"name":$('#Fname').val(),"age":$('#age').val()},
function(output){
$('#Rage').hide().html(output).fadeIn(1000);
});
}
After posting the script takes all the outputs from the php page (ie: echo's) and puts them all the in #Rage div. $('#Rage').hide().html(output).fadeIn(1000);
I am wondering is it possible to have two different outputs for each of the inputs.
By this i mean an echo response for "name":$('#Fname').val() goes to #Rname and an echo response for "age":$('#age').val() goes to #Rage.
I hope i have explained myself well enough.
Cheers guys.
You could have your PHP script return some JSON with those keys, and in the callback function, assign the values to their respective elements.
Say you had the PHP script return this:
header('Content-type: application/json');
$return_obj = array('age' => 'someAge', 'name' => 'someName', 'success' => true);
echo json_encode($return_obj); //{"age": "someAge", "name": "someName", "success":true}
You could do this on the client side:
$.ajax({
url:'data.php',
type:'POST',
data: {"name":$('#Fname').val(),"age":$('#age').val()},
dataType: 'json',
success:function(json) {
if(json.success) {
$('#age').val(json.age || '');
$('#Fname').val(json.name || '');
}
}
});
I am trying to decode JSON in php I sended using an ajax call in javascript (jquery).
The javascript code:
var editSchedule_data = {
'action' : 'editSchedule',
'eventid' : $('#eventid').val(),
'pixels_per_minute' :$('#pixels_per_minute').val(),
artists: {
artist: []
}
}
$('.artist').each(function(index) {
var id=$(this).attr('id');
id=id.split('_');
editSchedule_data.artists.artist.push({
'artistid' : id[0],
'stageid' : id[1],
'left' : $(this).offset().left-$('.artists').offset().left,
'width' : $(this).width()
});
});
$.ajax({
type : "POST",
url : "callback.php",
data : editSchedule_data,
dataType : "json",
async : true,
success : function(json) {
if(json.success) {
showSucces(json.message);
}
else{
showError(json.message);
}
},
error: function(error){
alert("An error occurred: "+error.message);
}
});
The php-code:
$clean = sanitize($_POST);
echo(json_encode($clean['artists']),
json_last_error());
echo(json_decode($clean['artists']),
json_last_error());
My output:
encode:
{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]}
0
decode:
0
Can someone tell me how to get the decode function to work?
Why are you trying to use json_decode there? You already have the data as array in $_POST.That's why json_decode fails and retuns NULL...it expects a properly formated string and you are passing it an array.
If the dataType : "json" parameter confuses you, it specifies the type of the data you are expecting back from the server not the type of the data you are sending.
You shoud simply process the data from $_POST, create your response , apply json_encode on it and echo the resulted string.
json_decode($clean['artists']); is giving you an object, that's why echoing it doesn't show anything. Try print_r() to see what's inside the object:
// Will show you the whole PHP object
print_r( json_decode( $clean['artists'] ) );
it is much better if you will use this. when fetching data from the database
$.getJSON("callback.php",function(json){
$('#div to update').html(json[0].databasefield); // 0 if query is only 1 result
}); // when there are many of them use for loop
on your php you should encode it using json_encode(array values);