Here i am passing the javascript array values to php using the jquery ajax.now i want to recive the data in php script. how should i do it?
php:
<?php
$list = array
(
//here i want to get the ajax array data
);
$t = time();
$file = fopen("xls/$t-userinput-input.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
Jquery:
function arrayPush(val1,val2) {
uservalues.push(val1,val2);
passvalues()
}
function passvalues(){
$.ajax({
type: "POST",
data: {info:uservalues},
url: "write.php",
success: function(msg){
alert("Thankyou")
}
});
}
Because you're POSTing the data, just try with:
$list = $_POST['info'];
First of all, read it from PHP POST variable:
$jsonRawData = $_POST['info']
Next, decode it to have php array - http://php.net/manual/en/function.json-decode.php
$decoded = json_decode($jsonRawData);
You can always peek what's inside PHP variable with var_dump.
Related
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
I am sending a JSON object from js to post.php
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:json_str}
});
but I am not able to retrieve the result in a post.php file
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
I have no idea about your $jsonr_str.
It's my example:
$json = '{"people":[{"user":"Amy"},{"user":"Lee"},{"user":"David"}]}';
// covert into object
$data = json_decode(stripcslashes($json));
echo "People[0]=" . $data->people[0]->user;
// or covert info array
$data = json_decode($json, true);
// Using print_r()
echo "<pre>" .print_r($data, true). "</pre>";
Try like this
var data = {
people:{user:'Joe Cooper'}
};
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:JSON.stringify(data)}
});
<?php
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
Here is my code to call AJAX and get the response from another PHP file:
$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
function(data){
$('#fare').html(data);
$('#loading_spinner').hide();
});
ajaxscript.php file
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
This code gives me the fare at the time of $('#fare').html(data);
But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php:
echo $json['city'];
After doing this, it gives me 30580Islamabad
How can I store these two values separately in JavaScript? I need them for future work.
You are doing everything backwards
Your PHP should be
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
//$json = json_decode($jsonData,true);
echo $jsonData;
As you already have a JSONString to send to your javascript.
Then your javascript will recieve a javascript object in the data parameter of
$.post( '<?php echo get_site_url(); ?>/ajax-script/',
{pickup:pickup,dropoff:dropoff,km:km},
function( data ) {
$('#fare').html(data.fare);
$('#city').html(data.city);
$('#loading_spinner').hide();
}, "json");
Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect
Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display
like below;
$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
in jquery
function(data){
var tdata = data.split("^^");
$('#fare').html(tdata[0]);
$('#loading_spinner').hide();
});
Well i have this php for get the value of mysql.
I get two rows in this query.
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);
and this is my Jquery code
function traerAcciones(pnc){
$.ajax({
url: 'php_ajax/select_acciones.php?pnc='+pnc,
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
alert(this.accion);
});
}
});
}
when i execute this code the alert show me "undefined".
The $.each loop works fine but the value is the problem.
Please help and sorry for my bad English
Try to pass the value and the Index as parameters, this is how it works:
$.each(data, function(index, value) {
alert( value.accion );
});
Might also be a problem with the data object not containing what you think it does, do a
console.log(index, value);
inside your loop and a
console.log(data);
before the loop and you will see what you have and how to handle it.
Hope it helps!
Currently you are returning the array of your first row only. So to retrieve both you might want to do this:
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);
Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.