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.
Related
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 :-)
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!
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
I've been struggling with this problem for the last few hours, and every tutorial points toward the solution that I have implemented but it doesn't work.
Basically my PUT request returns an error:
PUT http://localhost:8083/stockapi/rest/stocks/5485cba248673a0dd82bb86f 400 (Bad Request)
When I intercept the request, I see that it contains a $promise and $resolved data element:
> {"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXX","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
This makes sense since I'm using the ngResource object -- but every tutorial shows that the following code should be able to handle it, but it doesn't.
Note/edit: if i PUT the JSON object without the "$promise" and "$resolved" elements through an external program (such as Postman REST client) then it works fine.
Factory:
.factory('Stock',function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
}); });
Controller (note: doing 4 updates but none of them work, 4 times the same Bad Request):
.controller('StockEditController',function($scope,$log,$http,$state,$stateParams,Stock){
$scope.stock = Stock.get({id:$stateParams.id});
$scope.updateStock=function(stock) {
Stock.update(stock);
stock.$update();
Stock.update($scope.stock);
$scope.stock.$update();
$state.go('stocks');
};
});
I'm really clueless right now how to use the ngResource object in the correct way so that I can use it to put/post to my webservice. Any ideas?
Thanks!
EDIT:
Chrome network output:
Response header
Remote Address:[::1]:8080
Request URL:http://localhost:8080/stockapi/rest/stocks/5485cba248673a0dd82bb86f
Request Method:PUT
Status Code:400 Bad Request
Request Headersview parsed
PUT /stockapi/rest/stocks/5485cba248673a0dd82bb86f HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 355
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8080/stockapi/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Request Payloadview parsed
{"id":"5485cba248673a0dd82bb86f","name":"iShares ESTOCK DivXXXYYY","ticker":"AMS:IDVY","url":"https://www.google.com/finance?q=AMS%3AIDVY&ei=F5BxVLiCB8GlwQPJ1YD4DQ","currency":"EUR","currentPrice":19.81,"currentPriceInEuro":19.81,"lastModified":1418054562234,"historyStockPrices":[{"timestamp":1418054562234,"price":19.81}],"$promise":{},"$resolved":true}
Response Headersview parsed
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 968
Date: Tue, 09 Dec 2014 06:36:24 GMT
Connection: close
According to the docs you are not quite using the update action correctly.
So really your updateStock method should be:
$scope.updateStock=function(stock) {
Stock.update({id: stock.id}, stock);
Stock.update({id: $scope.stock.id}, $scope.stock); //not sure why you have 2 calls here
$state.go('stocks');
};
Just looking at the factory definition and how it differs from mine, you should change that second parameter of factory definition into array to something like this:
.factory('Stock',[$resource, function($resource){
return $resource('http://localhost:8083/stockapi/rest/stocks/:id',
{ id: '#id' },{
update: { method: 'PUT' },
show: { method: 'GET' }
});
}]);
Not sure if this is the issue but that is at least significantly different to angular docs' definition on dependency injection here: https://docs.angularjs.org/guide/di
If not, could you also print out the contents of $scope.stock after the GET returns the data there?
I know this question is super old, but I stumbled upon the same issue and found this SO question as well as this question:
http://www.scriptscoop2.com/t/fddc3f0a1f6f/angularjs-using-ngresource-for-crud-adds-extra-key-value-when-using-save.html
There was 1 answer which explained that the issue is coming due to CORS (cross origins). Which means that your server side needs to allow it. If you are using Spring MVC it would be enough to add the org.springframework.web.bind.annotation.CrossOrigin annotation at the controllers request mapping:
#CrossOrigin
#RequestMapping(value = "/product/{id}", method = RequestMethod.POST)
#ResponseBody
public void editProduct(#PathVariable("id") final long id, #RequestBody final ProductDto productDto) {
// your code
}
As the title suggests, I have the following:
$.ajax({
"url" : ...
, "type" : "GET"
, "dataType" : "JSON"
, "success" : function(response_data) {
that.data = response_data;
success(response_data);
}
, "onerror" : function(data) {
console.log(JSON.stringify(data));
}
});
But when I run it, I get
XML Parsing Error: syntax error Location: moz-nullprincipal
Looking at firebug, I see that the request was
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-us,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Host localhost:8888
Referer http://localhost:8888/
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1
X-Requested-With XMLHttpRequest
Any ideas?
Change "JSON" to lowercase "json" first. But this is the type that jQuery is expecting back from the server, it's not necessarily what the server will send.
Are you sure that the server is returning JSON? Worth a double-check. Have you looked at the response in Fiddler? If it's XML it's the server's issue, not the script's.
Ok great thanks to everyone tried to answer this.
But it turns out, as usual, I noob'ed out here.
The XML parsing error shown in firebug is not actually an error with the code, and firebug's failed attempt to guess it's XML and parse it.
My problem was elsewhere in the program and it was solved.
Upper vs lower case "JSON" did not make a difference.
Max
The real problem is that your server is not setting the 'Content-type' header. Set it to 'application/json'.
For example in node.js:
res.setHeader('Content-type', 'application/json');