Send a post request to a php page using ajax - php

I'm trying to send a text that is typed via ajax to a php page that will make a query using that text that is received. I want to know how to send the value of variable nmClient to the php page. I tried the following code and the return was 500 (Internal Server Error). I'm using the framework Symfony
Jquery
var name = $("#name").val();
$.ajax({
url: "../search",
type: "POST",
data: {'name':name},
dataType: "json"
}).done(function(response) {
console.log(response);
}).fail(function(jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
}).always(function() {
console.log("done");
});
PHP
public function searchAction(Request $resquest)
{
if ($request->isXMLHttpRequest()) {
$name = $request->get('name');
return new JsonResponse(array('name' => $name));
}
return new Response('This is not ajax!', 400);
}

I believe you're trying to access the parameter name in the incorrect place. The get() method is available on the ParameterBag instance, not the Request instance. Try the following:
$name = $request->request->get('name');
Per the docs here:
Each property is a ParameterBag instance (or a sub-class of), which is a data holder class:
request: ParameterBag;
query: ParameterBag;
cookies: ParameterBag;
attributes: ParameterBag;
files: FileBag;
server: ServerBag;
headers: HeaderBag.
All ParameterBag instances have methods to retrieve and update their data:
get() Returns a parameter by name.
Here is the example from that same page:
// the query string is '?foo[bar]=baz'
$request->query->get('foo');
In the docs example case, the parameters are passed via the GET method as a query string but they access them via the query ParameterBag instance. You'll want to use the request Parameter Bag instance since your parameters are passed via the POST method.

Related

How to redirect from one blade view to another blade view, and pass dynamically generated variable to it?

In my view , let's call it View-A, I get an input from user in a prompt and assign it to a variable, and then I need to load in browser another view, say View B, while passing it that variable.
Say, in my viewA.blade.php, I have taken user's input and assigned it to variable usersInput. Now I need to send it to view B, whose route in web.php is defined at Route::get('editRecord', 'MyController#displayEditRecordView')->name('editRecordFormView');.
Question is how do I load route(editRecordFormView) in browser and pass usersInput variable to it, from javascript written in my blade view?
#Tushar In in my ViewA.blade.php:
$.ajax({
url: url_editRecordView.url,
data: {
usersInput: dataToSend.usersInput,
},
method: "get",
cache: false,
success: function (dataReturned, stringStatus, jqXHR) {
console.log("dataReturned from mYController.displayEditRecordFormView:-");
console.log(dataReturned);//check
console.log("Type of dataReturned:-" + typeof dataReturned); //SAME DATA COMES BACK, AS THE DATA I SENT
},
error: function (jqXHR, stringStatus, stringExceptionThrown) {
alert("Error! status: " + stringStatus + " ExceptionThrown: " + stringExceptionThrown);//check
}
});
In my MyController:
public function displayEditRecordFormView (Request $request) {
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
$title= $request->input('usersInput');
error_log("In displayEditRecordFormView: title: ".$title);//check
$allPaintingsArray = $this->getAllPaintingsArraySanitized();
$data = [
"allPaintingsArray"=>$allPaintingsArray ,
"title"=>$title
];
return view("paintings.editRecordForm")->with("allGoodData", $data);
}
Instead of AJAX call why don't use something like this:
var url = "/editRecord?usersInput=dataToSend.usersInput;
window.location.href = url;
catch variable In controller:
$title= request()->filled('usersInput');// or find a way according to Laravel version
You can make use of AJAX. Just set an event handler for when the user gives an input, and send a request containing the user input to a method in your View-A controller via AJAX and from there you can redirect to View-B along with the value that you got from the request.
EDITED
Instead of using view() method try using redirect() method like this:
return redirect()->route('editRecordFormView', ['input' => 'userInput']);
To know more about redirects please refer to this

Use the autocomplete event in the succes of my ajax

I would like to use an autocompletion in my application. I'm trying to use the jquery UI completion but nothing happens. I made an ajax to get all columns with a specific variable written by the user. The query is working, I have my array with all my columns back from the server. With this query reponse, I tried to do the jquery autocompletion in the success ajax but as I said nothing is happening.
Do you have an idea?
function autoCompleteRegate(){
$("#code_regate").keyup(function() {
// AJAX de l'auto-complete
var source = '/gestion/gestDepot/ajaxautocompleteregate';
var codeRegate = $("#code_regate").val();
$.ajax({
type : "POST",
url : source,
async : false,
dataType : 'json',
data : {
'codeRegate' : codeRegate
},
success : function(response) {
var availableTags = response;
$("#code_regate").autocomplete({
source: availableTags
});
}
});
});
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
echo json_encode($response);
}
Network query - form
Exemple of nothing happening
The answer from the server
You have to directly pass the cd_regate array instead of a multidimensional array. One workaround is you could process the json output on the backend side :
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
$json = [];
foreach ($response as $key => $value) {
array_push($json, $value->cd_regate); // the output will be "[774970, 774690, 774700,... ]"
}
echo json_encode($json);
}
I would suggest the following for your JavaScript:
$("#code_regate").autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url : '/gestion/gestDepot/ajaxautocompleteregate',
async : false,
dataType : 'json',
data : {
'codeRegate' : request.term
},
success : function(data) {
response(data);
}
});
}
});
This uses a function as a Source. From the API:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
When 1 or more letters are entered into the text field, this will be passed to the function under request.term and you can POST that to your script via AJAX. When you get the result data, it must be in an Array or an Object with the right format.

AngularJS UI-router pass param from view to state resolve

I am trying to pass params in ui-sref then access it to state resolve.
HTML View
ui-sref="reservation({check_in: check_in, check_out: check_out})"
I am trying to get the params passed in ui-sref to the resolve.
This is some code in my controller when I don't yet use a resolve.
$http.get('server/getFilteredRooms.php', {
params: {
check_in: data.check_in,
check_out: data.check_out
}
}).then(function(res){
Then I tried to implement resolve because I want to wait for the data to get before rendering the view. In that way, I believe, I will not encounter undefined due to data from http function is not yet returned.
JS (app.js)
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
resolve : {
promiseObj : function($http){
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: check_in,
check_out: check_in
}
});
}
}
})
And I am trying to access in my PHP file like this.
PHP
$check_in = $_GET['check_in'];
$check_out = $_GET['check_out'];
To receive those parameters in the state's resolve, at first, you need to declare those in the state's configuration. Change the state's configuration, and introduce a params key as follows:
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
params: {
check_in: null,
check_out: null
},
resolve: ...
Then, modify the resolver as follows:
promiseObj: function($http, $transition$){
var params = $transition$.params();
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: params.check_in,
check_out: params.check_in
}
});
}
This way, your resolver knows that it should extract the parameters' values from the URL and passes those to the HTTP call.

How to pass multiple forms as parameter in laravel?

(1/1) ErrorException
Argument 2 passed to App\Http\Controllers\priceDetails::finalSubmit() must be an instance of Illuminate\Http\Request, none given
Error I'm getting while passing multiple parameters with controller function.
Ajax code:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
$.ajax({
url:"{{url('dbvalue')}}",
type: 'GET',
data: {form1: form1, form2: form2, form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
Laravel route:
Route::get('dbvalue','priceDetails#finalSubmit');
Controller:
public function finalSubmit(Request $priceform,Request $formdescription)
{
$var1 = $this->addPriceDetails($priceform);
$var2 = $this->addProductDetails($formdescription);
$var3 = $this->addAdditionalInformation($additionaldescription);
$var4 = $this->addImages($imagesform);
echo("success");
}
This what I'm trying to give multiple form parameters in laravel controller function.
addPriceDetails fn:
public function addPriceDetails(Request $priceform)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$priceform->input('skuid');
$priceInfo->deviceCategoryId=$priceform->input('dataId');
$id=$priceInfo->id;
$priceInfo->save();
return response()->json([
'SKUID' => $priceInfo->SKUID,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getpriceDetailsId()
]);
}
What you are attempting to do simply does not work. Just because you sent data of two form in your 1 ajax request does not mean laravel will interepret it as two request. That is simply not possible.
What you have done in your code is get get data from 3 forms and make a json object from them and sent that json object in 1 get request. You cannot send multiple request in 1 request. This is as fundamental as it gets.
The best way to get the result you want is to accept 1 request object in you controller and parse it to get data from multiple forms that you sent.
You need to make your function as
public function finalSubmit(Request $request)
{
$var1 = $this->addPriceDetails($request->form1);
$var2 = $this->addProductDetails($request->form2);
$var3 = $this->addAdditionalInformation($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have $imagesform
return response()->json(["response"=>"success"]);
}
Also change http verb from GET to POST
type: 'POST', //in ajax, it is good send bulk data in post not in get
In route
Route::post('/dbvalue','priceDetails#finalSubmit');

$http headers is not a function - angularjs

I am posting data to Dynamics CRM via SOAP on my PHP server with cURL. After this is done it is giving the entity GUID in the form of a HTTP Response header. When attempting to access this via my angular factory and $http.
My header is exposed and is able to be viewed in Chrome Developer tools and gives me the GUID I need.
The code for accessing the promise data is as follows:
$http({
method: 'POST',
url: url,
data: formData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data, headers) {
var array = [];
array.data = data;
array.headers = headers('EntityId');
console.log(array.headers);
deferred.resolve(array);
})
return deferred.promise;
//etc
The error I get is:
headers is not a function()
I can however, access some header result such as a status 200 code by using:
array.headers = headers;
But I need to access my custom header. Any ideas on how I can achieve this?
As per Deprecation Notice on https://docs.angularjs.org/api/ng/service/$http
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
the preferred way would be:
$http.get('/someUrl')
.then(function(response){
var array = [];
array.data = response.data;
array.headers = response.headers('EntityId');
});
As Andy said already, headers is the 3rd parameter of the success callback. So you will have to do this:-
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
})
I wasn't going to add this as an answer but doing this as I wanted to add that headers is indeed a function.
In my project, I did the below and saw function logged out as type in console. The function returns the value of the header item corresponding to the name passed, if no parameters are passed, returns an object containing all headers.
login(user) {
return this.$http.post(this.url, user)
.success((data, status, headers, config) => {
console.log(typeof headers, 'headers'); => prints function
console.log(headers(), 'headers'); => if you don't pass anything, returns an object containing all headers.
return response;
});
}
Excerpt from the angular code.
function headersGetter(headers) {
var headersObj;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
You parameters for success are incorrect. headers is the third parameter.
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Check "Usage" section in https://docs.angularjs.org/api/ng/service/$http for reference.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers –{function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Angular version == 1.3.5 , Suppose header value has been set "X-AUTH-TOKEN = 'eyJwYXNzd29yZCI6ImFkbWlu'" in Application Security class after authentication.
$scope.postData = "{\"username\" : username , \"password\": password ,\"email\" :email}";
$http({
method: 'POST',
url: '/API/authenticate',
data: postData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Login-Ajax-call": 'true'
}
})
.then(function(response) {
if (response.data == 'ok') {
$cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
// below put,put,putObject Cookies value is valid for Angular version >= 1.4
// $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN');
window.location.replace('/');
}
else {
// Error Message...
}
});

Categories