I am trying to make a JSON Post to the Simpleconsign API, and I keep receiving a 0 error from the browser. Here is my code:
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
type: 'POST',
key: "apikey,
url: 'https://user.traxia.com/app/api/inventory',
contentType: "application/json",
success: function(result){
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
I am a beginner at posting to the REST API's, so any help would be much appreciated. Thank you!
I don't see any data in your Ajax POST? This code should have work
var postData = {
"key": "Your API Key Here",
"query": "some query",
"consignorId": "123456",
"includeItemsWithQuantityZero": "false"
};
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
type: 'POST',
data: postData,
url: 'https://user.traxia.com/app/api/inventory',
contentType: "application/json",
success: function(result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
http://wiki.traxia.com/display/guide/List+and+Search+Inventory
Related
I have an web service running on http://remoteip:8080/TestService I want to call it through java script this service takes parameters in JSON format
{"status":"F","subscriber":[{"PhoneNumber": 1234567890}, {"PhoneNumber":0123456789}]} like this how can I implement this in javascript.
<script>
function callWebService() {
jQuery.ajax({
url: 'http://remoteip:8080/TestService',
type: "POST",
data: {
"status": "F",
"PhoneNumber":"0123456789",
.....
.....
},
dataType: 'json',
success: function (data) {
console.dir(data);
},
error: function (xhr, err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
},
complete: function () {
}
});
}
</script>
Hope it helps you
here is about a javascript widget DataTables. An example can be found here.
sorry, i am not a javascript specialist. How can i transfer the selected row (practically my objects from server) back to the server in form of json-format ?
i did try to do it with this approach, but it doesn't work:
$('#save_btn').click( function () {
//table.row('.selected').remove().draw( false );
console.log ( table.rows('.selected').data());
var stringData = table.rows('.selected').data().serialize();
$.ajax({
url: '${pageContext.request.contextPath}/ajax/storeSelectedContacts',
data: stringData ,
type: "POST",
cache: false,
success: function (savingStatus) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error")
}
});
} );
many thanks
First, its return array of objects.
var stringData = table.rows('.selected').data();
Second, for convert array to JSON ...
var aData = table.rows('.selected').data();
var sData = JSON.stringify(aData)
and for send to server you slould indicate that is JSON dataType: 'json'
$.ajax({
url: '${pageContext.request.contextPath}/ajax/storeSelectedContacts',
data: sData ,
type: "POST",
cache: false,
dataType: 'json',
success: function (savingStatus) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error")
}
});
} );
Browser Current URL is:
http://localhost/a_project/index.html
I have a Ajax code calling a PHP file who checks the login details and return a unique id if found in database else returns false. On Ajax success i want to create a URL and redirect the browser to that. I tried following code:
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
var pathArray = window.location.pathname.split('/');
window.location = pathArray[1] + "/my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
But it always result in following URL:
http://localhost/a_project/a_project/my%20page.html?id=20
Instead it should be routed to:
http://localhost/a_project/my%20page.html?id=20
I have a feeling that i am missing something but not sure what.
try this:
window.location = window.location.origin + '/a_project/my%20page.html?id=20' + res;
Why do you need to generate the URL?
As you site root is http://localhost/a_project/, the pages index.html and my page.html are in the same directory. You can use relative path.
Just use "my page.html?id=" + res
And I would strongly recommend NOT to have spaces in URL.
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res) {
if (res > 0) {
location.href = "my%20page.html?id=" + res;
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
Add A Base URL in the javascript then concatinate with the original Url
var baseUrl="http://example.com/";
$.ajax({
url: 'site_api/user_login.php',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: formData,
success: function(res)
{
if(res > 0){
var pathArray = window.location.pathname.split( '/' );
window.location =baseUrl+ pathArray[1] + "/my%20page.html?id="+res; //changes Here
} else {
$('#login_error').html('Invalid Credentials. Please try again.');
}
},
error: function(xhr, ajaxOptions, thrownError)
{
alert (xhr.status);
}
});
I have used the do ajax function for text field like this.
function doAjax(input)
{
var formData="proId="+input.attr('id')+"&text="+input.val();
$.ajax({
type: "POST",
url: "update_protask.php",
data: formData,
success: function(data){
if(data==1)
{
input.siblings().text(input.val()).show();
input.hide();
}
else
{
input.siblings().show();
input.hide();
alert("something Wrong !");
}
},
error:function (xhr, ajaxOptions, thrownError){
alert("Error:"+xhr.status+" "+thrownError);
}
});
}
How to write this do ajax for select menu?
I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.
Here is the javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List/AddItem",
data: "{ ListID: '1', ItemName: 'test' }",
dataType: "json",
success: function(response) { alert("item added"); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Here is the controller method:
Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
'code removed for brevity
'ListID is nothing and ItemName is nothing upon arrival.
return nothing
End Function
What am I doing wrong?
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType and set data without double quotes.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
In my case, if I remove the the contentType, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.