Reading json object sent via ajax in php file - javascript

I am trying to solve one problem with reading json object sent via ajax request in php file and I am keep gettin null in the console.
Javascript file
//create function to send ajax request
function ajax_request(){
console.log("hello");
var post_data = {
"news_data" : 'hello',
"news_date" : '1st march'
}
$.ajax({
url : 'index.php',
dataType : 'json',
type : 'post',
data : post_data,
success : function(data){
console.log(data);
}
});
}
//on click event
$('#news_post_button').on('click', ajax_request);
and php file which is only for testing to see what i get
<?php
header('Content-Type: application/json');
$aRequest = json_decode($_POST);
echo json_encode($aRequest[0]->news_data);
?>

Try using json_last_error function.
And print out Your post as a string:
print_r($_POST);
echo '<br /> json_last_error: '.json_last_error();
This way You will see what You got and what potentially had gone wrong.
For testing this kind of things I suggest Postman chrome extension.

You aren't sending a JSON object at all.
You are passing jQuery an object, so it will serialise it using standard form encoding.
<?php
header('Content-Type: application/json');
echo json_encode($_POST["news_data"]);
?>
If you want to actually send a JSON text, then you need to:
Set the content type of the request
Encode the data as JSON and pass it as a string to data
See this answer for an example.
To read the JSON, you would then need to read from STDIN and not $_POST as per this answer/

You can read properties of objects directly in $POST var, like this:
$_POST['news_data'] and $_POST['news_date']
You can check the post vars through the developer tools of the browser, in network tab.

The dataType property of the $.post options specifies the format of data you expect to receive from the server as a response, not the format of the data you send to the server. If you send data by the method POST - just like you do, if you use $.post - there is no need to call $aRequest = json_decode($_POST); on the serverside. The data will be available as a plain PHP array.
If you just want to get the news_data field as a response from the server, your serverside script should look something like this:
<?php
header('Content-Type: application/json');
$post = $_POST;
echo json_encode($post['news_data']);
?>
Notice, that you should check for the key news_data whether it is set.

Related

Writing to JSON file using ajax and php. Server not recieving POST

I tried following the steps in a few other stackoverflow questions, but for some reason my server is not showing any indicator of recieving a request. I know that the client is sending the request since it shows up in firefox debugger.
Here is the js method:
function writeToFile(dat) {
$.ajax({
url : 'dataSaveAjax.php',
method : 'post',
data : { 'data': JSON.stringify(dat) },
success : function( response ) {
alert( response);
}
});
}
PHP code:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, json_encode($_POST['data']));
fclose($fp);
?>
Try updating your code like that
<?php
$fp = fopen('general.json', 'w');
$writtingResponse = fwrite($fp, $_POST['data']);
fclose($fp);
echo $writtingResponse;
?>
You did not write any response and you encode json twice.
first you need to understand what is the reason and why our script does not work. First, let's look at the server part (php). First, put the data in a variable, instead of $ _POST ['data'] try to do something like:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, 'MyTest');
fclose($fp);
?>
If this does not work, most likely the reason is that you need to set the write permissions for the file (Chmod).
If everything is recorded correctly, then something is wrong with the client part of your site. When it comes to POST / GET queries, I usually use Postman. It allows not only to test requests, but also to generate code. If you run a query through Postman and the result is written to a file, then the error is unambiguous in javascript. Try to press F12 in the browser and go to the js console, there you will see an error message. Do you use jQuery in the example, and is it connected? Is it connected before you try to execute the script?
Try to look at the data that you are trying to send using console (F12)
console.log(JSON.stringify(dat));
Are your data really going to be collected, or are you trying to send empty data to the file?

can not Send data to php file using ajax

I have this php file graph.php
$host = $_POST['hostname'];
echo $type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
and I trying to send data to this file using this ajax code
var type_char='fortigate_cpu';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: { hostname:hostname,type_char:type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
the result when I send data to that file is
fortigate_cpu as a value of type_char variable
when I opened error.log file in apache logs
I have this message
include(): Failed opening 'graphs/.inc.php' for inclusion (include_path='.:/usr/share/php')
as you see the value of fortigate not included in include function even if the char_type variable is send by ajax and printed in page
include file must be as this
include( 'graphs/fortigate_cpu.inc.php')
why type not included in the include session even if the variable is received from ajax
As was mentioned by other users in the comments, maybe your issue is that you are setting type to a different value after including rrdtools.inc.php .
Try randomizing ( changing the name), of the type variable:
$host = $_POST['hostname'];
echo $type123456=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type123456.'.inc.php');
It's the only thing I can think of, since both I (and others) have tested your code.
(both front-end and back-end).
PS: Include using post param is a bad practice.

how to send json array from controller to view in CodeIgniter

I have a function in my controller:
function getAllExpense()
{ $date=$this->frenchToEnglish_date($this->input->post('date'));
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
return json_encode($allExpenses);
}
In the view, I need to do an ajax_call to getAllExpense, but I need also to retrieve the result returned by getAllExpense in case of success(and I can't do this). Here is my view
function searchExpense()
{
var date= $('#dateSearch').val();
$.ajax({
type:'POST',
url : '<?php echo site_url()."/public/expenses/getAllExpense/"; ?>',
data :'date='+date,
success:function(data)
{ $('#searchExpense').toggle();
}
});
}
and finally the form :
<div id="searchExpense" class="toogle_form" style="display:none">
<label><strong>Vos depenses :</strong></label>
<?php
if (isset($allExpenses) && ! empty($allExpenses))
{
foreach ($allExpenses as $expense)
{
echo $expense['id_depense'] ;
echo ' ';
echo $expense['commentaire'];
echo '</br>';
}
}
else
{
echo 'Vous n\'avez pas eu de depenses pour cette date';
}
?>
</div>
This does not show anything on the browser.
I can't use the method of sending data by loading the view in getAllExpense because I already load it in the function index.
Could anyone help me please?
In your controller function getAllExpense, try echoing your json data with a header rather than using return:
Change this:
return json_encode($allExpenses);
to:
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($allExpenses);
The url:
Reading it backwards I understand getAllExpense to be your function name and expenses to be your controller name... What is /public/?
The data:
Currently you're using data :'date='+date. This is incorrect. $.ajax expects an object as the data parameter. Use data: {date: date}.
Where's the dataType?
If you're expecting json from the server, tell $.ajax this so it can parse the response properly. Use: dataType: 'json'
Your success function
It helps for debugging to call console.log() on the returned data. Inside the callback use: console.log(data); Then, open up your web tools. If you're using Chrome press ctrl+shift+j and inspect the console tab when firing your AJAX request. If you head over to the network tab and click on the most recent request (at the bottom) you can view the HTTP response as well.
"and finally the form :"
You didn't include a form.
Isolate the problem:
You're much better off inspecting the AJAX response using Chrome's Network tab as I've mentioned, but you could also isolate the issue to a client one or server one by changing your function temporarily to:
function getAllExpense(){
//$date=$this->frenchToEnglish_date($this->input->post('date'));
$date = "12/21/2012"; /*or whatever your date format is.*/
$id_user=$this->session->userdata('id_user');
$where=array('date'=>$date, 'id_user'=>$id_user);
$allExpenses=$this->expenses_model->get_all('depenses',$where);
//return json_encode($allExpenses);
echo json_encode($allExpenses);
}
And calling getAllExpense directly in the URL bar. You'll be able to see the raw json and determine if it's in a format you're happy with.

how do i use the success function with an $.ajax call

I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};

Both .getJSON() and .ajax() not working for REST API call

Can someone explain me how to make a REST call using jQuery/Javascript? I tried using the .getJSON() and .ajax(), but neither helped me.
This is the REST URL :
http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&date=2010-01-15&format=json&key=API_KEY
Code:
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode='+zip+'&format=json&key=**<KEY HERE>**',
function(data)
{
alert(data.AQI);
}
);
$.ajax({
url: 'http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode',
type: 'GET',
data: 'zipcode='+zip+'&format=json&key=**<KEY HERE>**',
success: function() { alert('get completed'); }
});
there are a couple of problems. First, you need to add &callback=? to the end of the querystring to allow the crossdomain.
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D&callback=?',
function(data)
{
alert(data.forecast[0]);
}
);
You will then get an Uncaught SyntaxError: Unexpected token : error. This is because you are expecting json data, but the headers on the server are sending text/html - not application/json. Take a look at the console when you run this fiddle, you'll see the errors.
Therefore, you can't get the data from cross domain because you have to be using jsonp - which requires the header to be sent correctly.
If this is your api, then you just need to send the correct header, otherwise, you need to get with the developers there and ask them to fix it.
Alternatively
If neither of those above options work, you could always create a proxy script that would get the contents of the json feed for you and echo it out. Here's one in PHP:
<?php
// myproxy.php
header('Content-type: application/json');
$zip = $_GET['zip'];
$results = file_get_contents('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=' . $zip . '&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D');
echo $results;
?>
Then, you would just point your $.getJSON to this script on your server:
$.getJSON('/myproxy.php?zip='+zip,
function(data)
{
var mydata = jQuery.parseJSON(data);
alert(mydata.forecast[0]);
}
);

Categories