Error while trying to consume a Mashape webservices using javascript - javascript

I'm trying to consume a mashape api using ajax, javascript.
I have a text area and a button in my html :
<div>
<textarea id="message" placeholder="Message">
</textarea>
<br><br>
<button id="mb" onclick="success();">Analyse</button>
</div>
And a really simple javascript success() function :
function service(){
$.ajax({
url: 'https://loudelement-free-natural-language-processing-service.p.mashape.com/nlp-text/', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'GET', // The HTTP Method
data: {text: $("#m").val()}, // Parameters go here
datatype: 'json',
success: function (data) {
alert(data);
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "<MY MASHAPE KEY>"); // Enter your Mashape key here
}
});
};
however when i trigger the function, the following error is displayed in my browser console :
ReferenceError: success is not defined
Any idea on how to solve this error ?

The function success() dosn't exist however you have a service() function either you change the invocation success() -> service() or you change the function name from function success -> function service

Related

Ajax returns undefined

I'm trying to upload a image to my server using a POST form and AJAX. But everytime I submit the form, my AJAX returns an undefined in my error box. This is the Ajax function I'm talking about:
$('.register_submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "./functions/register.php",
data: new FormData(this),
contentType: false,
processData: false,
success : function(data){
if (data.code == "200"){
window.location.replace("./?page=home");
} else {
$(".display-error").html("<ul>"+data.msg+"</ul>");
$(".display-error").css("display","block");
}
}
});
});
and my form:
<form class="addCar_form" data-toggle="validator" method="post" enctype="multipart/form-data" >
<input type="file" class="form-control productimages" id="images" name="images[]" onchange="preview_images();" multiple/>
<input type="submit" name="addCar_submit" value="Auto toevoegen" class="btn btn-default button addCar_submit">
</form>
Please do not mark this question as a duplicate, as I've been reading about ajax and it being asynchronous in other topics but I'm really not getting it from these answers. Anyone who sees what I'm doing wrong?
The click handler for $(".register_submit") would be targeting the button; then the button is passed in through FormData(this). FormData should instead contain a reference to the form...
Also, I don't see a register_submit class definition on the form in this example, so maybe it's getting overlooked?
In your PHP page, can you trace through it to see what form data is being passed? That is helpful to track down these kinds of problems, by evaluating the form posted data.
I think your server returns an error with a different status code. Therefor the success callback might not be called.
There are different callback available for $.ajax I think error is the one you need to check.
From the docs:
error callback option is invoked, if the request fails. It receives the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
Try:
$('.register_submit').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "./functions/register.php",
data: new FormData(this),
contentType: false,
processData: false,
success: function (data) {
if (data.code == "200") {
window.location.replace("./?page=home");
} else {
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});

POST variable error

Good day, i need past variable in post to other file
}
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}
code variable
<tr>
<td class="col1"><label for="pat">Sucursal:</label></td>
<td class="col2">
<input type="text" name="suc" id="suc" class="medium" readonly="true" style="width: 200px;"size="40" maxlength="200" onChange="javascript:this.value=this.value.toUpperCase();" />
<input type="button" class="btn btn-success btn-sm" id="sbm" name="sbm" value="Buscar" onclick="llenaSucursales()" />
</td>
</tr>
Error image is :
whats its a problem?
I await your help and I started reading and search and can not find the error
You should have a look at the jQuery documentation for $.ajax() to understand what you may use to react on errors in your AJAX call:
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function(jqXHR, status, errorThrown) {
// This callback is called if your AJAX query has failed
alert('Got the error ' + errorThrown + ' with status ' +status);
}
});
I would also recommend to open up the Developer Tools (F12 in most browsers) and check the "Network tab" to see the responses of AJAX calls.
Not related to your question:
In the future please take more care when writing your post. Remove unnecessary blank lines, don't post code with errors (just concentrate on the important parts of what you post) - thanks.
The error was that I was missing "/" the address of the file, Thanks, then I leave the code
function empleados(){
if($("#suc").val()=='')
{
alert('Elige una sucursal');
return false;
}
$.ajax({
url: '/emps.php',
type: 'POST', // GET or POST
data: {"suc":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}

JQuery $.ajax() post - data to call method in my Controller

I am still quite new to JQuery and am having difficulties with using the $.ajax() function.
I am attempting to send data to controller for processing.
Debugging the Jquery, It doesn't look the ajax is called when click on the button.
function getGuestInfo() {
var phone= $('#phone').val();
$.ajax({
type: "GET",
url: "/RequestForms/getGuestInfo.ajx",
data: phone,
cache: false,
success: function(response){
// we have the response
window.alert("success"+ response);
$('#guestName').html(response);
$('#address').val('');
$('#email').val('');
},
});
window.alert("Call");
}
the button:
<input type="button" value="Call Func" onclick="getGuestInfo()"/>
Controller:
## #RequestMapping(value = "/getGuestInfo.ajx", method = {RequestMethod.GET, RequestMethod.POST})
public #ResponseBody String getGuestInfo(
final RequestContext requestContext, #ModelAttribute Form form) { ## Do something }
Also, In this case should I use post or get to call the method in the Jquery function?
Considering that you are only passing a string as your data and your Controller is expecting a Form object, your server is probably returning a "Not Found" error. I would recommend always adding the error event to your ajax calls so you can catch them.
error: function (jqXHR, textStatus, errorThrown) {
// Do something here
},
As for passing the correct data, you'll probably want to do something like this:
var dataToSend = { "phone" : phone };
Then change your data to:
data: JSON.stringify(dataToSend),

Ajax error message can't accept parameters

I am trying to send the ID provided when the ajax-call is called to the error message but when I do it this way, the error message gets displayed even if no error message is returned through ajax (likepost_XML.php):
function like(commentid){
$.ajax({
type: 'POST',
url: 'likepost_XML.php',
data: {
comment_id: escape(commentid)
},
success: successlike,
error: errormsga(commentid)
});
}
And this is the Error function:
function errormsga(commentid)
{
console.log(":didn't work bro");
$("#"+commentid).css({"color":"red"});
}
You are calling errormsga instead of setting an error callback function. Wrap the call in a function expression.
error: function(){
errormsga(commentid);
}

How to handle response of a POST request in jQuery

I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.

Categories