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']);
}
});
Related
I want to pass the response data to another page in ajax success.
I'm using jquery in laravel. I have called the function and get the data from the controller in success call. I want to pass the received data to another page detail
$.ajax({
type: 'get',
url: 'am_detailed_report', //send the request to the controller
data: {
am_geo_selection: am_geo_selection
},
dataType: 'json',
success: function(data) {
console.log(data);
$url = "am_detailed?filter=" + data;
window.open($url, "_blank"); //want to send the parameter in post instead of passing it in url.
$('.loaderImage').hide();
},
error: function(jqXHR, textStatus, errorThrown) {
$('.loaderImage').hide();
}
});
Try this
$.ajax({
type: 'get',
url: 'am_detailed_report', //send the request to the controller
data: {
am_geo_selection: am_geo_selection
},
dataType: 'json',
success: function(data) {
console.log(data);
$url = "am_detailed"
const html = `<form action="${url}" method="post">
<textarea name="filter">${data}</textarea>
</form>`
const w = window.open("", "_blank");
w.document.write(html);
w.document.close();
w.document.querySelector("form").submit()
$('.loaderImage').hide();
},
error: function(jqXHR, textStatus, errorThrown) {
$('.loaderImage').hide();
}
});
I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
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")
}
});
} );
$('#deviceLoadMore') is a link. When this link is being clicked, it will trigger a ajax to the web service I have created.
The problem I'm having now is it keeps on throwing this error in the console.log
Uncaught TypeError: Converting circular structure to JSON. But when I just paste the ajax part in the console.log, it able to retrieve the data back. I have checked that all the value is just a normal string and integer.
I was wondering why i can trigger in console log without having any issue and couldn't if i just click on the link?
var currentContextSection = '<%=currentSection %>';
var currentTemplateIds = '<%=templateIds %>';
var currentItemPerPage = <%=itemPerPage %>;
var currentPageIndex = <%=currentPage %>;
var arguments = { templateIds:'<%=templateIds %>' , currentSection:'<%=templateIds %>', currentPage:currentPageIndex, itemPerPage:currentItemPerPage };
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(arguments),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
------ EDIT -------
If I have this:
var arguments = {"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage};
and executing with the ajax data:JSON.stringify(arguments), i will get the following errror:
Converting circular structure to JSON.
When I console.log the "arguments", it displays:
Object {templateIds: "963C1D18A93849309D6014CE2135173C", currentSection: "Personal", currentPage: 1, itemPerPage: 8}
And it displays this when I console.log JSON.stringify(arguments):
"{"templateIds":"963C1D18A93849309D6014CE2135173C","currentSection":"Personal","currentPage":1,"itemPerPage":8}"
After google around for some successfully implemented ajax sample, I changed my code to the following, and it works! And I have no idea why it works this way.
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage}),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
try after removing, JSON.stringify from
data: JSON.stringify(arguments),
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>');
}
});