jQuery post returns empty response - javascript

I'm having a big problem over the last week and I can't seem to figure out a solution.
I'm trying to post some raw XML to a server that another company has developed for us that has, I think a listener to receive this XML input. I'm posting and sending the information just fine the thing is that I don't get any response back (just like every girl I liked in highschool...).
The error i get from Chrome is: >POST http://xx.xxx.xxx.xxx:xxxx/SLISMESSAGE net::ERR_EMPTY_RESPONSE
and I've tried other browsers also but all of them the same deal except for Firefox that gives me a CORS error.
When I post the listener on the the server just says: Get Request /SLISMESSAGE.
var template = [
'<?xml version="1.0"?><request type="create-order"><PATIENT><CODE><?CODE?></CODE><DEPARTURE_DATE><?DEPARTURE_DATE?></DEPARTURE_DATE><LASTNAME><?LASTNAME?></LASTNAME><FIRSTNAME><?FIRSTNAME?></FIRSTNAME><BIRTHDAY><?BIRTHDAY?></BIRTHDAY><SEX><?SEX?></SEX><PHONE1><?PHONE1?></PHONE1><EMAIL><?EMAIL?></EMAIL><HOTEL><?HOTEL?></HOTEL><HOTELNO><?HOTELNO?></HOTELNO></PATIENT><ORDER><ORDERNO><?ORDERNO?></ORDERNO><ORDERDATE><?ORDERDATE?></ORDERDATE><ORDERTIME><?ORDERTIME?></ORDERTIME><SENDERCODE><?SENDERCODE?></SENDERCODE></ORDER><TESTS><TEST><?TEST?></TEST></TESTS></request>'
].join('\r\n');
function update() {
var len = 10;
var randomId = parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
//console.log(randomId.toString());
var variables = {
'CODE': $('input[name="wpforms[fields][25]"]').val(),//randomId.toString(),
'DEPARTURE_DATE':$('input[name="wpforms[fields][3][date]"]').val(),
'DEPARTURE_TIME':$('input[name="wpforms[fields][3][time]"]').val(),
'LASTNAME': $('input[name="wpforms[fields][6][last]"]').val(),
'FIRSTNAME': $('input[name="wpforms[fields][6][first]"]').val(),
'BIRTHDAY': $('input[name="BIRTHDAY"]').val(),
'SEX': $('input[name="wpforms[fields][9]"]').val(),
'PHONE1': $('input[name="wpforms[fields][14]"]').val(),
'EMAIL': $('input[name="wpforms[fields][15]"]').val(),
'HOTEL': $('input[name="wpforms[fields][16]"]').val(),
'HOTELNO': $('input[name="wpforms[fields][17]"]').val(),
'TEST':$('input[name="wpforms[fields][2]"]').val(),
'ORDERNO':$('input[name="wpforms[fields][25]"]').val()
};
var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
console.log(newXml);
var parsedNewXml = $.parseXML(newXml);
//console.log(parsedNewXml);
var order_num = document.getElementById("wpforms-1034-field_25")
$.ajax({
url: "http://xx.xxx.xxx.xxx:8008/SLISMESSAGE",
method: 'POST',
crossDomain: true,
cache: false,
async: true,
timeout:0,
data: newXml,
contentType: "application/xml",
dataType: "xml",
success : function(){
console.log('XML Sent');
alert("Data sent");
},
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
console.log('HEYYYYYYYYYYYY');
alert(order_num);
}
});
The thing is when I try to post the same XML from postman I get a response. And the weirdest of them all, when I try to post with a python script I also get a response! ????????
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...
Python Code
Response Time
Results of Python Code and JS jQuery
Python is in blue JS in red
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...

It could be a CORS issue. You can see in the console tab in developer tools if you are getting cors error. Because browser blocks the response if cors is not properly configured. When you hit the api from Python the cors issue wont be happening because the cors check happens in the browser and not in Python

Related

Request issue: Uncaught SyntaxError: Unexpected token /

I am developing i small app that displays some JSON data
inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:
Uncaught SyntaxError: Unexpected token :
my code:
$.ajax({
url: 'http://localhost/documents.json',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
// do something with the data
},
type: 'GET'
});
});
My JSON file is valid. I checked it with a JSON validator.
Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.
Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:
Omit protocol and host:
url: 'http://localhost/documents.json',
should be:
url: '/documents.json',
(Probably not required, but will help to void errors.)
Ask for the correct data type:
dataType: 'jsonp',
should be:
dataType: 'json',
Do not parse again what jQuery already parsed for you:
var json = $.parseJSON(data);
should be:
var json = data; // Yeah, nothing :)
This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!
Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.
Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.

How to get PHP page returned by a jQuery Ajax request

So I have to send some data to a php page, and it will return me another php page based on my data.
I send the data this way:
$(document).ready(function() {
$.ajax({
url: '//www.example.com/page.php',
type: "post",
dataType: 'jsonp',
data: { myvar:myvalue },
success: function(response) { console.log("success."); },
error: function(XMLHttpRequest, textStatus, errorThrown) { console.log("error."); },
complete: function() { console.log("complete."); }
});
});
It shows an alert saying jQuery180014405992737595236_1357861668479 was not called (numbers are copied from other question)
I think the reason is that it's expecting a json result from the page, when it's not.
In Chrome it says Uncaught SyntaxError: Unexpected token < referring to the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
To sum up, this works, but that jQuery alert and the console error needs to be fixed, and I think the right way would be handling properly the returned result page.
I hope you guys can help me fix it that seems quite a simple task, but Im really new to this. Thanks
Removing the dataType: 'jsonp' or changing it to 'json' turns out on my script not being executed and getting the following error:
XMLHttpRequest cannot load http://www.example.com/page.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com/myPage' is therefore not allowed access.
I think the reason is that it's expecting a json result from the page
It's expecting a JSONP response. (JSONP is not JSON). You said:
dataType: 'jsonp',
… which explicitly forces jQuery to treat the response as JSONP (and, as a side effect, GET).
the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
The server shouldn't be returning a PHP page. It should be executing the PHP code and returning whatever that outputs. It looks like it is outputting HTML.
You need to either:
Not tell your script to expect JSONP. (Note that you'll probably then have to configure CORS on the server to deal with same origin issues) or
Change the PHP to return JSONP

JSONP - "Uncaught SyntaxError: Unexpected token"

before I explain my issue I would like to mention that I'm a naive on jsonp. This is actually my very first attempt to work with JSONP.
Im using jquery ajax call to pullback data from a website.
my jquery code is below
$.fn.checkTPS = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function() {
var api_key = 'asdfasfsadfsadfsad';
var format = 'json';
var username = 'dame#example.co.uk';
var self = $(this);
var selfValue;
var feedback = $('.tps-feedback');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()) {
selfValue = self.val();
if (selfValue.length > 9){
$.ajax({
url: 'https://www.selectabase.co.uk/api/v1/tps/' + selfValue + '/',
type: 'get',
dataType: 'jsonp',
data: {
format: format,
username: username,
api_key: api_key
},
success: function(data) {
console.log(data);
},
error: function() {
},
jsonp: 'jsonp'
});
}
}
},3000);
}
});
});
};
I want to accommodate a service from selectabase.co.uk, according to them this is how I should use the service https://www.selectabase.co.uk/api/v1/tps/[number]/?format=json&username=[username]&api_key=[api key]
when I send request using ajax I get this error Uncaught SyntaxError: Unexpected token : and when clicked this opens up
{"ctps": false, "number": "1452500705", "resource_uri": "/api/v1/tps/01452500705/", "tps": false} by the way this I want but don't know what's this error is unexpected token :
I've copied the following link from inspect element tab (you can see the image below) I think this is the call that has been generated by json https://www.selectabase.co.uk/api/v1/tps/01452500705/?jsonp=jQuery17102731868715648129_14120077325500&format=json&username=dame40example.co.uk&api_key=asdfasfsadfsadfsad&_=14120077325500
I copied the link below from inspect element > source tab in chrome.. I think I should add an image to describe properly where this json data and link I've copied from.
I hope I've manage to convey my message across... please help if you have any Idea what do i need to add... Regards
The format=json in your query string should probably be format=jsonp. The server is replying with JSON, but you're expecting a JSONP response. But I don't know that they support format=jsonp, it's just a guess.
Alternately, if that server supports CORS and allows requests from your origin, you could handle JSON instead (just remove dataType: "json" from your ajax call). Beware that that would require that the user be using a browser that properly supports CORS, which IE8 and IE9 don't. (They support CORS, but not via the normal XMLHttpRequest object, and this is a browser inconsistency that jQuery doesn't smooth over for you. If you search, though, you can find "plugins" or similar that will handle it.)

Unable to get a simple jQuery.Ajax call to work

I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.

How do I pass or parse that access_token from the Dom to a Variable I can then Store and call for access_token?

With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.

Categories