POST Nested Json to API With Jquery Ajax & Get Response With PHP - php

I want to Post a Json string or PHP array to a Restful API and get the response without reloading the page. So, I want to use Ajax and/or jquery. So far, I'm failing miserably. my code is below.
I've tried several jquery methods - some using stringify and others just sending raw json. I'm not getting enough response or error of any kind to know where I need to look to solve the problem.
$(".avm_zip").on("click", function() {
$.ajax({
url: "REMOVED",
type: "POST",
data: {
"Header": {
"UserId": "REMOVED",
"Password": "REMOVED",
"SourceApplication": "Dev Service Tester"
},
"Property": {
"StreetAddress": "10345 W Briar Oaks Dr # E",
"City": "Stanton",
"State": "CA",
"Zip": "90680",
"APN": null,
"PropertyType": null
},
"Order": {
"CustomerOrderReference": "Test LITE",
"PreferenceTableName": "VeroLITE TEST",
"Price": null,
"Credit": null,
"AdditionalFields": null
}
},
dataType:'json',
success: function (response) {
alert("Success");
},
error: function(error){
alert("Something went wrong");
},
});
The API is more robust and centered on XML. Getting the basic call & retrieval set up using Json had challenges because of this. So, it is possible that is bleeding over into this effort.

Related

am chart pie chart not reading json file data?

when we pass static list of data like [{category":"a","data:"3"},"category":"b","data":"1"}]
then its working fine, but when we pass page url like {"url": "abc.php","format": "json"} in dataprovider section then chart not populate.
This is my code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider":{ "
url": "abc.php",
"format": "json" },
"labelRadius": -35,
"labelText": "[[percents]]%",
"titleField": "category",
"valueField": "column-1",
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"align": "center",
"markerType": "circle" }
});
Any solution?
Using amCharts with "static" data
If you have "static" data, use the dataProvider setting, like this:
var chart = AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataProvider": [{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}],
// ...
});
Using amCharts with AJAX data
If you want the data to be loaded using AJAX, one way is to make use of amCharts' Data Loader plugin.
Make sure to include it in your HTML:
<script src="amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script>
Leave out the dataProvider setting, and use dataLoader instead.
var chart = AmCharts.makeChart( "chartdiv", {
"type": "pie",
"dataLoader": {
"url": "abc.php",
"format": "json"
},
// ...
});
Your abc.php file should return valid JSON, like this:
[{
"category": "a",
"data": 3
}, {
"category": "b",
"data": 1
}]
You can find a complete list of options for the Data Loader plugin here: https://www.amcharts.com/kbase/using-data-loader-plugin/.

Custom Guzzle serialization

I would like to have a custom serialization in Guzzle.
I'm setting a POST application/json request, but my object is serialized with its name (professionalSession) at the beginning, i.e.:
{
professionalSession :
{
param1 : "asdf",
param2 : "jkl;",
...
}
}
That is inconsistent with the REST API I'm trying to call. (className is hidden as one of the parameters).
This is my definition in serviceDescription.json:
"PostAuthentication": {
"httpMethod": "POST",
"uri": "/xxx-person-service/session",
"summary": "Posts the session object",
"type": "json",
"responseClass": "XXX\\WebServicesClientBundle\\Entity\\ProfessionalSession",
"parameters":{
"session": {
"location": "json",
"required": true
},
"session-identifier": {
"location": "header",
"required": true,
"sentAs": "HTTP_X_SESSION_KEY"
}
}
}
I would like to use serviceDescription.json and only override its 1 parameter (by produce json myself).
I tried changing the location of param to body (as it was said in SO somewhere), but Content-Type is not being properly set to application/json.
How can I do it? Thanks!
I will reply as there are no responses yet and I've overcame this problem.
Changing the location of param to body was good approach as it removes that top level JSON element. (This was signaled as a problem, but still - this is how Guzzle behaves.)
To change request to application/json you can use following description in serviceDescription.json:
"PostAuthentication": {
"httpMethod": "POST",
"uri": "/xxx-person-service/session",
"summary": "Posts the session object",
"responseClass": "XXX\\WebServicesClientBundle\\Entity\\ProfessionalSession",
"parameters":{
"session": {
"location": "body",
"required": true
},
"session-identifier": {
"location": "header",
"required": true,
"sentAs": "HTTP_X_SESSION_KEY"
},
//THIS is what you need:
"content-type": {
"location": "header",
"static": true,
"required" : true,
"default" : "application/json",
"sentAs" : "Content-Type"
}
}
},

getJSON not working correctly with codeigniter

I am trying to implement AJAX call method into my website using codeigniter, the reason why i want to use AJAX so i can get live updates from the database
The click button works and displays all of the JSON data but the issue is when i try and display a specific array it does not recognize it, it seems to be iterating through every single character.
Also another wierd thing is when the alert is being called i can see the html and head tags I want to be able to print specific arrays for example the array id"
Things i have done to try and work it out
i have alerted the datatype and found out it was a string
i have managed to get ajax to work in regular PHP rather then codeigniter so their is nothing wrong with the database
I have also tried to use jQuery.parseJSON so i can force it to be json but then the script did not run
I used JSONlint and apprently its a valid JSON
Any help would be appreciated
Consolelog
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXpGbk1wkkaPiv_qkBevxAP9s4kk0oiiU&sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]
Controller
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
echo json_encode($arrays);
}
View
<script type='text/javascript' language='javascript'>
$('#getdata').click(function (data) {
$.ajax({
url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
type: 'POST',
cache: 'false',
datatype: 'json'
}).done(function (data) {
alert(data);
});
});
</script>
json_encode
[
[
{
"id": "1",
"postcode": "NW6",
"imgurl": "hello.jpeg",
"from_user": "henny",
"created_at": "2013-03-18 23:03:00"
},
{
"id": "2",
"postcode": "NW2",
"imgurl": "test.jpeg",
"from_user": "belly",
"created_at": "2013-03-15 23:03:00"
}
]
]
You need to send the correct response headers back (application/json) from your controller function.
Try changing your controller to the following:
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arrays = array($queryresults);
$this->output->set_content_type('application/json')
->set_output(json_encode($arrays));
}

Returned JSON is seemingly mixed up when using jQuery Ajax

I've a php script that has the following line:
echo json_encode(array('success'=>'true','userid'=>$userid, 'data' => $array));
It returns the following:
{
"success": "true",
"userid": "1",
"data": [
{
"id": "1",
"name": "Trigger",
"image": "",
"subtitle": "",
"description": "",
"range1": null,
"range2": null,
"range3": null
},
{
"id": "2",
"name": "DWS",
"image": "",
"subtitle": "",
"description": "",
"range1": null,
"range2": null,
"range3": null
}
]
}
But when I call a jQuery ajax as below:
$.ajax({
type: 'POST',
url: 'url',
crossDomain: true,
data: {name: name},
success: function(success, userid, data) {
if (success = true) {
document.write(userid);
document.write(success);
}
}
});
The userid is 'success'. The actual success one works, its true.
Is this malformed data being returned? Or is it simply my code?
Thanks in advance,
Niall
The arguments the success callback takes are defined in the documentation:
success(data, textStatus, jqXHR)
The response is not split up before being passed as arguments to it. You have to extract the values from the first argument.
You also need to add header('Content-Type: application/json') to your PHP so that jQuery will parse the response as JSON instead of as HTML when populating the first argument.
You can then test data.success and access data.userid (as well as data.data which will be the array assigned to the data property in the returned data… you might want to rename it to avoid confusion).
Note that when you test it you need to use === (or ==), not the * assignment* operator you are using at present. Also note that your JSON response is returning the string "true" and not the boolean true.
You can't add your own arguments in Success. Change your code like this,
success: function(response) {
if (response.success == true) {
document.write(response.userid);
document.write(response.success);
}
}
According to jQuery Docs for success(),
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.
http://api.jquery.com/jQuery.ajax/

jquery php mysql and json returning looped data

I havent tried this before and my solution hasnt worked.
In mysql I would be able to write it using a while loop but im trying to pull the data through ajax.
Can someone help
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
$('#'+continent).append('<li>'+data[0].country+' '+data[0].company+'</li>');
}, "json");
The above returns in console.log's ajax response the following
[{
"continent": "Europe",
"country": "Spain",
"company": "Universidade de Vigo CITI",
"comments": "We are very satisfied with the disrupter. It's equipment is very easy to use and effective in breaking cells. I also would like to thank Constant System for for the assistance provided."
}, {
"continent": "Europe",
"country": "Spain",
"company": "IPLA",
"comments": "The Constant Systems cell disruptor has made extraction of membrane proteins from Gram positives a reproducible and efficient task in our lab."
}]
How can I get this to display as an li list on my page?
Thanks in advance
EDIT
$("#comments-tabs div.country a").click(function(e){
e.preventDefault();
var continent = $(this).parent().attr("id");
var country = $(this).attr("name");
console.log(continent+country);
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
for(company_nr in data){
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}, "json");
});
Just loop it in javascript:
function (data)
{
for(company_nr in data)
{
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}

Categories