Sending variable by ajax in use of laravel - php

I am trying to send two variables through ajax into the php script in laravel.
It is actually not clear to me how to move these variables.
Would you mind guys to give me some advice on it? the newComment contains some string, and id is just a number.
var newComment = document.getElementById('newComment').value;
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id},
success:function(){
alert('success');
},
error:function(){
alert('failure');
}
});
});
Here is my route:
Route::any('/editcomment/{id}/{newComment}', 'HomeController#editComment');
And here goes the function in homecontroller:
public function editComment(){
$aaa = Input::all();
return $aaa;
}
I am struggling with this for last 2 days, constantly looking at documentations and tutorials but have no idea how to do this.

You don't need to add the variables to the url for this request. The data you include in your ajax request will be send to the server as a post body.
Try changing the route to Route::any('/editcomment', 'HomeController#editComment');
And use
public function editComment(){
return Input::all();
}
This should display the id and the newComment

you have to change your route file like this :
Route::any('/editcomment', 'HomeController#editComment'); because yo dont need to ajax request parameter to send in route file.
And yes in your controller method editComment change like this:
public function editComment(){
if(Request::ajax()) {
return Input::all();
}
}
We have to check that requested by ajax call.

Try,
$_GET['newComment'] and $_GET['id']. This will work.
Thank you :)

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

Laravel 5.2 return with errors - how to tell which form is submitted

I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!

Pass a variable with JQuery to the Controller - PHP Codeigniter

I am working on a project using PHP Codeigniter. I want to know how can I sent a variable with JQuery to the controller. Below is my code
<script>
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id", {id: id}, function(page_response)
{
$(".modal-body").html(page_response);
});
}
</script>
Here I'm first getting the variable 'id' from function parameter. But when I run this code, it return the string 'id' instead of the actual user id from database. I want to view the user id. Below is my function from the controller..
public function Reset_User_Password()
{
$data['admin_id'] = $this->uri->segment(3);
$this->load->view('admin/user/reset_user_password', $data);
}
Send data by POST method is not append in url as GET method. So you can't get is using $this->uri->segment().
Instead use
$data['admin_id']=$this->input->post('id');
Use
$this->input->post('id');
Don't use $this->uri->segment(3); because you are posting id by post method if you want to use $this->uri->segment(3); then do a minior miodification in your function
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/"+id, function(page_response)
{
$(".modal-body").html(page_response);
});
You can take help with this code. It is working perfectly at my end
function Reset_User_Password(){
var currentpwd= document.getElementById("currentpwd").value;
var newpwd = document.getElementById("newpwd").value;
var cnfrmnewpwd = document.getElementById("cnfrmnewpwd").value;
var url = "<?php echo base_url('user/changepwd'); ?>"
$.ajax({
type:"POST",
data:{currentpwd:currentpwd,newpwd:newpwd,cnfrmnewpwd:cnfrmnewpwd},
url:url,
success:function(data){
if(data){
$('#newsleter').html(data);
}
}
});
}
try below code
you should get that id variable from GET method on the controller.
function Reset_User_Password(id){
$.post("<?=base_url();?>WebAdmin/Reset_User_Password/id="+id
$(".modal-body").html(page_response);
});

Sending json to symfony controller

I need to pass json data to my Symfony Controller. My ajax function looks like this:
var data = '{"firstname":"John"}';
$.ajax({
type: "POST",
url: save_url, //path to controller action
data: {json:data},
success: function(response) {
// Do something
}
});
In my controller, I try to get my data through:
public function createAction(Request $request) {
$data = $this->getRequest()->get('firstname');
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
Just to see if this works, I send $data to be echoed in a template. In Firebug I can see the data being sent and everything seems to work, but $data is empty and nothing is echoed. Where am I doing this wrong?
EDIT: When I check the response in Fireburg console, I see my data there, in place, but it never appears in the template. var_dump($data) tells that $data is null. So, it seems data is being sent but the controller ignores it.
As Marek noticed:
$this->getRequest()
already returns the request object, you're accessing the request property of the request, that doesn't add up. Either try:
$data = $this->request->get('json');
Or use:
$data = $this->getRequest()->get('json');
You can, of course assign the return value of $this->getRequest() to a variable, and call the get method on that var from there on end... anyway, here's my initial answer, it does contain some more tips, and considerations you may find useful:
You should be able to get the data this way, though AJAX requests + echoing in a template? That does sound a bit strange. I don't see you passing the $data variable to a $this->render call anywhere.
This is a copy-paste bit from a controller action in one of my projects. It works just fine there:
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest())
{//check if request is AJAX request, if not redirect
return $this->redirect(
$this->generateUrl('foo_bar_homepage')//changed this, of course
);
}
$id = $this->getRequest()->get('id',false);//works fine
However, I can't begin to grasp why you're doing this:
var data = '{"firstname":"John"}';
Why not simply go for:
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {firstname: 'John'},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
Then, in your controller you're able to:
$this->getRequest()->get('firstname');//it should be John
You could even pass {json:{firstname: 'john'}} as the data param to $.ajax, the only difference in your controller will be, that you have to do this:
$data = $this->getRequest()->get('json');
$firstName = $data['firstname'];
That should work just fine, unless there's somthing you're not telling us :)
RECAP:
This is what I'd write:
public function createAction()
{//no Request param in controller
if (!$this->getRequest()->isXmlHttpRequest())
{//no ajax request, no play...
$this->redirect(
$this->generateUrl('homepage_route')
);
}
$data = $this->getRequest()->get('firstname');
//return json response:
return new Response(json_encode(array('dataReceived' => $data));
//return rendered HTML page:
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
}
Of course, then the JS code should read:
$.ajax({
type: "POST",
url: 'route/to/create'
data: {firstname:'John'},
success: function(response)
{
console.log(response);
}
});
I have tested this, and I see no reason why this shouldn't work. It works just fine for me...
Please note this was #EliasVanOotegem original example but there are some obvious steps missing
in the controller i'm reading a few replies as in "I cannot see how this works as i'm getting null" this is because your not correctly keying your object.
i.e.
var data = { name : 'john' };
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {json : data},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
as you can now see accessing the requerst object like
$request->get('json');
refers to the post key for the json data
Is the content what you're trying to retrieve, neither params nor headers.
Try:
$request->getContent();
In your case $request->request->get('json') should do.

CodeIgniter AJAX: POST not working, GET works fine

Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!

Categories