good day, im trying to consume a web service in react, but im having problems with the ajax function, i'm not sure if is working my code is this:
prox= {"email":email, "password": password};
//tag comment
$.ajax({
type: 'POST',
url: (web service url),
data: JSON.stringify(prox),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: 'json',
success: function(data) {
this.setState({success: true, result: data});
alert("success");
this.setState({prueba: 'success'});
}.bind(this),
error: function() {
this.setState({failure: true});
alert("failure");
this.setState({prueba: 'failure'});
}.bind(this)
});
but i dont have any alert, when i click the button only re-render the form, the function handdle submit works, i try it putting a confirm() in the space where the //tag comment is and the confirm pop up, but the alerts dont, i think that i have an error in the function or something, thank's for the help.
I didn't run the script but just looking at it I imagine the problem could be your bind(this)
this.setState to me should be an error “is not a function” as this is not the react object. To get an alert try placing the alert as the first state.
To be sure just look at your browser console.
It looks like its working for the most part. I threw it into a JSBin and nothing seems to be out of the ordinary.
http://jsbin.com/rulaguxote/1/edit?html,js,output
I kept your JSX mostly the same, and added a few things in the component to help you visualize its state. Click the button to send a fake ajax request. Depending on the state, it will either send back an HTTP status of 200 or 400 (success or failure). This way, you can see how the success() and error() functions behave.
Another thing to note: If you are concerned that your .bind(this) is the reason your code is not working, you can specify the context like this:
$.ajax({
type : 'POST',
url : '/test',
data : JSON.stringify(prox),
contentType : "application/json; charset=utf-8",
context : this, //use this instead of .bind
success : function (data) {
this.setState({success : true, failure : false});
alert("success");
},
error : function () {
this.setState({failure : true, success : false});
alert("failure");
}
});
Let me know if you have any questions.
Doing some extensive research i see that my real problem whas the same origin policy, now im working fine in the localhost version of the project, thank you.
Related
I'm able to dump value of the variable message in console .
But im not able to send it off in POST Request.
AJAX call:
chat.throwmsg = function(message) {
if ($.trim(message).length != 0) {
console.log(message);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message} ,
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
}
}
This maybe due to wrong syntax, but I've tried both single and double quotes, and combination as well .
With a wild assumption, you are not having any error messages in developer console and chat.php has a post handler forthese parameters
Since your data is JSON, please change the code as this way and have a try..
var temp={ method: 'throw', message: message};
var param=JSON.stringify(temp);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: param ,
dataType: "json",
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
after reviewing the code I could not find any issues that restrict the data to be sent along with ajax request,if you are having any syntax errors you should have been warned prior the request initialization, however I recommend you to check the request header in the network tab of browser console and see your sending data along with the request if it's there you probably need to check the code of getting the post data in your server-side implementations
I have built my first website and it works on local server but not online. The problem is loading a json file with Ajax. In the published version I get the error message that my object is undefined.
This is a (simplified) version of my code that shows the problem:
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
This is the message in the console when running on local server:
great success! main.js:37:13
Object { id: "brunskar", title: "<h2>Brunskär</h2>", image: "img/countryside.jpg" }
But when I publish online this is what I get:
great success! main.js:37:13
TypeError: torp.items is undefined
In the Utilities Net section I get status code 200 and the whole content of the JSON file is readable under the "reply" tab, so it seems like the file is loaded. But I don't understand why my object is undefined.
Sounds like an asynchronous issue (your page is loading before your ajax call can return the data, therefor it is returned as undefined) one way to solve this is to put a function inside your ajax call that fires your page functions that use the data being returned by the call.
$.ajax({
url: "json/torp.json",
contentType: "application/json",
success: function (data) {
torp = data;
console.log('great success!');
console.log(torp.items[3]);
function usePageData (); <----calls webpage function utilizing
data
},
error: function (/* request, error */) {
console.log('Network error has occurred please try again!');
}
Hope that helps!
Problem solved by changing
contentType: "application/json"
to
dataType: "json"!
I used the tip from Patrick Evans in one of the comments. Thank you for the help!
I got a strange problem. while i run my VS and click specific button on browser, an ajax function fired and shows error. After debugging i found the URL is showing error. the error is::
POST http://localhost:4942/Employee/Employee/AllEmployees 404 (Not Found)
The problem is, for some reason the "/Employee" controller is coming two times.
my ajax call is:
function allEmployeeFunc() {
$.ajax({
type: "POST",
url: "Employee/AllEmployees",
//data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
// context:"" ,
error: function (msg) {
alert("something is wrong");
},
success: function (data) {
}
});
}
Here the URL clearly showing only one /Employee. so whats the problem?? can anyone help please??
Try to add a slash to the URL
url: "/Employee/AllEmployees"
I guess you are using too much in url; I can see "/Employee/Employee/AllEmployees". Employee twice. Rather try
url: "AllEmployees"
I guess that should do. Assuming that you have annotation [HttpPost] in place to hit AllEmployees function.
I found a script for real chat using $.ajax jQuery, but it refereshes only my massages. For example:
I write to You: Hello, this message refresh for me.
You write to me: Hey, to see your message I must refresh a site by clicking F5, but You do not have to click F5. Something wrong!
My $.ajax code:
$(document).ready(function() {
$("#lupnijto").click(function (e) {
$("#lupnijto").hide();
$("#LoadingImage").show();
var zeszyt_value = 'zeszyt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax ({
type: "POST",
url: "response.php",
dataType: "text",
data: zeszyt_value,
cache: false,
success: function(response) {
$("#responds").prepend(response);
$("#contentText").val('');
$('#contentText').focus();
$("#lupnijto").show();
$("#LoadingImage").hide();
},
error:function (xhr, ajaxOptions, thrownError) {
$("#lupnijto").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
What am I doing wrong? Why data only refreshes for me? How the chat works? Am I doing it correct? I accept answers. Thanks.
For such real time applications, you need to use WebSockets: On MDN
,you can also check on some WebSockets API Socketio for Node.js
I do advice those, but also you can use AJAX (not recommended).
You can use Socket.IO. For non-WebSockets browsers you can use Engine.IO.
I have to update a large collection so I am calling in a loop an web api. I use jQuery.ajax()
Something like this:
$.ajax({
type: 'GET',
url: 'http://www.somesite.com/API/API.php',
jsonpCallback: 'API_SC4',
contentType: "application/json",
dataType: 'jsonp',
data:'action=update&page='+collection[currentIndex].name+'&callback=API_SC4',
async:false,
success: function(data) {
//use data for update of collection[currentIndex]
UpdateNext(currentIndex+1);
},
error: function(e) {
//interpret error
UpdateNext(currentIndex+1);
}
});
The problem is the collection is quite large and sometimes I get a 502 Bad Gateway error and the ajax error handler is not called.
I even tried $( document ).ajaxError() but i'm doing a cross-domain jsonp call , and it seems .ajaxError() does not get called in that situation.
Is there any way to handle that error? Something at window level?
I can see the error in the Chrome development console , and I was thinking there might be a way.
Thanks
Yes, there is: statusCode. See the jQuery documentation on AJAX for details.
Simple example:
$.ajax({
statusCode: {
502: function () {
alert('Fail!');
}
}
});