How to get data value using this code? - javascript

I used this below code to post data to server,its working fine,but How do I get values of data.Suppose server will send name and surname of a persion alert message showing these values but how do I get in variable...please help...
var data = {"data":{"app_name":"hansel","device_id":"123456"}};
//data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "http://15.27.0.180/cr/z0501/getconfig", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$.each(data, function(key, value){
$.each(value, function(key, value){
//alert(value)
alert("key" +key +""+value)
var servervalues=value;
//alert(servervalues+servervalues);
});
});
}
});
return false;
});

Just use jqXhr object
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});

Related

Parse json from php in jQuery

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;
....

Cannot use 'in' operator to search for 'length' in

I read this answer
And I did this:
function countryPage() {
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=parse&disablelimitreport=true&format=json&prop=text|langlinks&noimages=true&mobileformat=true&page="+ curTitle + "&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: countryPageSuccess
});
}
function countryPageSuccess(counterObject, data) {
$.each(data, function(i, item) {...
But if I then do as per that answer
$.each(JSON.parse(data), function(i, item) {
I get
Uncaught SyntaxError: Unexpected token o in JSON at position 1
It's already a JSON object. You cannot parse it again.
to receive HTTP error code, provide a error callback function next to success, showed my code below.
function countryPage() {
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=parse&disablelimitreport=true&format=json&prop=text|langlinks&noimages=true&mobileformat=true&page=1&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: countryPageSuccess,
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
}
function countryPageSuccess(data, result) {
$.each(data, function(i, item) {
console.log(item);
});
}
countryPage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

transfer selected table's row (javascript DataTables) to server

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")
}
});
} );

Converting data from JSON to JavaScript array

I'm having a problem with converting data sended from "naloga3.php" .
How can i convert from JSON to array.
JAVASCRIPT
<script>
function shrani(){
var formData = {naslov: document.getElementById("naslov").value,
besedilo: document.getElementById("besedilo").value,
datum:0
};
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#zapisi').append('<a>'+data+'</a></br>');
var x = eval("(" + data + ")");
for(var i=0;i<x.length;i++)
{
$('#zapisi').append('<a>'+x.length+'</a></br>');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});
}
</script>
naloga3.php
<?php
$file="podatki.txt";
$podatki=file_get_contents($file);
$izpolje=array();
$izpolje= json_decode($podatki,true);
$polje=$_POST;
$polje['datum']=date('H:i:s');
if($izpolje!=null)
{
array_unshift($izpolje,$polje);
file_put_contents($file,json_encode($izpolje));
}else
{
$tr=array();
array_unshift($tr,$polje);
file_put_contents($file,json_encode($tr));
}
$podatki=file_get_contents($file);
echo json_encode($izpolje);
?>
My output
[{"naslov":"d","besedilo":"d","datum":"16:07:05"},{"naslov":"dddd","besedilo":"d","datum":"15:51:41"},{"naslov":"d","besedilo":"d","datum":"15:51:33"},{"naslov":"d","besedilo":"d","datum":"15:51:30"},{"naslov":"d","besedilo":"d","datum":"15:51:26"}]
What you need to do is set the dataType of your ajax response to json, then you need to iterate the returned object and append within the $.each() loop.
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
dataType: "json", // jQuery will now parse the returned data and return an object
success: function(data, textStatus, jqXHR)
{
$.each(data, function(i,obj){
//now you can acess navlos, besedilo and datum
$('#zapisi').append(obj.naslov+'</br>');
$('#zapisi').append(obj.besedilo+'</br>');
$('#zapisi').append(obj.datum+'</br>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});

Unable to access json data retrieved from php page using jquery $.ajax

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']);
}
});

Categories