I´m trying to use ng-submit to update/create new posts in database. I use this HTML.
<form ng-submit="savePost()">
<input ng-model="post.TASK">
<input ng-model="post.STATUS"">
<button type="submit"></button>
</form>
When submit, he return to controller who has this function. I use console.log(scope.post.task) to show if value update works, and it works but don´t know how insert multiples values in service.
$scope.savePost = function() {
console.log($scope.post.TASK);
//I send here ID but not sure if I can send multiples values
PostAPI.update($routeParams.id).success(function(data, status, headers, config) {
$scope.post = data;
});
}
})
I only get a ID to update.
this.update = function(data) {
return $http.put("ajax/updatePost.php?postID=" + data);
}
And this is is php file.
$conexion = new PDO("mysql:host=localhost;dbname=angularcode_task;charset=utf8", "root", "");
$postID = $_GET['postID'];
//WE NEED TASK AND STATUS HERE
$sql=$conexion->query("UPDATE tasks SET task='Buuu', status=2 WHERE id='$postID'");
$json = json_encode($sql->execute());
echo $json;
In a put request you must especify the data to update your resource, if you need to send the resource id, it could be sent by url or in the same recipe you send the data.
According to Angularjs docs for $http.put, you should be able to do such thing by sending an adition parameter to be the data sent for the PUT request like the below code:
$http.put(url, data, [config]); // config is optional
For Example, PostAPI should receive the post as parameter too:
// controller
PostAPI.update($routeParams.id, $scope.post).then ...
// PostApiService
this.update = function (postId, data) {
return $http.put("ajax/updatePost.php?postID=" + postId, data);
Also, if you had the post id inside the post object, you wouldn't need the postId param, only the post object and then you catch it inside the update method to build your url.
Related
I am creating a comment system where user can comment each post, when user click comment button popup box will appear with multiple field, form is posted to db from jquery, i have a problem that i can't store post_id and user auth id to db through jquery formData method
#foreach($customerposts as $customerpost)
<button type="button" class="btn btn-info" data-toggle="modal" data-
target="#maskup-{{$customerpost->id}}" style="float:right; margin-
top:50px;" id="bidnow" value="{{$customerpost->id}}">Comment
Now</button>
#include('forms.commentform')
#endforeach
comment form
created form field
display correct post id and user id here
passed through hidden field also it doesn't work
</form>
>jquery
$( 'form' ).submit(function ( e ) {
var data;
data = new FormData();
data.append('message', $("#message").val());
data.append('hidden', $("#hidden").val()); can't get this value from
controller
// console.log(data);
alert(data);
$.ajax({
url: 'api/comment/',
data: data,
processData: false,
contentType: false,
type: 'POST',
});
i want to post post_id and user id dynamically for each post
my controller
public function Bidpost(Request $request)
{
$validator = \Validator::make($request->all(), [`enter code here`
'message'=>'required'
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
$bidon = new ContributerBidOn();
$bidon->user_id = '5'; //can;t het user id from hidden field
$bidon->post_id = '8';
$bidon->Guarantee_Of_Product = $request['message'];
$bidon->save();
return response()->json(['success'=>'Data is successfully added']);
}
}
Route api
Route::post('/bidon/','BidController#Bidpost');
It is a bit difficult to understand what you wanted to do here. But I guess you are unable to send post id and authenticated user id in ajax.
My suggestion will be while you click for the comment you can get the post id from the button as you have the id present in button value="{{$customerpost->id}}" value by
add btnForComments class to your button inside for loop and remove the id attribute
$(".btnForComments").click( function() {
var postId = $(this).val();
});
Remove id bidnow from the button in your for a loop. As id should be unique inside DOM.
For authenticated user-id you do not have to send it or keep it hidden inputs in ajax as you can get it from Session in your Controller directly.
Else you can assign the id to a javascript variable and pass it in ajax. The authenticated use id will be the same for all comments though.
I can't download my XLS file via Ajax
function downloadFile(response) {
var blob = new Blob([response], {type: 'application/vnd.ms-excel'})
var url = URL.createObjectURL(blob);
location.assign(url);
}
$('#export').click(function () {
$.ajax({
type: 'POST',
url : 'factures/engagements/selected/export',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
dataType: "json",
data : {
checkboxes : checkboxValues
}
}).done(downloadFile);
});
my controller :
public function exportFacturesEngagementSelected(Request $request){
$checkboxes = $request->input('checkboxes');
$collection = collect($checkboxes);
$engagements = EngagementOrder::whereIn('id' , $collection)->get();
$date = Carbon::now('Europe/Paris')->format('d-m-Y H:i:s');
$output = Excel::create('factures_engagements' . $date. '', function($excel) use ($engagements) {
$excel->sheet('Excel', function($sheet) use ($engagements) {
$sheet->loadView('engagements.exportExcelSelected')->with("engagements", $engagements);
});
})->export('xls');
return $output;
}
I only get the output preview of the file in my console network, but nothing happens in my browser; no file is downloaded. What am I doing wrong?
UPDATE #matticustard solution :
my checkboxValues is a json for exemple the result is
{920: "920", 927: "927", 931: "931", 939: "939"}
when i console log query i get :
undefinedcheckboxes=920&checkboxes=927&checkboxes=931&checkboxes=939&
When i try to get the values to my controller i made a $request->all() and i get :
array:2 [
"undefinedcheckboxes" => "920"
"checkboxes" => "939"
]
why i get undefinedcheckboxes and why i don't get the other ids ?
Try this
if your ajax success
location.href = path/to/file/property_title.xls
change this line
->export($type);
with
->store($type, 'public/reports/', true);
These days I've used this package
(my recommendation) for converting my model's collections to XLS and export that.
As I understand, you want to download the file via AJAX. I didn't got you at all, but I just can share my experience for helping you. This working with a normal POST request, but it will not refresh your page anyway.
So this is a working example:
In Controller
public function export(Request $request)
{
$data = $request->get('data'); // get incoming data field
return \Excel::download(new ExcelService($data), "custom-file-name-with-extension.xls");
}
In Service (or you can implement this in controller too)
namespace App\Services;
use App\Models\Item;
use Maatwebsite\Excel\Concerns\FromCollection;
class ExcelService implements FromCollection
{
protected $data = null;
public function __construct($data)
{
$this->data = $data;
}
public function collection()
{
$items = Item::where('data', $data)->get(); // some query using incoming $data
return $items;
}
}
Route
Route::post('export', 'ItemController#export')->name('export');
There's really no reason to use AJAX or store the file. You can pass the checkbox data as parameters in the URL with a GET request and use an <iframe> to download the file. I guessed at the controller name, so adjust as necessary.
web.php
Change the route to GET.
Route::get('factures/engagements/selected/export', 'FactureController#exportFacturesEngagementSelected')->name('export');
JavaScript function and handler
Serialize the data as expected by your controller and make the request.
I guessed that checkboxValues was an array of values based on the actions taken in your controller. But you could serialize the form directly var query = $('form').serialize(); and adjust the controller to match the input.
function downloadFile() {
var query;
$.each(checkboxValues, function(index,value) {
query += 'checkboxes=' + value + '&';
});
$('<iframe />')
.attr('src', '/factures/engagements/selected/export?' + query)
.hide()
.appendTo('body');
}
$('#export').click(function () {
downloadFile();
});
FactureController.php
And use the download method in your controller.
// ...
->download('xls');
I have a link when pressed it requests a page from a controller via render ajax, Previously i used to pass only the id but now i would like to pass an extra parameter to the controller, how do i achieve this,
This is what i have tried
This is the link' which only passes a single parameter to the controller
Html::a('click me', ['#'],
['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed
'id' => 'perform']);
This is the controller code expecting 2 parameters:
public function actionChecktruck($id,$category) //it expects 2 parameters from above link
{
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
This is my jquery code of another button that depends on the above controller during post request
$("#postbutn").click(function(e) {
$.post("checktruck?id="+truckid, //here i would like to pass 2 params
{checked:checked,unchecked:unchecked,truckid:truckid}
)
}
This is the jquery code when there is no post
How can i pass an extra parameter in the link or even the $.post request for the controller
First of all, as you are using JQuery ajax to submit the form, there is no need to set value for the link
Html::a('click me', ['#'],['id' => 'perform']);
using this id you can submit the request as follows
$this->registerJs("$('#perform').click(function(event){
event.preventDefault(); // to avoid default click event of anchor tag
$.ajax({
url: '".yii\helpers\Url::to(["your url here","id"=>$id,"param2"=>param2])."',
success: function (data) {
// you response here
},
});
});");
There is no need to mention method attribute as 'POST', you want to send through GET method
And finally in your controller, you need to accept parameters as follows
public function actionChecktruck() //it expects 2 parameters from above link
{
$id = Yii::$app->request->queryParams['id'];
$param2 = Yii::$app->request->queryParams['param2'];
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
Try this one,
In View file
$this->registerJs("$('#postbutn').click(function(){
$.ajax({
url: '".yii\helpers\Url::to(["u r URL"])."',
method: 'POST',
data: {id:id, truckid:truckid },
success: function (data) {
},
});
});");
I have a problem with a Symfony Form which I want to prefill based on which record is viewed beforehand. The intention is to create a means for changing the record data.
I navigate to the form page via javascript and send an ajax request to the same controller the form is rendered by.
This is part of the page used for viewing records:
<input type="button" id="changeRecord" value="change"/>
record id: <div id="recordID"> {{ record_id }} </div>
I access the record id through javascript/jQuery like this:
var CssSelectors = new Array(
"recordID"
);
function getCurrentRecordID() {
return parseInt($.trim($("#" + CssSelectors[0]).text()));
};
The button-code in javascript is the following:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute));
$.ajax({
url: Routing.generate(recordChangeAjaxRoute),
type: "POST",
data: {'recordID': getCurrentRecordID()}
});
// both Routes point to the same controller
// problem located here ???
The Symfony Controller Action is the following:
public function changePlasmidRecordAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$recordHandle = $em->getRepository('DataBundle:RecordClass');
$AjaxRequest = Request::createFromGlobals();
$RecordID = $AjaxRequest->request->get('recordID');
$recordToUpdate = $recordHandle->findOneBy(array('id' => $RecordID));
$updateForm = $this->createForm(new RecordClassType(), $recordToUpdate);
$updateForm->handleRequest($request);
if ($updateForm->isValid()) {
$em->flush();
return this->redirect($this->generateUrl('route_showRecord'));
} else {
return $this->render('DataBundle:RecordClass:updateRecord.html. twig',
array(
'RecordID' => $RecordID,
'form' => $updateForm->createView()
));
}
}
What I am trying to achieve is:
view a record
go to prefilled form
make changes and save
Viewing records, creating the form, persisting the changes to the database - all work. What does not work is accessing the needed ID inside the controller.
I can access the ajax request data the way I try in an other controller action without problems.
How is the "Form Request" interfering? Or is it?
Do I have to use an Event Listener?
Any help is greatly appreciated, thanks in advance!
I fixed it by leaving the ajax stuff away and submitting the required data via GET. Like so:
$('#changeRecord').click(function () {
window.location.replace(Routing.generate(recordChangeRoute, {'recordID': getCurrentRecordID()}));
});
Thank you for your input, all the best.
hy,i am working on a wordpress plugin in which i require to delete multiple items using checkbox.when i check all rows and delete them i get their row id in the form of json string.
js code:
$('.check_it:checked').each(function (i){
c[i]=$(this).val();
});
var chk = JSON.stringify({ list: c });
debugger
$.ajax({
type:"POST",
data: chk,
url:'/word/wp-content/plugins/craiglist/action.php?action=delete_leads',
dataType: "json",
success:function(response){
alert('fdsfsfdsfd');
},
failure:function (response) {
alert("Please Try Again");
},
error:function (xhr, status, error) {
alert(xhr.response);
}
});
In var chk i got string like
"{"list":["151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166","167","168","169","170","171","172","173","174","175"]}"
how can i get it at server side in php and send it to database so i can delete the so called rows.
Because you are sending JSON as the post data, you will have to access the raw post data on the PHP side. This can be done like so:
$obj = json_decode($HTTP_RAW_POST_DATA);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
If you want the data in a $_POST variable, then you will have to change your ajax request data to something like:
$.ajax({
....
data: { list : JSON.stringify(c) },
....
Now, on the PHP side it is present in $_POST['list']. So you can do:
$obj = json_decode($_POST['list']);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
In your server side php since you're not calling the get_header() function, you have to add this piece of code manually require_once('../../../wp-load.php'); and you can now call global $wpdb; safely and all wp functions. Please also take note that you're php file must be inside your theme together with your functions.php and other core files. Do not put it into another directory inside your theme