how to send json array from controller to view in CodeIgniter - javascript

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.

Related

Reading json object sent via ajax in php file

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.

Passing Variable via AJax

Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.

unable to get the data value of ajax on another page

I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];

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