convert a value from json_decode to a string - php

how do i convert my value from json_decode to string so i can pass in a the string value to check if an email exists here is my code.
my json is in this format:
{email:'test#test.com' }
PHP:
$var = json_decode($_REQUEST["email"], true);
$result = $membership->CheckEmailAddress($var); // get $var to become a string
It looks pretty ugly im just starting php and Im not getting very far aye lol.
jquery:
$('#checkemail').click(function () {
var json = {
email: $('#email').val()
};
$.post('http://' + location.host + '/buyme/include/getemailaddress.php', {
'email': 'test#yahoo.co.nz'
}, function (res) {
var obj = JSON.parse(res);
alert(obj.message)
});
});
also how do I put my json variable in my $.post function cose thats the value I want to put there

what value in $_REQUEST["email"] if it's a json value you are showing above then try
your $var is a json object you can fetch email value like not use $var it's an array
tried this :-
$val = json_encode(array('email' =>'test#test.com'));
echo $val; //output {"email":"test#test.com"}
$var = json_decode($val, true);
print_r($var); // output Array ( [email] => test#test.com )
echo $var['email']; //output test#test.com

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 return single variable and an array variable

I have a comment form that requests a newtimestamp and newcomment variables. The newtimestamp variable is a single variable and the newcomment variable is an array returned from a foreach loop.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
}
I then use ajax to prepend the new comment's and set the newtimestamp on a hidden input field.
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajaxrequest.php',
data:$(this).serialize(),
type:'POST',
dataType: 'JSON',
success:function(data, response){
$("#posts").fadeOut(300);
$("#posts").prepend(data.newcomment);
$("#time").val(data.newtimestamp);
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');
console.log(data);
},
error:function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
});
The above method gives me a success message in console, the prepend works but only shows 1 result everytime when it should show all results from the last timestamp. The prepend and setting the value of the hidden input field do not work if the user posts a second, third etc comment.
console:
Object {newtimestamp: "2014-11-19 07:59:48", newcomment: "<div>a new comment</div> 1"}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
I need to return the newtimestamp variable as a single variable (not an array) and set this on a hidden input field value, and I need to return the newcomment variable as an array that can be prepended to a div.
How can I do this?
Change your php file. I am not sure this is you are expecting.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp[] = $now;
$newcomment[] = "<div class=post>$var1</div>";
}
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
Rewrite your php code like this
$data = array();
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
$data['data'][] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
echo json_encode($data);
now the JSON response will look something like
{"data" : [{"newtimestamp" : 72345654,"newcomment" : "comment data"},{"newtimestamp" : 72345654,"newcomment" : "comment data"}]}
loop through array of objects using jQuery each. The final code will look something like this.
$.each($response.data,function(index,value){
$("#posts").prepend(value.newcomment);
$("#time").val(value.newtimestamp);
})
NOTE: either send application/json header (so that the response will be parsed and converted to an js object by default) or parse it after receiving. This action should happen before the each loop
That's because you are echo multiple JSON string. You need to echo a single JSON string with all data.
Try something like the code below, this worked for me. You only need to fit this into your jQuery and PHP code.
<?php
$jsonArray = array();
$array2 = array(array('var'=>1),array('var'=>2));
foreach ($array2 as $print2)
{
$var1 = $print2['var'];
$newtimestamp = time();
$newcomment = "<div class=post>$var1</div>";
$jsonArray[] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
print_r($jsonArray);
$data = json_encode($jsonArray);
?>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var data = jQuery.parseJSON('<?=$data?>');
$.each(data, function(item, value){
console.log(value['newtimestamp']);
});
</script>

Can't print the json from ajax post using json_decode

I am using ajax to post data to a php script for work to be done... Basically, I'm taking all the form variabes, and creating json... Then taking this json and sending it to the controller script:
function createJSON() {
jsonObj = [];
$("input[class=form-control]").each(function() {
var id = $(this).attr("id");
var value = $(this).val();
item = {}
item [id] = value;
jsonObj.push(item);
});
jsonData = JSON.stringify(jsonObj);
var request = $.ajax({
url: "../../../../ajax/signupController.php",
type: "POST",
data: jsonData,
dataType: "html"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
My code gets to the php script fine, and when I use "print_r" in php to print the output, I get this:
Array
(
[0] => stdClass Object
(
[mail-firstname] => FName
)
[1] => stdClass Object
(
[mail-lastname] => Lname
)
)
My problem is, I can't GET AT the elements... I have tried:
$data = json_decode(file_get_contents('php://input'));
foreach ($data as $key => $value) {
print "<p>$key | $value</p>";
}
but I can't get at the array elements... I get an error... What am I missing about accessing the array after decoding the file contents?
Thanks.
Update:
Modified foreach:
foreach($data as $key=>$value){
print $value->ccyear;//now I can get at individual elements
}
BUT ANY VALUE THAT HAS A DASH IS CAUSING THE SCRIPT TO FAIL... For example, if the name is "mail-firstname" PHP thinks it's mail AND firstname...
The problem is that your values are nested an extra level in your data. And they each have different keys, so it's hard to get at them. It would be better if you use the id as the keys of the top-level array, rather than nesting them:
jsonObj = {};
$("input[class=form-control]").each(function() {
var id = this.id
var value = this.value;
jsonObj[id] = value;
});
Then you should change your PHP to use the second argument to json_decode(), so you get an associative array instead of a stdClass object:
$data = json_decode(file_get_contents('php://input', true));
I'm not really sure why you need to send JSON. Why not just use:
data: jsonObj;
Then you can access the inputs as $_POST['mail-firstname'], etc.

Trying to get integer out of json for current time comparison

<?php
date_default_timezone_set('America/Los_Angeles');
$date = date('Gi', time());
?>
<script type="text/javascript">
var locTime = <?php echo json_encode($date) ?>;
var jTime = null;
$.getJSON( "urltojson", function(result) {
console.log("sucess1");
jTime = result["crossroads"]["monday"][0];
console.log("sucess2");
console.log(jTime)
})
</script>
json -
{ "crossroads":
{
"monday": [
{"breakfastopen": 700},
{"breakfastclose": 1100},
{"lunchopen": 1100},
{"lunchclose": 1400},
{"dinneropen": 1700},
{"dinnerclose": 2100}
]
}
}
in console jTime output is always
Object {breakfastopen: 700}
How do i get jTime to trim down and show only '700'?
What I'm trying to do is get the local hours to compare with the integer in json array. So far i have no luck of brining the json variable to jTime and have it compare against locTime.
It should be returning an object so to get access it should be
data.crossroads.monday[0].breakfastopen
{} denote objects [] are arrays

how to convert a JSon object to an array in Javascript

I am returning array as
$array = array {
'id' => 1,
'name'=>krishna,
}
echo json_encode($array);
exit;
from an ajax call
How can I convert this json value to java script array?
This is my actual data
var data = [{
"candidate_notes_id":"1",
"candidate_id":"38",
"subject":"test",
"description":"t‌estestsete\netestes\n\n\nsteetet",
"private":"0",
"created_date":"2012-09-14 11:55:13",
"updated_date":"2012-09-14 11:55:13",
"updated_by":"admin"
}]
var newArray = jQuery.parseJSON(data);
alert(newArray);
return false;
result :
var newArray = JSON.stringify(data);
var date_split = newArray.substr(1,newArray.length-2);
var newData = date_split.replace('\n','<br>');
var newArray = $.parseJSON(newData);
alert(newArray.candidate_notes_id);
alert(newArray.candidate_id);
alert(newArray.subject);
alert(newArray.description);
If you are using jQuery then you can use jQuery.parseJSON(YOUR_AJAX_RESPONSE_DATA); which will convert json to JS object
Link: http://api.jquery.com/jQuery.parseJSON/
Please look at an answered question ...
You will find how to convert a json to an array.
JSON to javaScript array
var array = [];
$.each(JSONObject, function(i, obj) {
array.push([obj.id.value, obj.name.value]);
});
You can parse it using
obj = JSON.parse(responseData); // replace `responseData` with your XHR response variable name
in your success callback function. Then convert it an array as follows
var myArray=[];
myArray[0]=obj.id;
myArray[1]=obj.name;
but first of all your
$array = array {
'id' => 1,
'name'=>krishna,
};
should be
$array = array (
'id' => 1,
'name'=>'krishna'
);
DEMO.

Categories