Ajax post request is received as empty object - php

I send an ajax post request , and get a response, but it comes up empty. Is there is some details that need to be adjusted?
The idea is to send text that is submitted with a submit button. But just for testing, I have specified the data to be sent as "url": "helllo".
$(document).ready(function() {
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var submitted = $(this),
destination = submitted.attr('action'),
method = submitted.attr('method'),
url_send = {
"url": "helllo"
};
$.ajax({
type: method,
contentType : 'application/json',
url: destination,
data: url_send,
success: function(response){
console.log(response);
},
error: function(){
console.log("there was an error");
}
});
The "method" (post) and "destination" is specified in the form. So "url_send" is the object which is sent. Should this be retrieved as {"url": "helllo"} on the other end, or is it nested inside an object?
In PHP with laravel,I have a controller function where the request is recieved:
$data = json_decode(file_get_contents("php://input"));
If $data is empty, it's returned:
return Response::json($data);
And that gives me
Object { }

You are passing data an object, so it will be urlencoded by jQuery.
urlencoded data is not JSON, so trying to parse it as JSON will fail.
You need to actually send JSON.
data: JSON.stringify(url_send)

Related

Ajax variable ignores line breaks

I´ve got a problem when I try to send the value of a textarea through Ajax in Joomla.
The variable looks correct right before the ajax request. But when returned from helper.php, the success response var ignores all the line breaks.
My jQuery / Ajax:
var curBody = jQuery(this).closest("div").children("div").children('textarea').val();
//var curBody = curBodyVal;//.replace("/\r\n/","<br>");
console.log(curBody);
jQuery.ajax({
url: "index.php?option=com_ajax&module=usernotes&method=edit&format=json&Id="+edit_id+"&body="+curBody,
success: function( response ) {
console.log(response);
}
});
In my helper.php file at the function for the ajax call:
public static function editAjax()
{
$input = JFactory::getApplication()->input;
//$bodyToUpdate = $input->get("body", 'default_value', 'raw');
$bodyToUpdate = $_GET['body'];
return($bodyToUpdate);
}
Whenever you are trying to send values, which are not simple strings, send it ina a POST method instead of GET,
GET is used for simple strings, only used for characters within ASCII character range.
POST is used for any other complicated strings, you can send binary data as well, for example you can send files and images using POST method, but you cannot send using GET method
Change your ajax to this:
$.ajax({
method: "POST",
url: "index.php",
data: { option: "com_ajax", module: "usernotes" , method: "edit", format: "json" , Id: edit_id, body: curBody },
success: function( response ) {
console.log(response);
}
});

json_decode in Symfony controller returns array of length 0

I'm relatively new to Symfony, and I think my problem is in my controller, but cannot see it. I'm sending valid JSON via ajax request to my controller. When attempting to decode it, the resulting array is of length 0, like my JSON isn't being decoded properly or maybe returned by getContents() properly?
js/ajax:
$('#aggregate').on('click',function(){
var sorted = [];
$('.sortable-items').each(function(){
sorted.push(JSON.stringify($(this).sortable('toArray')));
});
console.log(sorted);
$.ajax({
url: '/documentwarehouse/items/aggregate',
type: "POST",
contentType : 'application/json',
data: {"sorted": sorted},
success: function (data){
alert(data);
}, error: function(data){
alert("Sorry");
}
});
});
example JSON stored in var sorted, and validated via JSONlint:
["[\"list1_23\",\"list1_24\",\"list1_16\",\"list1_17\",\"list1_19\"]", "[\"list2_22\"]", "[\"list4_21\"]"]
So, what gets sent as the json data via ajax, also validated, is:
{"sorted":[" . [\"list1_23\",\"list1_24\",\"list1_16\",\"list1_17\",\"list1_19\"]", "[\"list2_22\"]", "[\"list4_21\"]"]}
controller:
public function aggregateAction(Request $request){
$arrayOfListArrays = json_decode($request->getContent(),true);
$response = new JsonResponse([sizeof($arrayOfListArrays)]);
$response->send();
return $response;
}
The response alerted in the success block of my ajax call is 0.

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Laravel 5 access to ajax Post Data

I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault(); // Disable normal behaviour of the element (Form)
var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}
console.log(formData); // Log to the console the Input data
$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
Route:
Route::post ('user/save', 'CustomerController#createNewCustomer');
Controller:
public function createNewCustomer (Request $request)
{
$inputArray = $request->all();
print_r ($inputArray['form']);
// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response
return response ()->json ($response);
}
In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}
I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?
The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.
You can access like this
$request['name of field'];
i think you need to receive the data in the controller as json:
$request->json('field_of_interest')
The problem is your formData variable. Instead of:
var formData = {
form: $("#newCustomerForm").serialize()
}
it should be
var formData=$("#newCustomerForm").serialize();

ajax request once sent on mouseover, response recieved, but should not be sent again when i mouseover on the html element again

i am sending an ajax request on a mouse over event and I am receiving the desired response.
But when i send again hover on the element whose request was sent, the request is sent again.
i do not want to send the request again, rather i want the page to use the response previously received.
Who to do it?? here is a sample code. - > this function is being called on mouse over, do not want to send request again on the same mouse over element.
function showImage(val)
{
$("#DIV").html('<IMAGESOURCE="../adsd/ajax_loader.gif">');
$.ajax({
type : "get",
cache : false,
url : "blabla.php?imgID="+val,
data : $(this).serializeArray(),
success: function(data) {
document.getElementById("DIV").innerHTML = data;
}
});
};
Set a variable to a value when the response is received and check for that variable before send ing the request.
var response = false;
function showImage(val)
{
$("#DIV").html('');
if (response == false) {
$.ajax({
type : "get",
cache : false,
url : "blabla.php?imgID=" + val,
data : $(this).serializeArray(),
success: function(data)
{
document.getElementById("DIV").innerHTML = data;
response = true;
}
});
} else {
// What to do if the request was sent before
}
};
What I think is you need to use jQuery.data() on mouseover do
if(!jQuery.data(dom, 'sent')){
//take action
jQuery.data(dom, 'sent', true);// do it on success
}

Categories