use getJSON with variable - javascript

I apologize beforehand if the question is not clear, but i'll try.
I currently have this code that pull the status of all the devices from my home automation controller.
function pull_light_status (lights_array) {
$.getJSON( "resources/php/getjson.php", function( json ) {
var vera_obj = json;
$.each(lights_array,function(myindex, myvalue){
var id_del_object = myvalue;
var id_status = vera_obj.devices[id_del_object].states[0].value;
})
})
}
Due to the structure of the object i get its getting really hard for me to work with that object so I'm thinking in using another route.
I can get the status of an specific device by using this php called change_state.php
<?php
$url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status";
$jsondata_send = file_get_contents($url);
//echo $jsondata_send;
?>
My question is:
Is it possible to replace the JS to something that will allow me to request the json response of a device variable I specify?
Something like this?
function pull_light_status (lights_array) {
$.each(lights_array,function(myindex, myvalue){
$.getJSON( "resources/php/change_state.php",{ device_id: + myvalue})
.done(function(json) {
var vera_obj = json;
console.log (vera_obj);
})
})
}
What I would expect in return is a 0 or 1, that way I can play with the status of the devices.

Try using $.post since you are expecting a POST payload on the php side.
function pull_light_status (lights_array) {
$.each(lights_array,function(myindex, myvalue){
$.post( "resources/php/change_state.php", { device_id: myvalue })
.done(function( data ) {
var vera_obj = json;
console.log (vera_obj);
});
})
}
While on the php side you need to make sure that you are sending back a json encoded string.
So a var_dump($jsondata_send); would be in order, if it's all right, print it out along with the headers.
<?php
$url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status";
$jsondata_send = file_get_contents($url);
header('Content-Type: application/json');
print $jsondata_send;
?>
If you want to use getJSON instead, in the php file, change $_POST['device_id'] into $_GET['device_id']

Related

Can't get a json response from Cakephp 3 controller

I am trying to send an ajax request to a Cakephp 3 controller.
The controller will find the data from the model and return it to the same view to be displayed,
The view and the js function are as follows
<script type = "text/javascript" language = "javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type : "POST",
url : "<?php echo $this->Url->build(['controller' => 'users', 'action' => 'getByCategories', '_ext' => 'json']); ?>",
success: function (data){
console.log(JSON.stringify(data));
}
});
});
});</script>
The above function is in the index view of the controller.
Upon the click of the button a request will be sent to the getByCategories function in the same controller.
The getByCategories function is as follows
public function getByCategories()
{
$id = 33;
$this->request->allowMethod(['ajax']);
$this->autoRender = false;
$cat = $this->Users->Categories->get($id);
if ($this->Users->Categories->childCount($cat) > 0)
{
$result = $this->Users->Categories->find('all', ['conditions' => ['parent_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
else
{
$result['Machines'] = $this->Users->Machines->find('all', ['conditions' => ['category_id' => $id]]);
$result['Medias'] = $this->Users->Medias->find('all', ['conditions' => ['category_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
}
The ajax response from this function is alway empty but the debugkit display the _serialize variable correctly.
I have enabled the json extensions in the routes.php file. the variable for the this call in the debugkit is as follows
debugkit varables
I would appreciated if someone can guide to get the variable from the debugkit in the ajax response
Thank you in advance
Looks like you're close, except for a misunderstanding of how _serialize (and maybe either set or compact) works. Check the manual for all the details, but what you should be setting in _serialize is either a list of names of variables, or else true to serialize everything.
Also, if you're using compact with set, you give it names of variables, not the variables themselves.
So, what you should be using there is probably:
$this->set(compact('result'));
$this->set('_serialize', ['result']);

Save form data using AJAX to PHP

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?
LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>

Ajax request in Codeigniter

I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript. I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.
So here are my questions:
Is it really possible to use PHP inside Javascript, or am I mistaken?
What's the right way to perform an Ajax request in Codeigniter? What I've tried is the following:
var param = {name : event_name, date : event_date, time : event_time};
$.ajax({
// As seen from the question here at stackoverflow.
url : "<?php echo base_url('event/new_event'); ?>",
type : 'POST',
data : param,
beforeSend : function(){ },
success : function(){
alert("Event created! Feel free to add as much details as you want.");
namebox.val("");
$("#new-event-modal").find(".close").trigger('click');
window.location.href = "<php echo base_url('user/dashboard'); ?>";
},
complete : function(){ },
error : function(){ }
});
I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!
the easiest way for you to accomplish this is by using some jquery:
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";
$.post(url, postdata, function(result){
...alert(result);
});
or call it straight from JS by caching it:
<script>
var test = "<?php echo base_url(); ?>"+"event/new_event";
alert(test);
</script>
Here is a dirty hack that I was going to use:
Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field.
Now when you want to make an ajax request, access that hidden field
and grab the base url and use it however you want.
The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.
This is your controller
<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {
public function ajax_echo()
{
// get the ajax input
$input = json_decode(file_get_contents('php://input'));
// $input can be accessed like an object
$password = $input->password;
$name = $input->name;
// you can encode data back to JSON
$output = json_encode($input);
// and the response goes back!
echo($output);
}
}
?>
This goes into your client
<script>
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
// create the request object
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "example_ctrl/ajax_echo", true);
// on success, alert the response
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200)
return;
alert("Success: " + xhr.responseText);
};
// encode in JSON and send the string
xhr.send(JSON.stringify(my_data));
</script>
There is no better way to do this .
Php codes can't be executed from external javascript files.
Try any of these :-
1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code
2) you can store the same base_url() in local storage , it will be available in your external JavaScript files
Hope it helps you :)

ajax request all return error 500

When ever I am doing an ajax request with jquery I always get an error 500 return,
I am posting to the following URL
http://localhost/domain/index.php/my_profile/interests_music
using this javascript,
$("#add").click(function(e){
//set some process variables, we need to get the forms action,
//and any post data it is sending appending isAjax into the params
//gives us a point in the controller to gracefully check for ajax.
var action = $(this).parent('form').attr('action');
var formData = $(this).parent('form').serialize()+"&isAjax=1";
$.ajax({
type: "POST",
url: action,
data: formData
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
e.preventDefault();
});
The params that are being sent are,
music=Savage Garden&isAjax=1
And the PHP method the ajax is requesting looks like this,
public function interests_music()
{
if($this->input->post('music'))
{
$this->rest->initialize(array('server' => 'https://www.googleapis.com/freebase/v1'));
$response = $this->rest->get('mqlread?query={"type":"/music/artist","name":"' . urlencode($this->input->post('music')) . '","id":[]}');
$data['image'] = 'https://usercontent.googleapis.com/freebase/v1/image'.$response->result->id[0].'?mode=fillcrop&maxwidth=80&maxheight=80';
$data['category'] = 'music';
$data['user_id'] = $this->session->userdata('id');
$data['name'] = $this->input->post('music', TRUE);
$this->profile_model->add_interest($data);
Events::trigger('interests_music');
Events::trigger('badge_stagediver');
if($this->input->post('isAjax') == 1)
{
echo json_endcode($data);
$this->_buttons();
}
redirect('my_profile/interests');
}
else
{
show_404();
}
}
Am I missing something, is this a common problem?
Well for one there's a typo in your PHP which could be what your server is choking on: echo json_endcode($data); should be echo json_encode($data);. Aside from that there could be other issues with your HTTP server. What server are you using? A good practice is to find the server error log and PHP error log and use tail -f or some other method of monitoring the logs which should give you more information when you have 505s.

JavaScript in CakePHP's controller

In my CakePHP view, I call method in controller, using jQuery:
function placeSensors(nk) {
$.ajax({
type:'post',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status = 'ok') {
}
}
});
}
JS in controller is defined with ie.:
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
var $components = array('RequestHandler'); // added later, but still the same
function index( $id = null, $value = null ) {
$code = '';
?>
<script type="text/javascript">
alert('Hello!');
</script>
<?php
return $code;
}
So, with simple code, I can not get alert message on my web form. Very simple code I was using in some other project and it works there, and for some reason this does not work on this one...
I'm really stuck with this one, can you please help me.....
UPDATE: this is response i'm getting by Firebug:
<script type="text/javascript">
alert('Hello!');
</script>
You're trying to place code that should be viewed (javascript) by the client, inside a controller. Controller is for business logic, that the client doesn't see.
Place your javascript inside a javascript file in the /webroot/js/ directory.
For interacting with ajax, tell your controllers to use the RequestHandler component to determine that they're being called by ajax. From there you can return simple values, or return a json or xml view.
If that sounds complicated, don't worry about it for now and just start as simple as you need and slowly build up your application.
function placeSensors(nk) {
$.ajax({
type:'post',
dataType:'json',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status) {
alert(r.code);
}
}
});
}
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
function index( $id = null, $value = null ) {
}
// update below code
function placeSensors( ) {
$nk = $_POST['nk'];
echo json_encode(array(
'status' => true,
'code' => "code"
));
exit();
}
Ok, i finally solved this one.
All I needed was to add one form and one text, or even better hidden element on form.
After that everything started to work.
So my mentioned code was ok, all I needed was that one text box......... Hope that somebody can tell me why?
Thank you on all your help and support.

Categories

Resources