I have this code:
$.ajax({
url: '{{ route('frontend.validation') }}?sex=' + $(".sex").val() + '&date=' + $(".date").val() + '&hour=' + $(".hour").val()+ '&track=' + $(".track").val(),
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
console.log(response);
})
}
});
In result I have:
{"status":"ok","message":"Twoja rezerwacja zosta\u0142a zrealizowana"}
in console I have:
[Log] {status: "ok", message: "Twoja rezerwacja została zrealizowana"}
(projekt1.test, line 284) [Log] {status: "ok", message: "Twoja
rezerwacja została zrealizowana"} (projekt1.test, line 284)
I need check my status.
If it's "ok" - then message I want show in alert box.
When status = "error" them I want show alert with "Sorry, we have error with yours reservation".
How can I make it?
u have already json object so you don't need to parse. Remove each method ,it uses keys count so you get alert two times .
success: function (response) {
if(response.status==="ok"){
alert("ok")
}
else if(response.status==="error"){
alert("error")
}
}
try this
$.ajax({
url: '{{ route('frontend.validation') }}?sex=' + $(".sex").val() + '&date=' + $(".date").val() + '&hour=' + $(".hour").val()+ '&track=' + $(".track").val(),
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
var obj = JSON.parse( response );
console.log(obj['status'])
})
}
});
From Mozilla documentation
The JSON.parse() takes the string text input and returns the object corresponding to the given JSON text.
Use JSON.parse(response) and then read the index "status" of the object.
The question is already answered HERE LINK
$.ajax({
success: function(response){
$.each(response, function (key, value) {
if(response.status==="ok"){
alert("Twoja rezerwacja została zrealizowana");
}
else if(response.status==="error"){
alert("Sorry, we have error with yours reservation");
}
})
},
error: function(response) {
alert("Sorry, we have error with yours reservation");
}
});
return False;
....
Related
I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work
I have a view that takes a list of a model as the Model, so
#model List<Collections.Models.Status>
I want to pass this list as the data for an Ajax call, but I keep getting "System.Collections.Generic.List[Collections.Models.Status]" instead of the values in the model.
Here's the Ajax code:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(#Model),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
Which translates in the debugger to:
$.ajax({
url: "/Home/Update",
data: JSON.stringify(System.Collections.Generic.List`1[Collections.Models.CollectionStatus]),
type: 'POST',
dataType: 'json',
success: function (responseJSON) {
if (responseJSON.message == 'success') {
alert('here');
}
},
error: function (error) {
showModal("Error: " + error.message);
}
});
How do I pass the actual values of the list instead of System.Collections.Generic.List[Collections.Models.Status]?
I've tried #Model.ToList(), #Html.Raw(Model), neither worked.
set contentType property to application/json.
and use below code to set data property
data: JSON.stringify({'your controllers parameter name': '#Model'})
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>
I have ajax call to JSON object:
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
alert(answer);
},
error: function(answer) {
alert("Error")
}
});
and a JSON file:
{
"saveTime": 1396522039
}
I want to get alert not a value of "saveTime" but volue of object. I mean the result of alert must be exactly "saveTime".
Appreciate your help.
Try this for get property name
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
for (prop in answer) {
alert(prop); // alert property name => saveTime
}
},
error: function(answer) {
alert("Error")
}
});
this will help you
var keys = Object.keys(answer); // This will return all keys of an object as an array.
now use it as
alert(keys[0]);
Try this you get saveTime:
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
$.each(answer, function(key, val) {
console.log('Key: '+key+' Val: '+val);
});
},
error: function(answer) {
alert("Error")
}
});
can somebody please tell me, how can I display json data returning from the ajax call. I am new to this.
$.ajaxSetup({
cache: false,
timeout: 5000
});
//String.prototype.toJSON;
var the_object = {};
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + " value :" + obj[prop]);
}
return strArray.join();
}
//var ntid = "hhsh";
//document.writeln("httpRequest.responseText");
$(document).ready(function() {
$("button").ajaxStart(function() {
alert('Triggered ajaxStart handler.');
});
$("button").click(function() {
$.ajax({
type: "POST",
dataType: 'JSON',
//data: "{'ntid':'john'}",
//contentType: "application/json; charset=utf-8",
//processData: false,
url: "Testing.aspx/SendMessage",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(result, txtStatus, httpRequest) {
alert(txtStatus);
//$('#status').html(httpRequest.responseText);
//the_object = result;
$('#status').html(concatObject(result));
//$('#status').html(the_object);
//alert("hello" + concatObject(the_object));
//document.writeln(concatObject(the_object));
}
});
//alert(concatObject(the_object));
//$('#status').html(concatObject(the_object));
});
});
above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here. Its only diplaying this line:
toJSON value :function (key) { return this.valueOf(); }
Your result is most likely rooted with a property named d. Try modifying your success to use result.d;
This is usually a security measure that has to do with exploits which target a JSON collection with single root parent.