I'm trying to do a POST request with AJAX and I'm getting the following error:
Error: Not enough or too many segments
I have this function to send AJAX request:
function sendAjaxRequest(type, url, params, callback, returnType = 'json') {
var token = token_admin;
var request = $.ajax({
url: url,
method: type,
data: params,
beforeSend: function(xhr) {
/* Authorization header */
xhr.setRequestHeader("Authorization", "BEARER " + token);
// xhr.setRequestHeader("X-Mobile", "false");
},
dataType: returnType,
contentType: 'application/json'
});
request.done(function(res) {
callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
callback({ err: true, message: "Request failed: " + textStatus });
});
}
And I'm using it like this:
var hostAPI = 'server_url';
var token_admin = 'some_token';
var params = {
"criteria": {
"lang.es_es.verb.parent": "abandonar"
}
}
sendAjaxRequest("POST", hostAPI + 'words/getByCriteria', JSON.stringify(params), function(response) {
console.log("------------");
console.log(response);
console.log("------------");
});
But it's always returning me this error, the most weird thing is that I tested this webservice in Insomnia like this:
{
"criteria": {
"lang.es_es.verb.parent": "abandonar"
}
}
And it returns all data properly. I'm pretty new with AJAX and I have no idea of what's happening here, why it works in Insomnia and not with Javascript AJAX? What am I doing wrong?
Thank you very much for your answers.
This error usually comes when your JWT token is malformed or invalid. Please note that you are passing it in headers
xhr.setRequestHeader("Authorization", "BEARER " + token);
Please ensure that the token is valid, and the API is capable of accepting it. Also, please try to change BEARER to Bearer. The latter can be a cause if the API is not ignoring the case while checking for the header value.
Related
deleteNote()
{
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', universityData.nonce)
},
url: universityData.root_url + '/wp-json/wp/v2/note/98',
type:'DELETE',
success:(response) => {
console.log('congrats');
console.log(response);
},
error:(response) => {
console.log('sorry');
console.log(response);
}
});
}
I'm trying to delete a custom post type using rest api currently I've hard coded the id of the note
I've also setup the nonce but it still says forbidden, What should I do in this case. Please advice.
Edit: This is the response text "responseText: "{\"code\":\"rest_cookie_invalid_nonce\",\"message\":\"Cookie check failed\",\"data\":{\"status\":403}}"
"
I am calling jQuery ajax request, at CORS resourse. Backend works on nginx, and there set OPTIONS hook and response with allowed all domains, and all request types. But unfortunatly i am getting error calback. On Chrome Network console i saw 204 answer on OPTIONS request. And I have never seen my original POST request.
var email = $('#your_email').val();
var sendData = {
issue: {
description: "email:" + email,
category_id: 1
}
};
$.ajax({
url: "https://domen/issues.json",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("goodtry:goodtryq"));
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-type", "application/json")
},
data: JSON.stringify(sendData),
success: function (val) {
alert("Thanks you, we are going to contact you soon");
},
error: function (val) {
alert("Please check your internet connection");
}
});
So it is solved. I missed diagnostic message
Request header field Authorization is not allowed by Access-Control-Allow-Headers.
So helpful answer culd be found here:
https://stackoverflow.com/a/24556330/2835239
I am working on a piece of code where the user clicks on a button to make a call and the status of the call is displayed to him/her.
Everything is working fine and the calls are being made too, but the server which sends the json response is on another domain and I have no control over its response. I therefore used jsonp to get the response, but no matter what i did, i keep getting the error of Uncaught SyntaxError: Unexpected token.
I am attaching my code. please help as this is a live project and I am badly stuck in it. I need a response to be alerted with the message received by the server. the message received by the server in case of success is {"success": {"status": "success", "message": "Call successfully placed"}} and in case of error is {"error": {"message": "Invalid API Key"}}. I just need to display the message part.
my code:
function makecall() {
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = true;
var agentNum = document.getElementById('<%=lblCallFrom.ClientID%>').innerHTML;
var custNum = "+91";
custNum = custNum + document.getElementById('<%=txtNotoCall.ClientID%>').value;
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Calling...";
if (validatePhone(agentNum) && validatePhone(custNum)) {
$.ajax({
url: 'http://www.knowlarity.com/vr/api/click2call/?api_key=9e69eab0-1ec7-11e3-866c-16829204aaa4&agent_number=agent_number_variable&phone_number=Caller_number_variable&sr_number=%2B918881692001&response_format=json'.replace('Caller_number_variable', custNum.replace('+', '%2B')).replace('agent_number_variable', agentNum.replace('+', '%2B')),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (res) {
alert(JSON.stringify(res));
},
error: function (res) {
alert(JSON.stringify(res));
}
});
} else {
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Num. should be a valid 10 digit mobile no.";
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = false;
}
}
Try using this as an absolute minimum where you can pass in valid hard wired values for the numbers:
var url = 'http://ip.jsontest.com/ ';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
success: function (res) {
if (res != undefined) console.log(res);
},
error: function (res) {
if (res != undefined) console.log(res);
}
});
I need to create a JSON ajax request from another domain. after I think I got over the cross domain issues, here is where I stuck:
I need to add my custom "myCustomHeader" header - that's easy from a server, but seems to be much more complicated from the client...
We added them
$.ajax({
type: 'POST',
data: put the results of your header request here,
url: 'http://server.com/service',
beforeSend: function (xhr) {
xhr.setRequestHeader('myCustomHeader', '1')
},
success: function(data) {
alert('success.');
}
});
This generates a preflight header with the headers I wanted, without the values (CSV), but they do not appear in the header of the request itself (as myCustomHeader=X)...
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");
I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};