I am new to JSON and ajax. Basically i am trying to fetch the list of events from mysql database & send them as JSON encoded file back to .ajax() & display those event list from that function. I tried different ways but i dont think that i am on the right track. As a newbie to Ajax and JSON, Sending and receiving data using ajax is a bit confusing but interesting
The JSON obects and arrays are confusing me that i get stunned without knowing how to access the inner elements
$.ajax({
...
...
...
})
.done(function(result)
{
})
Is result
an object or array or string ? should i use JSON.parse()
method here or should i used the result
directly for the processing and display of data?
Here is the input format for my backend php file,
{"data":
{
"dept": "CSE"
}
}
This input is from a drop-down list,
$("#dept_drop_down").on("change", function() {
...
...
})
And the output format from my php file is,
{
"data": {
"status": "success",
"response_code": "202",
"events": {
"1": {
"name": "Help Dexter",
"desc": "Help Dexter to Solve the Puzzle",
"coordinate": "1307",
"dept": "CSE"
},
"2": {
"name": "Code Hunt",
"desc": "Lets hunt the CODE ..!!",
"coordinate": "2145",
"dept": "CSE"
}
}
}
}
Please Help me with the JavaScript code for sending that input format JSON and receiving output format JSON and displaying them using AJAX(format of input & output given above).
Waiting for your help. Thanks in advance...
here is my code ...
$(document).ready(function(){
$("#dept_drop_down").on("change", function(){
var dat = $(document.getElementById("dept")).serializeJSON();
var postdata = JSON.stringify(dat);
$.ajax({
url: "elist.php",
type: "POST",
data: postdata,
datatype: 'application/json',
error: function(xhr,a,b){alert("This is "+xhr.status)},
beforeSend: function(){alert("Sending.......")},
success:function(result){
var obj=result;
d=$.parseJSON(result);
if(obj.data.resopnse_code==202)
{
//object processing .. Here is the place i need help
}
else if(obj.data.response_code==200)
{
//object processing .. Here is the place i need help
}
else if(obj.data.response_code==201)
{
//object processing .. Here is the place i need help
}
else if(obj.data.response_code==400)
{
//object processing .. Here is the place i need help
}
}
});
});
});