jQuery and array of objects - php

$(document).ready(function () {
output = "";
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
success: function (output) {
alert(output);
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: output
});
}
});
});
I have code like this and if I copy the text verbatim out of my alert box and replace
events: output
with
events: [{ id: 1, title: 'Birthday', start: new Date(1355011200*1000), end: new Date(1355011200*1000), allDay: true, url: 'http://www.yahoo.com/'},{ id: 2, title: 'Birthday Hangover', start: new Date(1355097600*1000), end: new Date(1355097600*1000), allDay: false, url: 'http://www.yahoo.com'},{ id: 3, title: 'Sepotomus Maximus Christmas', start: new Date(1356393600*1000), end: new Date(1356393600*1000), allDay: false, url: 'http://www.yahoo.com/'},]
Everything works just fine. What can I do to fix this problem? I though that using events: output would place the text in that location but it does not seem to be working.
Thank you all kindly in advance for any comments or answers!

Since you haven't given us much information, i'm going to take a shot in the dark and say that the browser is interpreting the json as text. So add a dataType property to the ajax call so that jQuery can parse the return as json.
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
dataType: 'json'
......

If you are getting that string in your alertbox.. You need to use JSON.parse() to parse the string into a javascript Object
change
events: output
to
events: JSON.parse(output)
According to the documentation
An "event source" is anything that provides FullCalendar with data about events. It can be a simple array, an event-generating function that you define, a URL to a json feed, or a Google Calendar feed.
Since version 1.5, Event Objects can have "options" associated with them. However, before you can start specifying options, you must write an Event Object in its extended form. It must be a traditional JavaScript object with properties.
Also your json string has an extra comma at the end

$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
));
The program actually wants this very specific format of json_encode or it does not work. I only figured this out by reading through all of these replies.

Related

yii filter without press tab/enter

I need to change yii gridview filter to auto search(not autocomplete). for example I have an item name :StackOverflow. for this I need to type stack then press tab/enter to get the results. if I enter Sta the items will display which items start with letters sta(without press tab/enter keys).help me.Thank you
Hi please use below widget
<input type="hidden" name="formula_formula" id="formula_formula" value="">
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete',
array(
'name'=>'tff',
'source'=>'js: function(request, response) {
$.ajax({
url: "'.$this->createUrl('youraction').'",
dataType: "json",
data: {
term: request.term,
name: "treatment_formula_formula",
pk : "tff_id"
},
success: function (data) {
response(data);
}
})
}',
'htmlOptions'=> array('placeholder'=>'Formula List', 'class' => 'form-control auto_comp_search'),
'options' => array(
'autoFocus' => true,
'showAnim' => 'fold',
'minLength' => '0',
'select'=>'js:function( event, ui ) {
$(ui).hide();
$("#formula_formula").val(ui.item.id);
}'
),
));
?>

Select2 ajax option using YII Framework

I am using Yii framework on a project and i am using an extension which uses select2 jquery. I am unable to grasp how the implementation for ajax works with this extension or the select2.
My ajax call returns the following json.
[
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"}
]
The yii extension enfolds the select2 extension as below
$this->widget('ext.select2.ESelect2', array(
'name' => 'selectInput',
'ajax' => array(
'url'=>Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'type' => 'GET',
'results' => 'js:function(data,page) {
var more = (page * 10) < data.total; return {results: data, more:more };
}',
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
I found a related question from this Question! The link to the extension am using is YII select2 Extention!
So a week later i merged with the answer to this question.
First let me highlight how the select2 ajax or in my case the Yii ESelect Extension.
The ajax options for jquery are the same as for the Eselect Extention i.e. url,type and datatype altho there is a slight difference on the format returned after successfully querying.
As for the result set for Eselect/select2 expects two parameters to be returned. that is
id : data.myOptionsValue;
text : data.myOptionText;
Reference :: https://select2.github.io/options.html#ajax
if we want to customize the format for the result set that is retured we can go a head and extend the plugin by using
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
I also had an issue getting my head around how the extention was quering. A look around and i realised that we have two datatype jsonp and json these two datatypes will handle data differently.
Jsonp (json padding) allows sending query parameters when querying. As for my case i am not passing any other parameters e.g an authkey e.t.c. In my case i changed the datatype to json and returning a json with id and text as results. See below my working snippet.
echo CHtml::textField('myElementName', '', array('class' => 'form-control col-lg-12'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#myElementName',
'options' => array(
'placeholder' => 'Search ..',
'ajax' => array(
'url' => Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'delay' => 250,
'data' => 'js: function(term) {
return {
q: term,
};
}',
'results' => 'js: function(data){
return {results: data }
}',
),
),
));

Converting jQuery using CakePHP's Javascript Helper

I'm having issues converting the following jQuery/AJAX call to CakePHP's JS Helper.
Here is what currently works:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$("#DatabaseServerId").bind("change", function (event) {
var server_id = $("#DatabaseServerId").val();
$.ajax({
async:true,
dataType:"html",
evalScripts:true,
success:function (data, textStatus) {
$("#DatabaseEnvironmentId").html(data);
},
url:"\/apsportal\/servers\/get_environments/"+server_id
}
);
return false;
});
});
//]]>
</script>
Here is what I have thus far:
$data = $this->Js->get('#DatabaseServerId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#DatabaseServerId')->event('change',
$this->Js->request(
array('controller' => 'servers', 'action' => 'get_environments'),
array(
'update' => '#DatabaseEnvironmentId',
'async' => true,
'type' => 'html',
'dataExpression' => true,
'evalScripts' => true,
'data' => $data,
)
)
);
The issue is that the parameter passed has an array key specified and narrows the usage of this action.
http://my.domain.com/servers/get_environments?data%5BDatabase%5D%5Bserver_id%5D=36
Since server_id is being used in other models, I would rather have this as generic as possible.
Note: I figure if I standardize to the JS Helper, if something changes in the future, I'll only have to change things once.
Per the comments, I used raw jQuery instead of CakePHP's methods.

Remove escape character from Jquery Post

To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
and here is the code on the server:
$remision = json_decode($_POST['rem']);
Now, when I see whats inside of $_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
How can I remove the escape characters ?? thanks in advance for any comment or help :)
I actually just recently had the same issue.
I fixed it by using stripslashes();
This should work ok unless you actually do have slashes in the data.
var_export(json_decode(stripslashes('{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}'), true));
outputs:
array (
'id' => '12',
'fecha' => '2014-06-25',
'ciudad' => 'Manizales',
'camion' => 'NAQ376',
'driver' => '16075519',
'cant' => '0',
'anticipos' =>
array (
0 =>
array (
'type' => '1',
'com' => 'Comment',
'costo' => '1234',
),
),
)
You're calling $.post incorrectly. The second argument is all the POST parameters, it's not an options structure. If you want to pass options, you have to use $.ajax:
$.ajax("updateremission.php", {
data: { rem: jsonRemission },
dataType: "json",
success: function(data, status) {
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
}
});
You shouldn't use processData: false, because that will prevent the parameter from being put into $_POST['rem'].

flot piechart from PHP

I am having a very strange issue creating a piechart in Flot with data from PHP.
It seems to be drawing incorrectly, and I can't figure out why.
My PHP code (for testing) is:
echo json_encode(
'[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]'
);
My JS file is:
$.ajax({
type:'GET',
dataType:"json",
url:'../phpfile.php',
success: function(data) {
console.log(data);
$.plot($("#piechart"),data,{
series: {
pie: {
show: true
}
}
});
}
});
The consol log shows:
[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]
Which I thought was the correct format for flot...
But it graphs like this:
Does anyone have any ideas?
I believe your JSON currently is invalid, at the moment, you're trying to parse an JSON String, into a JSON String (If you get what I mean!) Currently, when I echo out from the PHP end with your echo'ed json_encode(), I'm provided with:
"[{ label: \"Series1\", data: 10},\r\n{ label: \"Series2\"]"
Furthermore, I would use PHP Arrays to encode JSON, like below:
<?php
$arr = array(
array(
"label" => "Series1",
"data" => 10
),
array(
"label" => "Series2",
"data" => 3
),
array(
"label" => "Series3",
"data" => 9
),
array(
"label" => "Series4",
"data" => 7
),
array(
"label" => "Series5",
"data" => 8
),
array(
"label" => "Series7",
"data" => 17
)
);
echo json_encode( $arr );
?>
PHP json_encode() does accept mixed variable types, but it's most popularly used with PHP arrays.
With the above, I'm able to construct the PIE chart successfully:

Categories