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!!
Related
Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.
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 :)
I have the following php codeigniter function code which is being called by a jquery ajax function:
$this->load->library('session');
$this->load->helper('url');
$ids = $_POST['i'];
$message = $_POST['m'];
var_dump($message);
var_dump($ids);
$sql = 'update replies set `response` = "'.$message.'" where id IN ('.implode( ',', $ids).')';
echo $sql;
R::exec($sql); // works normally to here
redirect($this->uri->uri_string());
I want to refresh the page after the db insertion of 'message'. however nothing seems to happen. everything works normally including the db insertion. What am I doing wrong?
You can not redirect via AJAX url. Redirect is possible using callback function in
three ways done, fail and always.
Example:
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function(url) { // echo url in "/path/to/file" url
// redirecting here if done
location.href = url;
})
.fail(function(url) { // echo url in "/path/to/file" url
// redirecting here if failed
location.href = url;
})
.always(function(url) { // echo url in "/path/to/file" url
// redirecting here always
location.href = url;
});
On your ajax success use this after showing success message
window.location="path_to redirect";
like for example i am redirecting to member controller
window.location="member";
Hope this helps.
I' m using cms ModX and want to send Ajax request to server using post method. The problem is that the post data of the second, the third and so one requests doesn't change and remains the same as in the first request.
To clarify the situation I provide the following example.
The javascript is the following:
var reqCount = 0;
$(document).ready(function () {
$(window).scroll(function() {
var dataToPost = {'reqCount' :reqCount};
$.ajax({
url: 'http://example.com/ajaxTest',
method: 'POST',
data: dataToPost,
dataType:"json",
success: function(data){
ajaxCountFromServer = data['ajaxCount'];
reqCount=reqCount+1;
}
});
}
}
Also I created resource with address http://example.com/ajaxTest in Modx with the code, running the snippet:
[[getAJAX]]
getAJAX snippet is the following:
<?php
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$reqCount = $_REQUEST['reqCount'];
$json_obj = array("ajaxCount" =>$reqCount);
return json_encode($json_obj);
}
?>
So, after the first scroll reqCount=0, it's passed to server and after the server responses(success callback) ajaxCountFromServer=0 and reqCount=1. There all works well.
However, after the second scroll reqCount=1 and after the server response ajaxCountFromServer=0,but it should be 1.
How to fix it?
The solution is quite simple. In the page customizing of the resource http://example.com/ajaxTest, where snippet getAJAX is called, I just unchecked the checkbox "Cacheable".
The correct way to do it is
[[!getAJAX]]
The snippet is not cached now
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.