I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST
Related
I have a react component - coursePage.js
function getCourseInitState(){
return {
courses: CourseStore.getAllCourses()//courseStore is required in script
};
}
var Courses = React.createClass({
getInitialState: function(){
return getCourseInitState();
},
render: function () {
return (
<div>
<h1> Course </h1>
<CourseList courses={this.state.courses} />
</div>
);
}
});
Action file -courseAction
var CourseAction = {
CourseList: function(){
var courseList = CourseApi.getAllCourses();
Dispatcher.dispatch({
actionType: ActionTypes.COURSE_INITIALIZE,
courseList: courseList
});
}
Store File - courseStore
var CourseStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback){
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback){
this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function(){
this.emit(CHANGE_EVENT);
},
getAllcourses: function(){ //here is the function define
return _courses;
},
getCourseById: function(id){
return _.find(_courses, {id: id});
}
});
Dispatcher.register(function(action){
switch(action.actionType){
case ActionTypes.COURSE_INITIALIZE:
_courses = action.CourseList;
CourseStore.emitChange();
break;
}
});
module.exports = CourseStore;
in console I am getting "Uncaught TypeError: CourseStore.getAllCourses is not a function"
I don't want to call api directly in my coursePage.js so I find this way of initialising the page but it is not working.
(Please note - I am new to this) As per my recent learning Action file must always call API and send the request to State. I can load with help of componentWillMount function. But, I wanted to solve with this.If not wrong, then it is more neat and preferable way of implementing?
You have a typo -> getAllcourses in the Store and in the Component you call getAllCourses
getAllCourses: function(){ //Should be getAllCourses instead of getAllcourses
return _courses;
},
Here is the Main code. Please check it. what is making this conflict.
<script type="text/javascript">
$(document).ready(function ()
{
setInterval(function()
{
$.get("ajax_files/manage_friend_requests.php", function (result)
{
$('#all_friends_requests').html(result); // This is the div i am reloading again and again after some seconds.
});
}, 9000);
});
</script>
You should be safer with something like this:
$(document).ready(function(){
setInterval(function(){
$.ajax({
type: "GET",
url: "ajax_files/manage_friend_requests.php"
}).done(function(result) {
var $friends_requests = $('#all_friends_requests');
if ($friends_requests.length > 0) {
console.log('Received: '+result);
$friends_requests.html(result);
console.log('UPDATED friends requests');
} else {
console.log('CANNOT access friends requests container');
}
});
}, 9000);
});
Depending on what the console will display, you will probably put the issue in evidence.
Im using jQuery to delete and fade the item container. This code will delete and fade div class box2. what i want to do this to fade div class box1. without changing the delete link to box1.
if anyone can point me out how to do this, highly appropriated. thanks in advace.
<div class="box1">
<div class="box2">
x
</div>
</div>
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#load').hide();
});
$(function () {
$(".delete").click(function () {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id=' + id;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function () {
commentContainer.slideUp('slow', function () {
$(this).remove();
});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
Try this code :
$(function() {
$('#load').hide();
$('.delete').click(function(){
$('#load').fadeIn();
$(this).parent().slideUp('slow', function () {
$('.delete').appendTo('.box1')
$(this).remove();
$('#load').fadeOut();
});
return false;
})
})
If you change it to var commentContainer = $(this).parent().parent();. It will now target .box1. You can then unwrap .box2 :
commentContainer.slideUp('slow', function() {
$('.box2').unwrap();
$(this).remove();
});
I believe you want
var commentContainer = $(this).parent().parent();
to get to .box1 and not .box2 Does that solve the problem?
Just a couple of comments though. A valid id should start with an alphabetic character. The digit '1' is not valid. 'a1' would be better, or just 'a'. Also use the ajax callback done rather than success as it is currently deprecated.
I'm new to socket.io and i already have a problem, minor i think.
I have installed node.js properly and socket.io too with npm. Then just for testing i cut and paste a sample of code from socket.io and everything works well.
Now, i want to strcuture my code and folders and i have created a folder "client" to put a fresh new js file client.js with the client code from the example.
Here is my architecture
/client
client.js
index.html
server.js
client.js :
var socket = io.connect('http://localhost:80');
socket.on('news', function (data) {
alert('sqd');
console.log(data);
socket.emit('my other event', { my: 'data' });
});
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html', 'utf-8',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html ' + __dirname);
}
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script type="text/javascript" src="/client/client.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
</body>
</html>
When i refresh my browser at localhost:80 i have a error on my client.js :
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html
It seems that there's a problem to interpret my js file as a js file. I've read some threads on the question but nothing works.
Can you help me please ?
Thanx :)
Ok i've found a solution... You have to specify the content type for each file request in a static webserver. May be it could help someone.
Here is the handler function :
function handler (req, res) {
var filePath = req.url;
if (filePath == '/') {
filePath = './client/index.html';
} else {
filePath = './client/lib' + req.url;
}
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}
else {
res.writeHead(404);
res.end();
}
});
}
Hope this can help someone.
I love to post a problem and respond by myself with no help. Somehow it meens that i'm desesperate too fast. And i love to tell my life in a post too :)
Ok i'm gonna eat something and drink more coffee !!!
Thank you so much! This solved my problem!! And I changed the switch to following code:
var extname = path.extname(filePath);
var contentTypesByExtention = {
'html': 'text/html',
'js': 'text/javascript',
'css': 'text/css'
};
var contentType = contentTypesByExtention[extname] || 'text/plain';
It may be easier to maintain :)
Only that solves:
function handler (request, response) {
var file = __dirname + (request.url == '/' ? '/index.html' : request.url);
fs.readFile(file, function(error, data) {
if (error) {
response.writeHead(500);
return response.end('Error loading index.html');
}
response.writeHead(200);
response.end(data, 'utf-8');
});
}
that's what i need! thank you!
and
we'll add one code line a top of
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
**, path = require('path')**
You can use mime module as well:
var mime = require('mime')
, content_type = mime.lookup(filePath);
// handle the request here ...
response.setHeader('Content-Type', content_type);
response.writeHead(200);
response.end(data);
And you must made fs.readFile wrapped by a closure, otherwise some file (especially the last file) will be read more than once, and others will not be read at all. And the contentTypewill not be set as you wish. This is because of the callback strategy used by fs.readFile. The problem does not appear when the html file just load one external file, but as the external files(css, js, png) loaded more than one it will appear as i pointed out above. (I came upoon this by myself)
So your code should make a little change as follows:
;(function (filename, contentType) {
fs.readFile(filename, function(err, file) {
// do the left stuff here
});
}(filename, contentType));
Hello friends i want to show Ajax loader before Data load in particular div but problem is the data is coming dynamically on same page but my script calling data from another file Script.php please see my code below
Script
<script>
function loadingAjax(div_id)
{
$("#"+div_id).html('<img src="ajax-loader.gif"> saving...');
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
HTML
<body onload="loadingAjax('myDiv');">
<div id="myDiv"></div>
<div id="xyz"><img src="ss/image/abc.jpg" /></div>
</body>
Its working fine but i want to load data in same page please help me
Thanks in advance ....
EDIT
I want to show loader before load data #xyz into #myDiv
you can try with following html -
<body onload="loadingAjax('myDiv');">
<div id="myDiv">
<img id="loading-image" src="ajax-loader.gif" style="display:none;"/>
</div>
</body>
and the script -
<script>
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
beforeSend: function() {
$("#loading-image").show();
},
success: function(msg) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
}
});
}
</script>
you can try with following script
<script>
function ajax()
{
var options = {};
options.url = '';
options.type = 'post';
options.data = '';
options.dataType = 'JSON'; // type data get from sever
options.contentType = 'application/json';// type data post to sever
options.async = false;
options.beforeSend = function () {
};
options.success = function (data)
{
};
options.error = function (xhr, status, err) {
console.log(xhr.responseText);
};
$.ajax(options);
}
</script>