Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}
Related
Need to delete a record without using form tag. Just pass a id in url and get a id need to process.
Thanks
follow below steps
HTML
Delete
JS
$('a#btnDelete').on('click',function()
{
var thisElement = $(this);
$.ajax({
type: 'post',
url: "{{url('/')}}" + '/deleteRecord/'+thisElement.attr('thisRecordId'),
data : {'_token': '{!! csrf_token() !!}'},
async: false,
success:function(response)
{
console.log(response)
}
});
});
Route
Route::post('deleteRecord/{id}','YourController#deleteRecord');
Controller
public function deleteRecord($id)
{
$findRecord = ModelName::findOrFail($id);
$findRecord->delete();
return 'success';
}
hope you will find your solution !
Try like this
<a type="button" class="label label-danger" href="/user/delete/{{$user->id}}">Delete</a>
Controller method
public function getDelete($id)
{
echo $id;
}
i am using codigniter .when i am inserting or updating data in mysqldb data is inserting.my form is in popup.then alert is getting but redirecting was not working..issue is redirected is displaying in popup not to page .can you please tell the alternate solution ..i am using ajax update to my form
This is my code of controller
$testid=$this->objTests->updateTest();
echo "<script> alert('sucessfully updated');</script>"
redirect(base_url().'tests');
this is my following code of model:
$testData = array('simulationId' => $this->input- >post('simulationId'),
'testTitle' => $this->input->post('testTitle'),
'description ' => $this->input->post('description')
);
$this->db->where('id',$this->input->post('tid'));
$this->db->update('tests',$testData);
return $this->input->post('tid');
$(function(){
$( "#frmActiontest" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#frmActiontest").serialize(),
type: $(this).attr('method')
}).done(function(data) {
//window.location.href="http://neuronguru.com/MedAdmin/tests/";
window.location.reload();
/*$('#result').html(data);
$('#frmActiontest')[0].reset();*/
});
event.preventDefault();
});
$( ".test" ).on("click",function(event) {
var url = $(this).data('url');
var actionUrl = $(this).data('actionurl');
console.log(actionUrl);
$("#frmActiontest").attr('action',actionUrl);
$.ajax({
url: url,
type: "GET",
dataType: 'json'
}).done(function(data) {
data=data[0];
$("#myModalTestLabel").html("Update Test");
$("#simulationId").val(data.simulationId);
$("#testTitle").val(data.testTitle);
$("#description").val(data.description);
//$("#contents").val(data.contents);
$("#tid").val(data.id);
$("#testModal").trigger("click");
console.log(data);
});
event.preventDefault();
});
});
this is my ajax function for the above question
I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.
Im just trying to send a simple jquery ajax request but always get the response like this:
""ok""< !--" 16.7154s "-->"
Why: < !-- 16.7154s -->?
My js:
jQuery.ajax({
type:"POST",
url: 'controller/action/' + $('#nickname').val() ,
success: function(data) {
alert( data ==='ok' );
}
}); return;
My controller:
function verifynick(){
$this->layout='ajax';
$this->autoRender = false;
return ('ok');
}
Thanks in advance
You just have to put the debug mode at 0.
You can do it on the fly in your action like this
Configure::write('debug', 0);
I'm tryin to validate an input field with an ajax call to a cakephp controller
My Ajax is:
$("#UserAlphaCode").change(function () {
$.ajax({
type: "post",
url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
data: ({code : $(this).val()}),
dataType: "json",
success: function(data){
alert (data);
},
error: function(data){
alert("epic fail");
}
});
});
My controller code
function checkCode() {
Configure::write('debug', 0);
$this->autoRender = false;
$codePassed = $this->params['form']['code'];
$isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
if ($isCodeValid == 0){
$codeResponse = false;
} else {
$codeResponse = true;
}
echo json_encode ($codeResponse);
}
I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?
Try something like:
$codePassed = $_POST['code']
you might also try putting:
$this->log($codePassed,LOG_DEBUG);
somewhere in there and examine the output in tmp/logs/debug.log
Using firebug will help debug the transport.
Don't know why it would be returning null, but I normally use $this->data to fetch form data.
And did you try debug($this->params)? If you don't have a non-AJAX form to test the request from, use Firebug or Wireshark to see what is being return by the server for the debug() call—since it will break jQuery's AJAX handler by not being in JSON.