HI,
I am using the following code
request.js
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = new XMLHttpRequest();
request.open("GET", "request.php?json="+JSONstring, true);
request.onreadystatechange = sendData;
alert('called');
request.send(null);
}
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
try
{
//var JSONobject = eval('(' + JSONtext + ')');
var JSONobject = JSON.parse(JSONtext);
}
catch(e)
{
var err="Error: "+e.description;
alert(err);
}
alert('1');
// notice how variables are used
try {
var msg = "Number of errors: "+JSONobject.errorsNum+ "\n- "+JSONobject.error[0]+ "\n- "+JSONobject.error[1];
alert(msg);
}
catch(ee)
{
var errr="Error: "+ee.description;
alert(errr);
}
}
}
The php function I have used here is request.php
<?php
// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);
// do something with data here
echo "Decoded string - ". $decoded;
// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';
// encode array $json to JSON string
$encoded = json_encode($json);
// send response back to index.html
// and end script execution
die($encoded);
?>
I'm calling this JavaScript function from a HTML page request.html
<html>
<head>
<script src="request.js">
</script>
</head>
<body>
call<br>
</body>
</html>
The problem here is I was getting Syntax Error at the line:24
var JSONobject = JSON.parse(JSONtext);
if I was using
var JSONobject = eval('(' + JSONtext + ')');
I was getting " ) Expected Error "
After that I deleted browser cache. Restarted the browser, now the code seems working very fine.
You should verify JSON format, then look up there - http://ru.wikipedia.org/wiki/JSON. You can get an idea.
Related
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>
My javascript code:
function _(selector){
return document.querySelector(selector);
}
function submitForm(){
var data = {
name: _("#name").value,
email: _("#email").value,
message: _("#message").value
}
var output = JSON.stringify(data)
var ajax = new XMLHttpRequest();
ajax.open( "POST", "/PATH" );
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
console.log('success')
} else {
console.log('fail')
}
}
console.log(output)
ajax.send(output);
}
When im trying do this with static data,it's work :
<?php
$name = "mateusz";
$to = "kaawkamateusz#gmail.com";
$subject = "kucharz";
$message = "message";
mail($to, $subject, $message);
?>
but, on example :
$name = $_POST["name"];
doesn't work.
Im trying use JSON but again, idk how get value from AJAX form in PHP.
Im never use PHP before, need help :)
EDIT
print_r show :
Array
(
[{"name":"asd","email":"asd#gmail_com","message":"12"}] =>
)
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
You say you are sending URL encoded form data …
var output = JSON.stringify(data)
… but your data is JSON encoded.
To URL form encode it use URLSearchParams.
var data = {
name: "Example Name",
email: "example#example.com",
message: "This is a message"
}
var output = new URLSearchParams(data);
console.log(output.toString());
Note limited browser support. Consider using a polyfill.
Alternatively, set the correct content type for JSON and rewrite the PHP since JSON is not supported for $_POST.
I'm trying to parse a string from a noSQL database. With difficulty.
when you access the PHP file it gives a result like this:
[{"timestamp":"2016-11-07T09:48:30.335Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:29.015Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:27.688Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:27.085Z","Id":"d7ee735f16b5"},
{"timestamp":"2016-11-07T09:48:26.577Z","Id":"d7ee735f16b5"}]
The same result is given in the network of the console.
When I then attempt to stringify the response it shows null.
Please can anyone help me access the timestamp values. Here is the current code:
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
Most likely the response hasn't returned from the server yet in this example. Also verify that an element with an id of 'demo' does in fact exist in your html document.
Add event listeners to the ajax object:
ajax.onload = loadCompleted;
ajax.onerror = onLoadError;
then create a function to handle the result:
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
Full example (updated per Bozidar's comments):
var url = 'https://jsonplaceholder.typicode.com/posts/1';
function loadCompleted() {
console.log(ajax.response)
var jsonResponse = JSON.stringify(ajax.response);
document.getElementById('demo').innerHTML = jsonResponse;
}
function onLoadError() {
//handle error logic
}
var ajax = new XMLHttpRequest();
ajax.onload = loadCompleted;
ajax.onerror = onLoadError;
ajax.open("GET", url, true);
ajax.responseType = 'json';
ajax.send();
See https://jsfiddle.net/px3mxa4n/ for a working example.
Shouldn't you wait for response before continuing with your code? Something like:
ajax.onreadystatechange = function () {
if(ajax.readyState == 4 && ajax.status == 200) {
// do what you need like
var jsonResponse = JSON.stringify(ajax.response); // maybe JSON.parse and then iterate trough array of objects to create individual HTML elements?
// .......
}
}
This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 7 years ago.
I'm able to send JSON Data to server through Ajax as i can see it in params of My Browser Developer Tool => Network but i get No Response Even if try to Print $_REQUEST, $_POST I get just the Cookie Value but not data which I have send
I'm Following From MDN https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Here what I've tried, I'm trying to send data to server without jQuery Ajax method
After I do this on Server side
echo json_encode($_REQUEST['msgData']);
I get
Notice: Undefined index: msgData in
/path/to/url/ABC/controller/msgNotify.php
on line 24 null
jQuery(document).ready(function(){
jQuery('#msgNotify').on('click',function(){
alert("He");
var data={};
data['info']='msgNotify';
data['username']=username;
var msgData={'msgData':data};
makeRequest(msgData,'../controller/msgNotify.php');
});
});
function makeRequest(data,url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
httpRequest.onload = alertContents;
httpRequest.send(JSON.stringify(data));
}
function alertContents() {
try{
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}catch(e){
alert('Caught Exception: ' + e.description);
}
}
SERVER SIDE "../controller/msgNotify.php"
echo json_encode($_REQUEST['msgData']);
exit;
Without changing the way you are doing your POST (the JSON is in the body of the http request), you should read as follows
// extract from my Servlet class :
$content = file_get_contents('php://input');
$ary = json_decode($content , true); // prefer decoding to associative array
if ($content && !$ary) {
self::logResponseStatus('Received malformed JSON', api_request_status::MALFORMED_REQUEST);
return false;
}
$command = $ary['command'];
$apiKey = $ary['apiKey'];
// ... etc
You are sending your data as JSON string without key for getting this parametar in your request.
You could try with this:
httpRequest.send("msgData=" + JSON.stringify(data));
Your msgData will be key to getting your object {'msgData':data}. Since it's already a JSON string you don't need to use json_encode in php. If you want only to display "data" from received json you can use
$data = json_decode( $_REQUEST['msgData'] )
echo json_encode($data["msgData"]);
From node.js I would like to get JSON data from a PHP file. I thought about using the request package, but I am not sure about what to write in the PHP file in order to send the JSON back to node:
Node:
var request = require('request');
request
.get('http://IP/File.php')
.on('response', function(response) {
data = JSON.parse(data from the php file);
});
PHP:
$data = array('message' => 'HeLLO');
$json = json_encode($data);
when executing this, send $json to node
you need to print a response from your .PHP file:
$data = array('message' => 'HeLLO');
$json = json_encode($data);
print_r($json);
javascript:
var request = require('request');
request('http://IP/File.php', function (error, response, body) {
if (!error && response.statusCode == 200) {
data = JSON.parse(body)[0];
}
})