Angularjs save form input to php and Mysql - javascript

I have a promblem trying to learn and build an angularjs application. I just can't get the form data saved to mysql...
I have spent hours trying everything and it just won't work.
The PHP-file inputs empty queries to the mysql table when using the variable. If I use static info it works fine.
Thanks :)
app.controller('addMsgCtrl', function ($scope, $http) {
$scope.fill = function(add) {
var data = {
addItem: $scope.addItem
};
$http.post("msinput.php",{'data' : $scope.addItem})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
};
});
$data = json_decode(file_get_contents("php://input"));
$addItem = mysql_real_escape_string($data->addItem);
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("stran189_taskma") or die(mysql_error());
mysql_query("INSERT INTO message (addItem) VALUES ('$addItem')");
Print "Your information has been successfully added to the database.";
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form class="add-task" id="newTaskForm" ng-controller="addMsgCtrl" novalidate ng-submit="fill()">
<div class="form-actions">
<div class="input-group">
<input ng-model="addItem" class="form-control" type="text" name="addItem" placeholder="Ny anteckning" />
<div class="input-group-btn"><button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-plus"></i></button>
</div>
</div>
</div>
</form>
RESPONSES
JS: "Inserted successfully!"
NET: "POST 200 OK msinput.php"
Request headers: "Host: (myUrl)
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0
Accept: application/json, text/plain, /
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: (myUrl)
Content-Type: application/json;charset=utf-8
Content-Length: 2
Connection: keep-alive"
respond-headers:
Connection: Keep-Alive
Content-Length: 62
Content-Type: text/html
Date: Mon, 07 Dec 2015 21:36:53 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.10 (Unix) OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
Vary: User-Agent
X-Powered-By: PHP/5.4.37

I am a bit confused by your controller code, but it seems to me, that you prepare the var data to be send to the server. If this is true you have to $http.post("msinput.php", {'data': $scope.data}) ...

Inside your fill() log data. See if anythign is in there. The change this
$http.post("msinput.php",{'data' : $scope.addItem})
to this
$http.post("msinput.php",{'data' : data})
Then check your Network XHR and see if data is being sent correctly to the server.
Also to get more info on what the server is saying back you can also use this method and log the error:
// Simple GET request example:
$http({
method: 'POST',
url: 'msinput.php'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

First make sure your data is present:
Open Firebug in Firefox, choose the console tab
Navigate to your form in Firefox, fill in the the form and submit it.
The last line in the console should show:
POST http://..../msinput.php
click this and look at the POST & JSON tabs, it will show all your input data for each field. Anything missing obviously wont get to your db.
Once you know your data is leaving, then you can figure out why its not arriving.
I also strongly suggest you change to PDO and stop using mysql functions has it is now deprecated.
Ok, so now you know the data in your form is leaving thru your post action.
Inside your msinput.php do the following
var_dump( file_get_contents(http://input) );
See what comes back in the firebug console.

Related

xmlhttprequest not posting to php file

I hope this is not a duplicate...
I am trying to POST user email & password to a php file and it seems that the php file isn't getting those values.
The js code:
function ReceiveLoginData() {
let text = this.responseText;
console.log(text);
let json_data = JSON.parse(
text.substring(1, text.length - 1).replaceAll("\\u0022", "\"")
);
// there is a lot more code... but its irrelevant.
}
function SubmitLogin() {
var email_addr = document.getElementsByClassName("login-email")[0].value;
var passwd = document.getElementsByClassName("login-passwd")[0].value;
var req = new XMLHttpRequest();
req.onload = ReceiveLoginData;
// req.onreadystatechange = ReceiveLoginData; // does not work...
req.open("POST", "/users/auth/login.php"); // ...,true); or ...,false); fail too...
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
let data_to_send = "uemail=" +
window.encodeURIComponent(email_addr) +
"&upasswd=" +
window.encodeURIComponent(passwd);
// data_to_send = "uemail="+email_addr ... works neither
req.send(data_to_send);
}
PHP (actually its location is localhost:4000/users/auth/login.php)
<?php
$uemail = $_POST["uemail"];
$upasswd = $_POST["upasswd"];
$login_err = true;
// set it to false otherwise
function SendData(string $str)
{
echo json_encode($str, JSON_HEX_QUOT | JSON_HEX_APOS);
}
function main_fn()
{
$uemail = strtolower($uemail);
if (strlen($uemail) == 0) {
SendData("[\"noemail\"]");
}
// and much more but again irrelevant...
}
main_fn();
?>
I learnt that using window.encodeURIComponent(...) is safer from here: https://stackoverflow.com/a/17382629/18243229
but neither of the ways work.
Whatever I got to know after literal 5 hours of debugging and getting fed up(I blame my noviceness):
The PHP form is being executed. ReceiveLoginData function prints ["noemail"] whenever the submit button is pressed
The Network debugging tab in chrome's dev tools shows that connection is established with php file.
Some information which might just be useful:
Response Headers (source):
HTTP/1.1 200 OK
Host: localhost:4000
Date: Sun, 18 Sep 2022 16:59:49 GMT
Connection: close
X-Powered-By: PHP/8.1.10
Content-type: text/html; charset=UTF-8
Request Headers (source):
POST /users/auth/login.php HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 31
Content-type: application/x-www-form-urlencoded
Host: localhost:4000
Origin: http://localhost:4000
Referer: http://localhost:4000/users/auth/auth.html?
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
sec-ch-ua: "Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
Payload: (source | URL encoded)
uemail=email%40gmail.com&upasswd=1234
uemail: email%40gmail.com
upasswd: 1234
Response:
"[\u0022noemail\u0022]"
What else I did...
I didn't waste those 5 hours on this project...
I tried to remake a smaller project with the same mechanism and the same js code calling a PHP file and voila, the php file got the values posted to it...
Everything "seems" correct according to my knowledge but why does PHP not get the $_POST values?
Also, I'm currently focusing on Google Chrome and am on Linux (ig that makes no difference...)
From the code you have posted i can spot one problem.
the $uemail = $_POST["uemail"]; is in the global scope and the code inside the main_fn function is trying to use that variable but that variable is not available in that scope because it is only available in the global scope. So it seems to me you need to pass them as arguments to get them into the functions scope.
Changeing the function definition
from: function main_fn()
to: function main_fn($uemail, $upasswd)
and calling it
with: main_fn($uemail, $upasswd);
instead of: main_fn();
should do the trick
Hope this helps :-)

AJAX request returning "405 Method Not Allowed"

I'm trying to write a submit form that sends a JSON object to an application on another server but I keep getting a 405 Method Not Allowed error in the console.
The app is set up to accept POST and that's what I'm sending so I'm lost at where the error is. There is also a warning in the console Loading failed for the <script> with source "Request URL"
Is this a problem with the way the application is reading the JSON or the format the JSON is being sent in?
From the app server
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
Code
json = JSON.parse(string);
$.ajax({
type: 'POST',
dataType: "jsonp",
contentType: "application/json",
url: "http://test:8080/request/committee",
data: json,
cache: false,
success: function (response) {
$("#successModal").modal('show');
},
failure: function (response) {
$("#failureModal").modal('show');
},
error: function (response) {
$("#failureModal").modal('show');
}
});
e.preventDefault();//prevents the form from being submitted by default
Request Headers
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: test:8080
Referer: http://www.form.com/servlet/rsvp.jsp?location=110%20Road%20Bolton%20Landing,%20NY&purpose=%20TPAS%20Teleconference%20(RSVP%20here%20to%20attend%20in-person)&visitDate=2018-03-15&visitStartTime=6:00%20AM&visitEndDate=7:00%20AM&committee=all
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0
Response Headers
HTTP/1.1 405 Method Not Allowed
Allow: POST, OPTIONS
Connection: keep-alive
Content-Length: 0
Date: Mon, 16 Apr 2018 15:38:24 GMT
Edit: corrected contentType. Same error occurs
From your exception details , it seems to be
Failed to execute: javax.ws.rs.NotSupportedException: RESTEASY003065: Cannot consume content type
either you are passing invalid content type or not passing at all , I see your content type is application/jsonp.
just give a try with application/javascript.
This error happened to me once. My java method wanted xml not json. this annotation (in java) fixed it for me.
#Consumes(MediaType.APPLICATION_JSON)
I hope this helps!

Echo posted Ajax data

I am using AJAX to post some array data to the server. I get the following expected results in the Firebug network console from the Ajax request.
POST -----> http://example.com/drag_data.php
//request header
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://example.com/drag.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 90
Cookie: PHPSESSID=b1lr9he4l2hbcnlkcsebfq2134
Connection: keep-alive
//data in the request body
item[]=1&item[]=3&item[]=2&item[]=4&item[]=5
//firebug params
item[]:"1"
item[]:"3"
item[]:"2"
item[]:"4"
item[]:"5"
for infor this is the ajax call which give the expected success message (same as the firebug param output)
$.post({
data: data,
type: 'POST',
url: 'drag_data.php?',
success:function(result){
$(".result").html(data);},
error: function(){
console.log(arguments);
}
});
I just want to echo the posted data in the drag_data.php script. I have tried the following test code (as well as (print_r and var_dump) but cannot see any posted data which has baffled me. Can anyone tell me what I am doing wrong please?
drag_data.php test file
$i = 0;
//this loop is failing to echo the posted array data from the Ajax request
foreach ($_POST['item'] as $value) {
echo "each".$value;
$i++;
}
?>
Make url: '/drag_data.php', with preceding slash and without ?.
Maybe serializing will help: make data: JSON.stringify(data) on client and json_decode on server.
Check configurations of your server - are requests you're seeing in your firebug actually reaching the server?
Finally cracked it. Turns out that there was a server side issue with Ajax calls that has now been resolved by the service provider. So in actual fact my original code works as it should. Maybe this thread or the code will be useful for someone else in the future.

Angularjs - Can't read local json file [duplicate]

Trying to make a call and retrieve a very simple, one line, JSON file.
$(document).ready(function() {
jQuery.ajax({
type: 'GET',
url: 'http://wncrunners.com/admin/colors.json' ,
dataType: 'jsonp',
success: function(data) {
alert('success');
}
});
});//end document.ready
Here's the RAW Request:
GET http://wncrunners.com/admin/colors.json?callback=jQuery16406345664265099913_1319854793396&_=1319854793399 HTTP/1.1
Host: wncrunners.com
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2
Accept: */*
Referer: http://localhost:8888/jquery/Test.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Here's the RAW Response:
HTTP/1.1 200 OK
Date: Sat, 29 Oct 2011 02:21:24 GMT
Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d SE/0.5.3
Last-Modified: Fri, 28 Oct 2011 17:48:47 GMT
ETag: "166a2402-10-4eaaeaff"
Accept-Ranges: bytes
Content-Length: 16
Content-Type: text/plain
Connection: close
{"red" : "#f00"}
The JSON is coming back in the response (red : #f00), but Chrome reports Uncaught SyntaxError: Unexpected token : colors.json:1
If I navigate directly to url itself, the JSON is returned and is displayed in the browser.
If I paste the contents of colors.json into JSLINT, the json validates.
Any ideas why I can't get this error and I never make it to the success callback?
EDIT - the jQuery.ajax() call above runs perfect at jsfiddle.net, and returns the alert 'success' as expected.
EDIT 2 - this URL works fine 'http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json' I noticed that it returned as TYPE: text/javascript and Chrome did not throw the Unexpected Token. I've tested several other url's and the ONLY one that does not throw the Unexptected Token is the wunderground that is returned as TYPE: text/javascript.
Streams returned as text/plain and application/json are not being parsed correctly.
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows:
1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ].
2- add a script link to it just below the normal jQuery link.
3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({
crossOrigin: true,
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",
type : "GET",
success:function(data){
console.log(data);
}
})
I had the same problem and the solution was to encapsulate the json inside this function
jsonp(
.... your json ...
)
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

Unable to fetch cookies, set by Play framework server, in Angular $http call?

I have been trying to get hold of the cookies I am setting in the server using PlayFramework:
response().setHeader(SET_COOKIE, AppConstants.COOKIE_USER_SESSIONID+"="+appSession.getSid());
in the angular app, but am not able to.
If I use the Advanced Rest client, I get the SetCookie header and the cookies get set in the call that follows. However when I call the same api through my angular app, I am not able to get the header in the response and hence no cookies for the app.
Here's what I have already tried:
renaming the environment from localhost to xyz.com since I read on multiple answers that cookies do not work at localhost.
Tried the api form a separate rest client, was able to fetch the header successfully, so the API looks fine to me.
There should be some catch in angular code which I am not able to figure out. Any help on this is highly appreciated. Thanks.
Angular code snippets:
LoginController:
angular.module('wratApp')
.controller('LoginCtrl', function (postService, wratSettings, wratRoutes, $location, $cookies) {
$("#header").hide();
this.user= {};
this.logUserin = function(){
console.log("User: " + this.user.email + " & pwd: " + this.user.pwd);
var payLoad = {};
payLoad.ldap = this.user.email;
payLoad.pwd = this.user.pwd;
postService.postPromise(wratRoutes(wratSettings).POST_USER_LOGIN(),payLoad)
.then(function(){ //login success
console.log("login success");
$location.path(wratRoutes().CLIENT_HOME());
}, function(){ //error in login
console.log("Login failed");
})
;
}
});
postService:
angular.module('wratApp')
.factory('postService', function ($http, $q, $cookies, $location) {
function postService() {
var self = this;
self.postPromise = function (uri,payload){
var deferred = $q.defer();
$http.post(uri,payload)
.success(function(data, status, headers, config){
console.log("Got response cookies: "+$cookies.getAll());
deferred.resolve(data);
})
.error(function(data, status, headers, config){
if(status == 401){
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
});
$location.path('/login');
}else{
deferred.reject(data);
}
});
return deferred.promise;
}
}
return new postService();
});
Now, my login succeeds but without any cookies being set by the server. Also, the PlaySession cookie which is somehow visible in the debugger(the manually set ones are even absent from debugger), is not in the angular $cookies variable(refer image below).
Please suggest how can I resolve this. Thanks.
Update 1:
If I run the Play server not in debug mode, the cookies are appropriately being sent by the server. It's an issue with the angular app where in the following call, it's not transferring the values form the Set-Cookie header to the cookies for the next call. It might be some silly mistake on my end too. Please see if you can help me figure out.
Server response /login:
HTTP/1.1 200 OK
Vary: Origin
Set-Cookie: sid=1e6823e24554598b0521ca5f64d7746b; Path=/
Set-Cookie: PLAY_SESSION=953d9d5730bf1b77cccaadef6b78c209e59d924b-sid=1e6823e24554598b0521ca5f64d7746b; Path=/; HTTPOnly
Content-Type: application/json; charset=utf-8
Access-Control-Allow-Origin: http://wrat.com:9009
Access-Control-Allow-Methods: OPTIONS, GET, POST
Access-Control-Allow-Credentials: true
Date: Thu, 24 Sep 2015 22:27:03 GMT
Content-Length: 429
The following request which should have cookies set, but no cookies there :-( :
GET /products/all HTTP/1.1
Host: wrat.com:9000
Accept: application/json, text/plain, */*
Origin: http://wrat.com:9009
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Referer: http://wrat.com:9009/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Taking off the Play framework tag since it's not a play issue anymore.
Adding the withCredentials option to the $http calls worked for me and resolved the issue.
$http.post(uri,payload, {withCredentials: true})
The issue is with the ajax calls where if this withCredentials flag is not truthy at both server and client, the cookies set by server are not maintained for cross-origin calls. Hence it was totally ignoring the cookies I was setting from the server.
Text from following question helped resolve the problem:
Why is jquery's .ajax() method not sending my session cookie?
from:
I am operating in cross-domain scenario. During login remote server is
returning Set-Cookie header along with
Allow-Access-Control-Credentials set to true.
The next ajax call to remote server should use this cookie.
CORS's Access-Control-Allow-Credentials is there to allow cross-domain
logging. Check https://developer.mozilla.org/En/HTTP_access_control
for examples.
For me it seems like a bug in JQuery (or at least feature-to-be in
next version).
UPDATE:
Cookies are not set automatically from AJAX response (citation:
http://aleembawany.com/2006/11/14/anatomy-of-a-well-designed-ajax-login-experience/)
Why?
You cannot get value of the cookie from response to set it manually
(http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-getresponseheader)
I'm confused..
There should exist a way to ask jquery.ajax() to set
XMLHttpRequest.withCredentials = "true" parameter.
ANSWER: You should use xhrFields param of
http://api.jquery.com/jQuery.ajax/
The example in the documentation is:
$.ajax({ url: a_cross_domain_url, xhrFields: {
withCredentials: true } }); It's important as well that server answers correctly to this request. Copying here great comments
from #Frédéric and #Pebbl:
Important note: when responding to a credentialed request, server must
specify a domain, and cannot use wild carding. The above example would
fail if the header was wildcarded as: Access-Control-Allow-Origin: *
So when the request is:
Origin: http://foo.example Cookie: pageAccess=2 Server should respond
with:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Credentials: true
[payload] Otherwise payload won't be returned to script. See:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials

Categories