How to use JSON data in your Ajax success - arrays

I send some data using the AJAX request.
On my PHP page I have following code.
$rouid = "";
if (isset($_POST['routeid'])) {
$rouid = $_POST['routeid'];
$array = array('routeid' => $rouid);
echo json_encode($array);
}
I am encoding the data into JSON.
Now I want to send this json back to my original page where I sent data from.
How can I get this $array variable into ajax request success.

var routeid=$('#routeid').val();
$.ajax({
url:"yoururlhere",
type:"post",
data:{routeid: routeid},
dataType:"json",
contentType:"application/json",
success:function(response){
console.log(response);
var ROUTEID=response.routeid;
},error:function(err){
alert("ERROR")
}
});

Related

how i can send post data array angular and get data on api laravel

i have code like it on angular
my array :
[{"kode":"123","nama":"satu dua tiga"},{"kode":"321","nama":"tiga dua satu"}]
$http({
method: 'POST',
url: 'api/insertCustomerArr',
data: myarray
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
and how i can get this data on controller laravel and how i can looping ?
public function insertCustomerArr(Request $request)
{
echo count($request);
exit;
}
this code result count 1, how i can get data?
You can check using
return $request->all();
this will return all the data you posted from angular request
Laravel $request object has a request property inside of it.
So that basically $request->request->all(); should contain all the data that came from angular.

Angularjs: how to properly save a blob pdf file recieved from the server

The recieved file goes through $http and i need to save the response data into a file, i am using angular-file-saver, the recieved files are pdf docx, but viewing the saved pdf file shows nothing on the reader, while other downloaders like PostMan does save it right.
the function that takes care of saving has this code:
function saveFile(data, header){
var extensions = {
"application/pdf": ".pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"
}
var file = new Blob([data], {type: header});
FileSaver.saveAs(file, documentsShow.document.name + extensions[header]);
}
data is the body data retrieved from $http success and header is the Content-Type also recieved from $http response
in case if it's needed, the $http code is like this:
$http({
method: "GET",
data: data, //This is sometimes null but it's not relevant for the application
url: "path/to/download"
}).then(function(data){
saveFile(data.data, data.header("Content-Type"));
});
Main problem I see here is that Angular will still be trying to parse the response as JSON.
You can modify this so it resolves with a Blob object
$http.get('path/to/download', {
responseType: 'blob'
}).then(function(res) {
FileSaver.saveAs(res.data, ...)
});
FYI, data is not used in GET requests.

AngularJs POST request for json not working

Hi i tried POST json data in two ways its response in null
var jsonData = $scope.addedCat;
console.log(jsonData);
var request = $http({
method:"POST",
url:base_url+"Category_controller/json_test",
data: JSON.stringify(jsonData),
dataType: "application/json"
});
request.success(
function(response){
console.log(response);
});
var cat_j = $scope.addedCat;
var data = $.param({ json:JSON.stringify(cat_j)});
$http.post(base_url+"Category_controller/json_test/",data).success(function(data, status) {
console.log(data);
console.log(status);
})
How we decode the json data in php.
I tried like this in Codeignitor framework.
$cjson = $this->input->post('jsonData');
$cat_json = json_decode($cjson);
echo json_encode($cat_json);
On your server php file , try that instead, and you get the parametes passed from client:
//get parameters
$params = json_decode(file_get_contents('php://input'), true); //read values from angular directive
Superglobal $_post only support application/x-www-form-urlencoded and multipart/form-data-encoded.
For application/json you should use php://input which can give you the raw bytes of the data. Here is a sample code of how to get the input data:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
print_r(json_decode($rawData));
$data = json_decode(file_get_contents('php://input'), true);
and do $data['jsonData']
now this $data['jsonData'] === $this->input->post('jsonData');

Angular $http read String?

The back end guy wants to send me a string, which will be returned by $http.post. If he sends me something like "success", I will get error like "parsing Json failed". I want him to wrap the string into object like "{"message": "success"}", which works fine. But other back end guys say that front end should comply with back end, so they will just send me the string. Is there any way that I can read the string?
This is the code I use if he sends me "{"message": "success"}", which works perfectly:
AdminService.saveCache(cache)
.then(function(data) {
var data = data.data;
if (data.message == "success") {
scope.successMessage = "Cache hours saved successfully";
} else {
scope.errorMessage = data.message;
}
}, function() {
scope.errorMessage = "Submission failed";
});
By default angular tries to detect if a http response contains JSON. Sometimes this detection fails and you get such an error as you described in your question.
You can avoid this behavior for a single request if you override the response transformation by providing an transformResponse property for on the configuration object passed to the request:
$http({
url: '...',
method: 'POST',
//Just return original response from server without parsing
transformResponse: [function (data, headers) {
return data;
}];
});
Alternatively you can change the default behavior for all your app's http requests by overriding the default response transformation:
myApp.config('$httpProvider', function($httpProvider) {
$httpProvider.defaults.transformResponse = [function (data, headers) {
return data;
}];
}]);
For more information see API Reference $http section "Transforming Requests and Responses"
the API Response Content-Type should be set to text/plain; and use POSTMAN to verify, it would save you a lot of headache

Example of progress on file upload in AngularJS $http POST

I am trying to get a 'progress' event from AngularJS $http POST request for file upload.
After looking at $http upload file progress in AngularJS, I came across one recent angular.js git commit, that suppose to resolve the issue Add XHR progress event handling to $http and $httpBackend.
Did anyone achieve this working? And if so, can kindly show the example?
PS. I'd prefer to stay with $http rather than create my own XMLHttpRequest. The reason is that my backend expects to get json object combined with multipart file data. And the attempt to make through XMLHttpRequest is failing with error message that backend doesn't see the json object part of request "Required String parameter 'objData' is not present. The request sent by the client was syntactically incorrect." While in the POST message I see "Content-Disposition: form-data; name="objData"" in Firebug.
$scope.uploadFile = function() {
var url = buildUrl('/upload');
var data = {objData: $scope.data, fileData: $scope.file};
var formData = new FormData();
formData.append("objData", angular.toJson(data.objData));
formData.append("fileData", data.fileData);
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type","application/json;charset=utf-8");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(formData);
};
At time of writing $http doesn't support the notify method of the new 1.2 $q. So you have to use jquery xhr. Its rather simple once set up:
Notice that we return a promise so your consumer of uploadFile would do uploadFile(..).then(success, fail, progress)
$scope.uploadFile = function() {
var deferred = $q.defer();
var getProgressListener = function(deferred) {
return function(event) {
//do some magic
deferred.notify(magic);
};
};
var formData = new FormData();
formData.append("objData", angular.toJson(data.objData));
formData.append("fileData", data.fileData);
$.ajax({
type: 'POST',
url: buildUrl('/upload'),
data: formData,
cache: false,
// Force this to be read from FormData
contentType: false,
processData: false,
success: function(response, textStatus, jqXHR) {
deferred.resolve(response);
},
error: function(jqXHR, textStatus, errorThrown) {
deferred.reject(errorThrown);
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener(
'progress', getProgressListener(deferred), false);
} else {
$log.log('Upload progress is not supported.');
}
return myXhr;
}
});
return deferred.promise;
};

Resources