I'm trying to pass data to my laravel controller function via Ajax. At this point I just want to return the data being sent to verify ajax is working. I can "GET" with ajax, but when I try to "POST" ajax brakes.
Could someone please tell me what I'm doing wrong? Thank you.
Here is my ajax code...
var startMapLocation = { startCity: "Cleveland", startStat: "Oh" };
$.ajax({
type: "POST",
url: url,
data: startMapLocation,
success: function(data, status) {
//alert(data);
console.log("success:", data);
},
error: function() {
alert("Ajax Broke!" + status);
}
});
My laravel function is...
public function postphp( Request $request)
{
$a = $request->all();
$city = $a["startCity"];
return json_encode( $city );
}
Thanks every one for your help. To resolve this issue, I first had to verify that my route was a post route not a get route.
Route::post('/postphp', 'GSResultController#postphp');
I also need to get my csrf-token and add it to the ajax call.
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
This fixed my problem.
Related
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.
This is my route
$app->post('/place_c', 'place_c_controller:place_c',
function ($request, $response, $db_connect) {
return $response;
})->setName('place_c');
JavaScript Code
$("#frm_place_c").ajaxForm({
url: "http://localhost/pub/place_c",
dataType: "text",
beforeSubmit: _Request,
success: _Response,
});
function _Request(formData, jqForm, options) {
$(".loader").show();
return true;
}
function _Response(responseText) {
$(".loader").hide();
}
And I am posting data to the controller /place_c through ajax but i am getting 500 internal server error "Method not allowed. Must be one of: POST" However using $app->get works perfectly fine. What i am doing wrong?
The server response data was different than what was expected.
I answered similar question here
Basically, your route specified a POST request. Therefore, in your AJAX request, you might want to add a method attribute to the object, like so:
$("#frm_place_c").ajaxForm({
url: "http://localhost/pub/place_c",
dataType: "text",
beforeSubmit: _Request,
success: _Response,
method: "POST"
});
I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db.
so I have this route:
//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');
which is resolved by this controller
public function postYell($request, $response)
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user'],
]);
return $response->withRedirect($_SERVER['HTTP_REFERER']);
}
I tried something like this:
$(".postYell").submit(function(){
$.ajax(
{
url: "/yell",
type: 'POST',
data: {
"_method": 'POST',
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction
// Make sure you specify a valid callable with two ':'
$app->post('/yell', 'UserController::postYell')->setName('yell');
And then in your controller, don't redirect when it is through XHR:
public function postYell(Request $request, Response $response) : Response
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user']
]);
if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
return $response;
} else {
return $response->withRedirect($request->getHeader('Referer'));
}
}
Then follow up with the configuration in your AJAX request to send the correct data value (jQuery.ajax automatically adds the X-Requested-With: XMLHttpRequest as documented here under "headers")
$('form.postYell').submit(function (e) {
// prevent the page from submitting like normal
e.preventDefault();
$.ajax({
url: '/yell',
type: 'POST',
data: $(this).serialize(),
success: function () {
console.log('it worked!');
},
error: function () {
console.log('it failed!');
}
});
});
As per Slim3 documentation
if ($request->isXhr()) {
return $response;
}
is a great way to ascertain if the request was from a JQuery AJAX call
vote up
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();
I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});