Send API data and image but always empty - html

I'm trying to send a user picture to my api with Slim 3, PHP 7 and JQuery 2.1.1
But when I call api in HTML page then I get couple errors in Apache log, it seems that data arguments are empty and I dont know why.
Someone could help?
-------HTML source code api call
function savePicture(){
var fID = $('#edtIDUser').val();
var fPicture = document.getElementById('img').src;
$.ajax({
type:"POST",
cache:false,
url:"index.php/user_picture/",
timeout:3000,
contentType:"application/json; charset=utf-8",
data:{'id_user': fID, 'picture': fPicture},
dataType:"text",
async:false,
error: function (request, error) {
alert("error");
},
success: function (result) {
alert("ok");
}
});
}
AND API
----API source code
$app->post('/user_picture/', function(Request $request, Response $response) {
$params = $request->getParsedBody();
$iduser = $params['id_user'];
$uploadedFile = $request->getUploadedFiles();
$img = $uploadedFile['picture'];
$data = file_get_contents($img);
$escaped = bin2hex($data);
//TO-DO
}
Error #1: Trying to access array offset on value of type null in $params['id_user']
Error #2: Undefined index 'picture'
Error #3: file_get_contents(): Filename cannot be empty

Related

ajax returning json data as undefined

when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.

My Ajax script not work with datatype json

In my codes, i could post data without error. but i cant return data from php file to show in my html tag. If i delete dataType: 'json', it works fine but as you know i cant get data. I get this error while datatype = json
error : {"readyState":4,"responseText":"<head>\n<meta charset=\"UTF-8\">\n</head>\n-1","status":200,"statusText":"parsererror"}
My ajax;
$(document).ready(function(){
// like and unlike click
$(".like, .unlike").click(function(){
var id = this.id; // Getting Button id
var split_id = id.split("_");
var text = split_id[0];
var postid = split_id[1]; // postid
// Finding click type
var type = 0;
if(text == "like"){
type = 1;
}else{
type = 0;
}
// AJAX Request
$.ajax({
url: 'likeunlike.php',
type: 'post',
data: {baslikid:postid,type:type},
dataType: 'json',
success: function(data){
var likes = data['likesonuc'];
$("#sonuc_"+postid).text(likes); // setting likes
if(type == 1){
$("#like_"+postid).css("color","#ffa449");
$("#unlike_"+postid).css("color","lightseagreen");
}
if(type == 0){
$("#unlike_"+postid).css("color","#ffa449");
$("#like_"+postid).css("color","lightseagreen");
}
},
error: function(data){
alert("error : " + JSON.stringify(data));
}
});
});
});
My php file(I didnt share above to avoid confusion. I get int result from $likesonuc)
$likesonuc= $total_likes - $total_unlikes;
echo json_encode($likesonuc);
In your response, you can see that the body you're returning from PHP:
<head>\n<meta charset=\"UTF-8\">\n</head>\n-1
...is not JSON. It looks like you're writing out the head of the HTML somewhere and then the JSON number -1. You need to send just the JSON in your response or it can't be parsed as JSON.

Retrieve data from database and send it to ajax in laravel

I have laravel project and I want to retrieve data from database and send it to ajax function
this is the code of show ($ip) function
public function show($id)
{
$result = DB::table('radcheck')get();
return ( $result);
//
}
this is the code of ajax which is trying to retrieve data from that function but it can not
$('.edit-user').on('click', function() {
var id=$(this).data('id');
$.ajax({
type: 'GET',
url: '/users/' + id,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(hr_request) {
alert(hr_request['username']);
},
error: function(hr_request) {
alert(hr_request['username']);
}
});
});
there is no data can be retrieving, I think I must send data from controller to ajax using json data, but how can I send it as json data and how can I process this json data into ajax function
It is simple .. you can do it like following :
public function show($id)
{
$result = DB::table('radcheck')->get();
return response()->json(['data' => $result]); // here 'data' is key to access $result in ajax response , it is optional.
}
In the ajax response you can console it using console.log(hr_request.data) and check your data result. Additionally , to access property you need to do hr_request.data.property
Hope it helps , Thanks.

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

Send generic JSON data to MVC2 Controller

I have a javascript client that is going to send json-formatted data to a set of MVC2 controllers. The client will format the json, and the controller will have no prior knowledge of how to interpret the json into any model. So, I can't cast the Controller method parameter into a known model type, I just want to grab the generic json and pass it to a factory of some sort.
My ajax call:
function SendObjectAsJSONToServer(object,url,idForResponseHTML) {
// Make a call to the server to process the object
var jsonifiedObject = JSON.stringify(object);
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: jsonifiedObject
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});
}
My MVC Controller:
public ActionResult SaveForm(string obj)
{
// Ok, try saving the object
string rc = PassJSONToSomething(obj.ToString());
string message = "{\"message\":\""+rc+"\",\"foo\":\"bar\"}";
return new ContentResult { Content = message, ContentType = "application/json" };
}
The problem is that obj is always null. Can anyone tell me how I should structure the ajax call and the controller parameter so that I get my json to the server? I'm using MVC2. This may appear to be a duplicate of some SO questions, but in my case I do not know the Model that the json maps to, so I can't use a specific model type in the controller parameter type.
Thanks very much.
Have you tried something like that?
$.ajax({
url: url // set by caller
, dataType: 'json'
, data: {obj :jsonifiedObject}
, contentType: 'application/json; charset=utf-8'
, type: 'GET'
, error: function(data) { alert('error in sendObjectAsJSONToServer:' + data); }
, success: function(data) {
alert(data.message); // Note that data is already parsed into an object
}
});