Codeigniter Ajax request appeared twice in view and database - php

I have created a comment library to handle comments all over my website developed by CI
I am adding comments using ajax so i have came up with practice to have the function located in MY_Controller that handle the ajax
public function comment_add()
{
echo $this->comments->add();
}
and in AJAX Jquery code noting that category is one of controller names as any controller will havethe access to comment_add() found in parent controller
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
and in my Comments library
public function add()
{
$post_id=$this->get_post_id();
$post_type=$this->get_post_type();
if(!$post_id || !$post_type || !$this->user_id)
return false;
$id=$this->ci->comments_model->comment_add($this->user_id,$post_id,$post_type);
if($id)
{
return $this->_markup($id);
}
else
return false;
}
and comments model
function comment_add($user_id,$post_id,$post_type)
{
$data['comment_user_id']=$user_id;
$data['comment_post_type']=$post_type;
$data['comment_post_id']=$post_id;
$data['comment_text']=$this->input->post('comment_new');
$this->db->insert('comments', $data);
if($this->db->affected_rows()>0)
return $this->db->insert_id();
else
return false;
}
Problem is that Comment is inserted twice and as well in database twice, i have been tracin this for hours even with x-Debugg found that he go through echo $this->comments->add(); twice dunno why he would do that, thanks for your help

maybe it was submited twice. Try to unbind submit when you get ajax
success or just alet("something") so you will know if that problem is
javascript or php based.
Replace your submit function with:
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$(this).unbind("submit"); //so you will submit only once
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});

The missing piece here is "snc/category/comment_add" controller ... are you sure you aren't calling from both that controller & also the MY_Controller?
Can you post the controller code as well?

Found out that I have loaded Jquery file twice, that was my bad, thanks guys

Related

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!

Sending variable by ajax in use of laravel

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 :)

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

Pass values into an external js file

Hey I hope someone can help me out,
I have an external js file that resides in the webroot/js folder that I insert into my view using:
echo $this->Html->script('script');
In the js file I have an ajax request to insert data into my database:
var assetData = {
"project_id": $("#projectId").val(),
"asset_id":"??",
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData
});
In my view I created a hidden form field with the project_id so that I can get it in the js file, however the asset items are created dynamically, the are created and saved into the assets table, and now I want to update that asset with the content.
What would be the best way to get the asset? I can't get the id and save it, for example, in the div's id because it was created in the js file.
I would really appreciate any suggestions!
/assets/add should return the ID of the asset it created.
If you're inserting into a mysql database, then one option is to use mysql_insert_id (there are mysqli and pdo equivilents on the manual).
var assetData = {
"project_id": $("#projectId").val(),
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData,
dataType:'text',
success:function (data)
{
assetData['asset_id'] = (int)data;
}
});
And then your /assets/add should echo out the ID after it is created
echo $asset_id; // some INT id
So you may want to consider HTML partials. These are little bits of HTML representing anything from a single tag, to a popup. The important thing is that it does not have the or tag.
$.post('/assets/add', data, function (html) {
$('#assets').append(html);
}, 'html');
After you POST data, your call returns a snippet of HTML. You can then append that HTML to a DIV on the page.
<div id="assets">
<div class="asset" id="asset-1">
<p>Asset content</p>
</div>
</div>
In your controller (I assume it's CakePHP), you have:
if ($this->Asset->save($this->data)) {
$this->autoLayout = false;
$this->render('asset_partial.html');
}
Using the suggestions I received this is how I managed to solve the problem:
javascript file:
$.ajax({
url:'/assets/create',
type:"POST",
data:assetData,
dataType:'text',
success: function (response) {
if (response.success) {
alert("response: "+response);
} else {
//console.log(response.data, response.code);
alert("response: "+response);
}
}
});
Controller:
public function create($id = null) {
if ($this->data != null) {
$this->Asset->save($this->data);
$this->autoRender = false;
echo $this->Asset->id;
}
}

CodeIgniter + jQuery Ajax runs successfully but error callback is called

I have a pretty simple CodeIgniter project that does some simple database work. Currently I have a controller method that deletes an item in the database. In my view, the code uses the jQuery ajax object to reference that controller, then displays either success or failure through its callbacks.
The problem is, although the controller works fine (deletes the item in the DB as expected), the ajax "error" callback is being called, instead of "success".
I'm sure I'm missing something super basic here...
Here is my controller method:
public function delete_note()
{
$this->load->helper('url');
$this->load->model('auth/user', 'User');
$this->load->database();
$note_id = $this->input->post('id');
$this->db->delete('admin_notes', array('id' => $note_id));
$this->db->query();
$this->output->set_status_header('200'); // Attempting to force the issue
}
And here is the code within the view:
$('.delete_note').each(function(){
var current = this;
this.onclick = function(event)
{
var note_id = this.title;
$.ajax({
type: "POST",
url: "/admin/delete_note",
data: { id: note_id },
success: function(data) { alert('I never see this!');},
error: function () { alert('I *always* see this!');}
});
}
});
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
Just because the database logic is working, you may be receiving issues related to something else (cross-browser perhaps?). To see the error, change your error function to be like this:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
I'd like to thank WojtekT for reminding me to check my responses in Firebug. I was actually receiving back a 500 status code for PHP errors. My extraneous $this->db->query(); call needed to be removed.
Everything works great now.
Thanks!

Categories