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
Related
I want the loader to stay until the complete execution is complete and statement $("#xyzDiv").html(data) has been executed. Currently the loader gets hidden after the first ajax call. Even if i add "beforeSend: function () { $("#loader").show(); }" to GetDataList(), the loader is not staying.
$.ajax
({
type: "POST",
url: ajaxUrl,
data: dataObj,
beforeSend: function () { $("#loader").show(); },
success: function (data)
{
if (data.result)
{
GetDataList();
toastr.success(data.strMsg);
}
else
{
toastr.error(data.strMsg);
}
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
},
complete: function () { $("#loader").hide(); }
});
function GetDataList()
{
$.ajax
({
type: "Get",
url: ajaxUrl,
data: dataObj,
success: function (data)
{
$("#xyzDiv").html(data);
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
}
});
}
I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO
I am using Ajax (and jQuery UI) and when i press a button on the dialog i trigger the following action in the controller:
[HttpPost]
public JsonResult DeletePost(int adrId)
{
return Json("Hello World Json!", JsonRequestBehavior.DenyGet);
}
My JQuery Code looks like this:
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog(
{
buttons: {
"Ok": function () {
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: { adrId: 6 },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
$(this).dialog("close");
}
}
});
jQuery('.delete').click(function () {
})
})</script>
However, when i POST to the server, i get an "Error: Not Found"
The problem is with your data parameter not being a valid JSON payload.
It is not valid JSON, because jQuery is using the jQuery.param() method internally to prepare the request parameters for typical POST submissions, and it will get converted to the following string:
adrId=6
However, the server is expecting a JSON payload, and what you specified is clearly not a JSON payload. A valid JSON payload would be:
{ 'adrId': 6 }
One approach to send correct JSON in the data parameter is to refactor your jQuery AJAX to look like this:
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: "{ 'adrId': 6 }",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert("success");
},
async: true,
processData: false
});
Or you can use JSON.stringify as suggested by others.
An alternative approach would be to send your data as 'application/x-www-form-urlencoded; charset=UTF-8' which is the default, and that way you don't have to change your data parameter. The code would be much simplified:
$.ajax({
url: '/Home/DeletePost',
type: 'POST',
data: { adrId: 6 },
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
alert("success");
},
async: true
});
JQuery will recognize that the result is valid JSON.
Try this:
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog(
{
buttons: {
"Ok": function () {
$.ajax({
...
data: JSON.stringify({ adrId: 6 }),
...
});
$(this).dialog("close");
}
}
});
jQuery('.delete').click(function () {
})
})</script>
How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
Using Qunit and MockJax, I seek to have two tests, simplified here for ease of understanding. One of the following two tests fails, presumably because the two tests run in parallel and thus they do not each get their own detour of $.ajax(). (The only difference is the responseText in each.) Any ideas on a good way to tweak it so that both the following tests pass?
function testAjax() {
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/fakeservice/1',
data: {'a':'b'}
});
}
asyncTest("testAjax 1", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'foo' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, 'foo', "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
asyncTest("testAjax 2", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'bar' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, "bar", "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
You must call $.mockjaxClear() at the end of each test (e.g. in the teardown() method of your module). This destroys the mock and prepares the environment for the next test.
function testAjax() {
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/fakeservice/1',
data: {'a':'b'}
});
}
module("AJAX tests", {
teardown: function() {
$.mockjaxClear();
}
});
asyncTest("testAjax 1", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'foo' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, 'foo', "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
asyncTest("testAjax 2", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'bar' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, "bar", "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
See your adapted example on jsFiddle.