How to retrieve data from jQuery.Post() in PHP? - php

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 },

Related

Json Returning [object object] instead of values

I am trying to extract the values ​​of a json but when I return it I get an object object.
Something I did wrong in decoding? this is the decoding code in php
<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
?>
this is the function code
<script>
$(function() {
$("#btnbuscar").on('click',function(){
var direccion='servicio.php';
$.ajax({
type:'get',
url:direccion,
success:function(datos){
var campo=eval(datos);
alert(datos[0]);
}
});
return false;
});
});
</script>
Uwhen you write this:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
Or fix your js like this:
alert(datos[0][0]);
Here is a simple way to read your JSON without Ajax but with using $.getJSON
On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"
On your javascript use:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.
For example:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
Welcome to stackoverflow! We hope you like it here.
As already pointed out by #Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

$.post() receive variable back from php

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);
?>

Cannot read JSON object returned from PHP

I am sending a JSON object to a PHP file, The PHP does some manipulation and returns a JSON string:
$('button#indexOpener').on('click', function() {
var aUsername = $('input#edUsername').val();
var aPassword = $('input#edPassword').val();
if (($.trim(aUsername) != '') && ($.trim(aPassword) != '')) {
var str = $("#form_login :input").serializeArray();
$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
alert(data.edUsername);
});
}
else {
alert('Please insert a valid username and password');
alert("<?php echo URL; ?>/ajax");
}
});
the PHP echoes a JSON object:
echo json_encode($_POST);
but when I try to alert the data with jQuery:
function(data) {
alert(data.edUsername);
}
is displaying the message undefined. I am sure it is something stupid but I cannot see what I am doing wrong, can you help?
I see no dataType set for $.post(). jQuery will try to recognize returned content type, but you need to set correct headers. So, you need to add:
header("Content-Type: application/json");
before echo json_encode, or you should set dataType:"json" in JS code (fourth parameter of $.post()):
$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
alert(data.edUsername);
}, "json");
This way, jQuery will know that the data returned is in JSON format and should be parsed. Without it, jQuery will check the Content-Type header and apply parser according to it. Suppose if no custom content type headers set, it will return return data as HTML. Actually, that is a usual string.
If I just alert(data) is returning {"edUsername":"qqq"
"edPassword":"qqq"} but if I alert alert(data.edUsername); I get
"undefined"?
JSON is a regular string which should be parsed on client side. jQuery detects your response as plain text or HTML and does not parse JSON to Javascript object. In case of data being an object, you would get [object Object] in alert window.
I think this should be this way using $.getJSON():
var str = $("#form_login").serialize();
$.getJSON("<?php echo URL; ?>ajax/checklogin", {data:str}, function(data){
alert(data.edUsername);
});

Sending JSON via AJAX to PHP using jQuery

I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.
Here is my code,
Javascript/jQuery:
function test(){
var selects = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: newArray }
});
}
PHP:
<?php
$json = $_POST['json'];
$person = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $person);
fclose($file);
echo 'success?';
?>
It creates the file, but it is completely blank, any idea what it could be?
Thanx in advance!
You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.
data: { json: JSON.stringify(newArray) }
Hope this helps
Don't use an array.
use a simple string like this:
var o = '[';
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
o += '{ "id": "'+id+'", "value": "'+val+'" },';
});
o = o.substring(0,o.length-1);
o += ']';
and in the ajax just send the string 'o'
data: { json: newArray }
in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);
You should set a contentType on your ajax POST. I would use contentType: "application/json";
You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.
No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.

Categories