Issue with AJAX and jQuery - javascript

<html>
<head>
<title>Ajax</title>
<script type="text/JavaScript" src="jquery-1.5.1.min.js"></script>
<script type="text/JavaScript">
function register()
{
$.ajax({
type: "GET",
url: "http://exampleurl.com/api/index.php",
data: "action=login_user&app_key=MyAPIKey&username=Bob&password=HisPassword",
dataType: "text",
success: function(data)
{
alert(data);
}
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
</script>
</head>
<body>
<form>
<input type="button" value="Test" onclick="register()"/>
</form>
</body>
</html>
The URL returns a string (plain-text) when used in the address bar. Why is the above code not working? When I click on the button, I get no alert. Basically, nothing happens.
Browsers tried: IE 8 and Chrome.
Thank you for your time.

There's probably an exception being thrown in the $.ajax call.
Consider
ensuring your URI is well formed by taking the query parameters out of the URL and supplying a data object instead:
data: {
action: login_user,
app_key: ....
etc
}
adding an error handler too

Is example.com the URL of your local site? If not, your above example violates Same Origin Policy. You can circumvent this by doing the call through a proxy on the server side.

Try to add
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
http://api.jquery.com/jQuery.ajax/

Have you tried to separate the data ?
$.ajax({
type: "GET",
url: "http://exampleurl.com/api/index.php",
data: "action=login_user&app_key=MyAPIKey&username=Bob&password=BobPassword",
dataType: "text",
success: function(data) {
alert(data);
}
});

Do you have access over the backend url?
You might need to declare the contentType. You might also need to do a post and set the data.
data: "{ 'action': 'login_user', 'app_key': 'MyAppKey', etc. }"

Related

Posting a JSon object to Webservice via AJAX

I'm trying to send an object in JSon format to my Java backend by AJAX, but I was unsuccessful.
I wonder if the syntax is properly correct.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scripts/jquery.min.js.download"></script>
<script src="scripts/jquery.imagemapster.js.download"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var myJSon = {"name":"Jo","age":30,"city":"Ny"};
$.ajax({
type: "POST",
url: 'http://localhost:8080/Servidor/server',
//contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(myJSon),
success: function (data){
alert('Sucess');
},
error: function () {
alert('Error');
}
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
When the line contentType: "application/json;charset=utf-8" is not commented out, I get the following error in the backend: INFO: Could not find grammar element for class java.lang.String
Is the syntax correct? Can the error be from the backend itself?
P.S.: Sorry for my bad english
Your code is good, you just misspelled "success" on the AJAX call (you need 2 letter c's instead of 1). So replace sucess: function(data){...} with success: function(data){...} https://jsfiddle.net/stephentillman/aow5pah2/

jquery:ajax not firing in document getready

I have added jquery in head section and below code are in body section.
Problem is this isn't working.
Even alert is not showing. I am not getting any error in firebug.
I want to execute ajax on page load. I am not sure my approach is good.
Please advise. Below are the js code.
<script type="text/javascript">
$('document').ready(function(){
alert('Test');
$.ajax({
type: 'post',
url: 'profile_exec.php',
cache: false,
dataType: 'json',
data: uid,
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
var applied_counts = data.applied_count;
alert(applied_counts);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
</script>
As you can see this should work fine:
$('document').ready(function(){
alert('ready');
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'GET',
}).then(function(data){
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
since even the alert is not showing, check your html code. Maybe swap your jQuery with the google CDN served jQuery.
Maybe you have conflict or noConflict somewhere else. Check this out: jQuery.noConflict
Try this code:
jQuery(document).ready(function(){alert('test')})

Ajax request not working when a function is added to the success option

I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.

Receive serialized in php data by using ajax

I have a php script, which return serialized in php data. And I try to receive this data by using $.ajax() method from jQuery 1.7. Here is the example.
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res) {
alert('COMPLETE() done');
console.log(res);
}
});
In console I see only
Object { readyState=0, status=0, statusText="error"}
So, what I do wrong? Could you help me please?
UPD
Interesting notice: if I use JSONP dataType request can receive data, but can't process it.
Here is an example.
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
dataType: 'jsonp',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Instead of complete: use success: then res will be the returned data from your ajax request.
Remember to use error: as well incase there is an error with you call, as it seems that there might be in your console output.
Code:
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Your code is probably fine, but you're trying to violate the same origin policy. Basically, if your site is http://aaa.com/, you cannot make AJAX called to http://bbb.com/.
There are a few ways around it:
Getting around same origin policy in javascript without server side scripts
But most of them require that both sides play nice.
The response is the second parameter of complete function:
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res,response) {
alert('COMPLETE() done');
console.log(response);
}
});
More info: http://api.jquery.com/jQuery.ajax/
You should also consider using JSON, not php serialized data

why not get POST parameters in ajax POST of jQuery

The code is listed below:
$.ajax({
type: "POST",
url: "http://localhost:3000/rcm/global_config/update",
data: {k: 'sdfa', v: 'dsfas'},
success: function(data, textStatus, XMLHttpRequest){
alert("数据更新成功");
},
error: function(xhr,textStatus, errorThrown){
alert("数据更新失败,请刷新回滚");
}
});
In the server i can not get post parameters, and then i tamper the request sent by ajax, it doesn't send the data params at all. i don't know where i am wrong.
thank you in advance.
This issue has been asked and aswered before in SO jquery-ajax-post-sending-options-as-request-method-in-firefox
This is because the same origin policy on FF. It only allows you to do XMLHTTPRequests to your own domain.
Maybe your script is loaded from domain "localhost" and your ajax request to "localhost:3000"
Please try this
$.ajax({
type: "POST",
url: "http://localhost:3000/rcm/global_config/update",
data: "{'k': 'sdfa', 'v': 'dsfas'}", // Change are here in this line
success: function(data, textStatus, XMLHttpRequest){
alert("数据更新成功");
},
error: function(xhr,textStatus, errorThrown){
alert("数据更新失败,请刷新回滚");
}
});
$.ajax({
type: "POST",
url: "http://localhost:3000/rcm/global_config/update",
data: $.param({k: 'sdfa', v: 'dsfas'}),
success: function(data, textStatus, XMLHttpRequest){
alert("数据更新成功");
},
error: function(xhr,textStatus, errorThrown){
alert("数据更新失败,请刷新回滚");
}
});
Wrapping the data object in $.param should do it. It will convert that object to the string "k=sdfa&v=dsfas"
hi
please try somthing like this:
$.ajax({
type:"POST",
url:"student/info/ajax.php",
data:({type:'test', r:which}),
success:function(data){
if((data.result)=='true')
$('#result_popup').html(data.output);
},
dataType:"json"});
return false;

Categories