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.
Related
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
Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.
I try to make a simple put-request with a jquery-ajax-call. I try to pass a normal json object but each time I get error 415.
The coding of the ajax call looks like the following:
$.ajax(
type: "PUT",
contentType: "application/json",
url: myURL + "/UpdateUser/User/" + localStorage.getItem("user"),
dataType: "json",
data: model,
success: function(data, textStatus, jqXHR){
},
error: function(jqXHR, textStatus, errorThrown){
}
});
The model is a simple javascript variable with is converted into json.
The JAXRS coding looks like the following:
#Path("/UpdateUser")
public class UpdateUser{
#PUT
#Path("/User/{user}")
#Consumes("application/json")
#Produces("application/json")
public String updateUser(#PathParam("user") String pUser, User pObject){
String return_val = "runs";
return(return_val);
}
}
Everytime when I run this code I get - as I already mentioned - the error 415. First I thought that I could have forgotten the content type ... but ... that was not the problem...
I really hope that you can help me solving this problem!
Greetings
As you did not provide enough information, I can only suppose what the problem is: Jersey is not configured to support JSON. That is described in details here. Besides more details to the problem you can probably find in the logs.
I am using ckeditor to format some data inside my textarea
<textarea id="editorAbout" rows="70" cols="80" name="editorAbout"></textarea>
Now when i try to post this data using jQuery.ajax like this,
var about=escape( $("#editorAbout").text());
$.ajax({
type: "POST",
url: "../Allcammand.aspx?cmd=EditAboutCompany&about="+about,
type:"post",
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); }
});
I get the error
HTTP Error 414. The request URL is too long.
I am getting the error here: http://iranfairco.com/example/errorLongUrl.aspx
Try clicking on the Edit Text button at the bottom left of that page.
Why is this happening? How can I solve it?
According to this question the maximum practical length of a URL is 2000 characters. This isn't going to be able to hold a massive Wikipedia article like you're trying to send.
Instead of putting the data on the URL you should be putting it in the body of a POST request. You need to add a data value to the object you're passing to the ajax function call. Like this:
function editAbout(){
var about=escape( $("#editorAbout").text());
$.ajax({
url: "Allcammand.aspx?cmd=EditAboutCompany&idCompany="+getParam("idCompany"),
type:"post",
async: false,
data: {
about: about
},
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("??? ?? ?????? ??????? ????","fail");}
});
}
For me, changing type:"get" to type:"post" worked, as get reveals all queries and hence make it bigger url.
Just change type from get to post.
This should help. :)
In my case, there was a run-time error just before the post call. Fixing it resolved the problem.
The run-time error was trying to read $('#example').val() where $('#example') element does not exist (i.e. undefined).
I'm sure this will, certainly, help someone.
In my case, the error was raised even though I was using 'POST' and the call to the server was successful. It turned to be that I was missing the dataType attribute...strange but now it works
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
A bit late to the party, but I got this 414, while using POST. It turned out is was a max path length in windows causing this error. I was uploading a file, and the actual request length was just fine (using post). But when trying to save the file, it exceeded the default 260 char limit in windows. This then resulted in the 414, which seems odd. I would just expect a 501. I would think 414 is about the request, and not the server handling.
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.