I try to send a handsontable table data using $http POST with Angulars.js
The code below:
var $container = $("div#table");
var handsontable = $container.data('handsontable');
$scope.saveData = function() {
$http.post('save.php', {'data':handsontable.getData()}).success(function(res,status) {
if (res.result === 'ok') {
console.log('Data saved');
}
else {
console.log('Save error');
}
});
}
But I get a 'Save error' with
Undefined index: data in <b>C:\xampp\htdocs\angular\save.php
I the development tool in Chrome I get Request payload of this form:
{"data":[[fdf,gsgg,gsg,null,null,null],[sgsg,sgg,sgg,ggs,null,null]]}
I changed parameters in $http.post to get it work but no solution,
Thank you to give some advices!!!
I finally found a solution in here : [How to retrieve Request Payload
Instead of retrieving the data in this way
$values=$_POST['data'];
I fetch in this way:
$request_body = file_get_contents('php://input');
Related
I'm not sure I'm even attempting the right thing. Heres my issue.
I'm loading data to a screen if the user is authenticated. Its a summary screen. I can click a item and it will send me to a new "details" page (window.location) . I'm passing the ID in the URL and then doing a GET request to get the details to display. When I implement my rules on the firebase DB, (".read": "auth != null"), I get a "401 Unauthorized" error in the console.
So somehow I need to either pass the user to the details.js or set Persistence somehow. Anyone have any suggestions?
THIS IS THE CODE FROM THE MAIN.JS
auth.onAuthStateChanged(user => {
console.log(user);
if (user) {
database.on('value', function(data) {
myData = data.val()
keys = Object.keys(myData)
buildProperties();
})
// tempBuild()
} else {
$('.eachProperty').empty()
$('.eachProperty').append($(`<h1>You must be signed in to view properties</h1>`))
}
})
$('body').on('click', '.singleProp', function() {
id = $(this).attr('id')
window.location = "/details.html?id=" + id
})
THIS IS THE CODE FROM THE DETAILS.JS
var myLocation = location.search.slice(4)
$.get(`https://XXXXXX.firebaseio.com/property/${myLocation}/.json`).then(myProperty)
function myProperty(prop) {
$('.propAddress').text(prop.address)
$('.zip').text(prop.zip)
if(prop.pictures){
for (var i = 0; i < prop.pictures.length; i++) {
var myImg = prop.pictures[i]
$('.imgContainer').append($(`<div class="eachPicDiv"><img src="${myImg}" alt="0" class="detailPic">
<ion-icon class="rBtn" name="arrow-redo-outline"></ion-icon>
</div`))
}
} else {
$('.imgContainer').append($(`<h1>THERE WERE NO PICTURES</h1>`))
}
}
You are using jQuery to fetch your data from Firebase Database,
$.get is a jQuery method, and for that to succeed you need to have some sort of auth token.
Firebase already provides best in class access, read more about access here.
Learn by example here.
I am trying to send a javascript variable (placeid) to PHP using AJAX. I use this variable to retrieve a JSON Object. The JSON returned to Javascript is NULL. How do I fix this?
function sendToPhp(placeid){
var url = "finals.php?placeid="+placeid;
var getJSONObj=function(url,callback){
var httpc = new XMLHttpRequest();
httpc.open("GET", url, true);
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.responseType='json';
httpc.onload= function(){
var status=httpc.status;
if(status==200){
//alert(httpc.response);
callback(null,httpc.response);
}
else{
callback(status,httpc.response);
}
};
httpc.send();
};
getJSONObj(url,function(err,jsonObjectReturned){
if(err!==null){
alert("something went wrong"+ err);
}
else
{
alert("success");
alert(jsonObjectReturned); // **returns NULL**
}
});
} // end of function
The PHP script uses the placeid to return a JSON file as shown:
if(isset($_GET['placeid']))
{
$placeid= $_GET['placeid'];
$apikey="someKeyValue";
$url="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=".$apikey;
$jsonPlacesObject=json_decode(htmlspecialchars(#file_get_contents($url),true),true);
echo json_encode($jsonPlacesObject); //sending json to javascript**
die();
}
Your AJAX form looks wrong. Try reading https://www.w3schools.com/js/js_json_php.asp .
Original.
I get this error
TypeError: self.rooms[setup.to].publish is not a function
when sending the message. I already have the keys in pubnub, what should I do to make it work? My Angular version is 1.6.6.
// Send Messages
$scope.send = function() {
Messages.send({
data: $scope.textbox
});
};
I dunno if you use a form but try this way :
<form name="form" novalidate="true" ng-submit="send()">
$scope.send = function () {
if ($scope.form.$valid) {
var data = $scope.textbox;
$scope.textbox = null;
$scope.messages.push(data);//of push or send depend did proto
}
}
It's about time I call in the big guns for this as I can't seem to figure it out.
I have a simple CRUD API in Node. I'm using EJS on the front-end. Essentially, I've got a selectAllRecords view where I display a table of all the records. I have a button next to each record to edit the record. When the button is clicked, it redirects to an editrecord.ejs page, hits the API for a single record where each line is displayed as a value in an input box. From there, I have an onclick method with an XMLHttpRequest making a put request to update the database. However, I'm getting an error - 500 (Internal Server Error) - I'm sure it's something fairly simple I'm missing, but I can't seem to figure it out.
Any help is greatly appreciated! Code below:
First on my view:
<script type="text/javascript">
function someFunc() {
var id = <%= id %>;
var url = '/api/edit/' + candID;
console.log('url ' + url);
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var data = {
name: name,
email: email,
}
var json = JSON.stringify(data);
console.log('json ' + json);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url, true);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
};
and in my queries.js file:
function updateCandidate(req, res, next) {
var candID = parseInt(req.params.id);
console.log('hit update');
console.log('name ' + req.body.name);
db.none('update cands set name=$1, email=$2 where id=$3',
[req.body.name, req.body.email, candID])
.then(function () {
var candID = candID
var name = data.name;
var email = data.email;
res.render("edited", {"candID":candID, "name":name, "email":email});
})
.catch(function (err) {
return next(err);
});
}
A potentially important note, when I hit the update button and execute the someFunc() function, the dev tool logs show a PUT request to 'api/edit/50' (or whatever ID) and '500 (Internal Server Error)' -- If i hard reload the 'getAllRecords' view, the updates are reflected so it's an issue with the render or redirect (I've tried both)
EDIT
As suggested, I removed the render from the updateCandidate method, but I still get a 500 Internal Server Error. the devtools show me the PUT request is hitting the right URL so i'm really not sure why this isn't functioning correctly. Updated code below...
function updateCandidate(req, res, next) {
var candID = parseInt(req.params.id);
db.none('update cands set name=$1, email=$2, client=$3, jobtitle=$4, question1=$5, question2=$6, question3=$7 where id=$8',
[req.body.name, req.body.email, req.body.client,
req.body.jobtitle, req.body.question1, req.body.question2, req.body.question3, candID])
.then(function (data, err) {
res.status(200)
.json({
status: 'success',
message: `Edited Candidate`
});
})
.catch(function (err) {
return next(err);
});
}
You are sending an ajax request to update the record. So, you should not try to render a view or redirect user as the response of this request. Instead, you can send back a JSON object with some properties e.g. "status".
Then on client side, you check the returned JSON response and based on "status" parameter ( or any other you chose ), you can either update your data or reload the page using window.reload on client side.
Your db query says
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email]) ...
Shouldn't it be
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email, candID])
Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv