Problem not restarting the function keydown in ajax - ajax

I use Ajax to update my data in database,when I Enter input this function is Called
my code is here:
<input type="hidden" value="{{$cart->id}}" id="cartId">
<input type="text" class="input" value="{{$cart->count}}" id="changeCount">
$("#changeCount").keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
var cartId = $(this).parent().children('#cartId').val();
var count = $('#changeCount').val();
clearTimeout(timer);
timer = setTimeout(function() {
$.ajax({
url: '/changeCount',
type: 'post',
dataType: 'json',
data: {
cartId: cartId,
count: count,
_token: $('input[name=_token]').val()
}
})
.then(function (response) {
document.getElementById("carts").innerHTML
=response.html;
})
},250)
}
})
My Problem, is here that when I want to update count for second I get this Error:
How I can solved this Error?

I solved,My problem with use this code:
.then(function (response) {
$('div[id=carts]').html(response.html)})

Related

ajax post is returning null at the actionmethod

I am trying to retrieve the array of integers by posting it from ajax post as:
function myFunction() {
var items = [];
for(var i = 0; i<7;i++)
{
items[i]= i;
}
SubmitForm(items);
}
function SubmitForm(obj) {
$.ajax({
url: "/Home/Index",
method: "POST",
data: obj,
success: function (data) {
alert(data);
}
,
error: function (err) {
console.log(err);
}
})
}
<input type="submit" value="Submit" class="btn" onclick="myFunction();" />
My controller is as:
Public JsonResult Index(int[] arr)
{
return View();
}
I have tried it with every parameter type but it still wont bind values to my action parameter. Do anyone knows what i am doing wrong?
Try the following. You should try and pass the array as a JSON
function SubmitForm(obj) {
$.ajax({
url: "/Home/Index",
type: "POST",
data: JSON.stringify({"arr": obj}),
contentType: 'Application/json',
success: function (data) {
alert(data);
}
,
error: function (err) {
console.log(err);
}
})
}

How does Codeigniter receive the ajax post data in controller without input type text and input post

Here's code for Controller :
public function Update()
{
$id_form = $this->input->post('id_form');
$no_request = $this->input->post('no_request');
$data = {
"no_request" => $no_request,
"date_ps" => date('d M Y')
}
return $this->db->where('id_form', $id_form);
return $this->db->update('table', $data);
}
Here's code for View :
<input type="hidden" name="id_form" id="id_form"></br>
<input type="text" name"no_request" id="no_request"></br>
Edit
Here's code for Ajax :
$('#btn_update').on('click', function() {
var id_form = $('#id_form').val();
var no_request = $('#no_request').val();
var date_ps = $(date_ps).val();
$.ajax({
type: "POST",
url: "<?= site_url('Controller/Update') ?>",
dataType: "JSON",
data: {
id_form: id_form,
no_request: no_request,
date_ps: date_ps
},
success: function(data) {
console.log(date_ps);
}
})
}
But The result for date_ps is undefined, How can I get the date_ps value without having to undefined

How to load data from database using autocomplete?

Here is my jQuery:
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response($data);
}
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());
here is my HTML,
<input type="text" id="user_role" name="user_role">
Here is my controller,
function search_username() {
$keyword=$this->input->get('term');
$this->load->model('chat_model');
$data=$this->chat_model->GetRow($keyword);
echo json_encode($data);
}
Here is my model
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
What I my trying to do is to load data form database using ajax but it's response is no properties but data is already there in table, please anyone help me for get rid of this.
First of all check this function it will return result or not
public function GetRow($keyword) {
$this->db->like('user_type', $keyword, 'both');
return $this->db->get('lc_user_types')->result_array();
}
If it returning change the function
$(function() {
$( "#user_role" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search_username",
dataType: "json",
data: request,
success: function(data){
response($.map(data, function (value, key) {
return {
id:key,
label: value,
value: value
};
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
//Do something extra on select... Perhaps add user id to hidden input
},
});
}());

why can't my typo3 6.2 ajax action be found?

I am trying to hit an ajax action "ajaxfactsAction()" in my controller Factoids. But when the ajax call is made I get a 303 error and a redirect to another page.
This is what I have in my template that calls the ajax:
<f:section name="main">
<h1>I am</h1>
<f:form action="">
<f:form.select id="topics" name="topics" options="{categories}" optionValueField="uid" optionLabelField="title" additionalAttributes="{onchange: 'getFacts()'}"/>
<f:form.hidden id="extraids" name="extraids" value="3,4,5" />
<f:form.hidden id="number" name="number" value="3" />
</f:form>
<div>
<div class="factoid1"><f:render partial="Category/Factoid1" /></div>
<div class="factoid2"><f:render partial="Category/Factoid2" /></div>
<div class="factoid3"><f:render partial="Category/Factoid3" /></div>
</div>
<f:flashMessages renderMode="div" />
<script type="text/javascript">
var actionsPathFromViewHelperSetInTheView = '<f:uri.action action="ajaxfacts" controller="Factoid" />';
</script>
</f:section>
and this is the javascript:
function performAjaxCall(Topics, Extraids, Number) {
alert("dddd");
$.ajax({
url: actionsPathFromViewHelperSetInTheView,
data:{
"tx_factoids_interests[uid]":Topics,
"tx_factoids_interests[extraids]":Extraids,
"tx_factoids_interests[number]":Number
},
success:function (data) {
// do something with your json
alert('Load was performed.');
}
});
}
function getFacts(){
performAjaxCall($("#topics").val(), $("#extraids").val(), $("#number").val());
}
and this is my action function:
/**
* action ajaxfacts
*
* #return void
*/
public function ajaxfactsAction() {
echo __LINE__;
die;
}
and my plugin in ext_localconf:
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Seethroughweb.' . $_EXTKEY,
'Interests',
array(
'Factoid' => 'interests, list, show, new, edit, create, update, ajaxfacts',
),
// non-cacheable actions
array(
'Factoid' => 'interests, list, show, new, edit, create, update, ajaxfacts',
)
);
What am I missing to make the action accessible?
The resulting uri looks like this :
xhttp://...xyz.com/index.php?id=111&tx_factoids_interests%5Baction%5D=ajaxfacts&tx_factoids_interests%5Bcontroller%5D=Factoid&cHash=0e805af8af888ebd7fec5e207f64b5f7&tx_factoids_interests%5Buid%5D=5&tx_factoids_interests%5Bextraids%5D=3%2C4%2C5&tx_factoids_interests%5Bnumber%5D=3
the page is is called from is accessible with the first part ie :
xhttp://....xyz.com/index.php?id=111
I am using Typo3 6.2,
Thanks.
PS: javascript version two - made to work like the Arek's answer.
function performAjaxCall(Topics, Extraids, Number) {
alert("performAjaxCall");
$.ajax({
url: $('form').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('form').serialize(), // serializes the form
// data:{
// "tx_factoids_interests[uid]":Topics,
// "tx_factoids_interests[extraids]":Extraids,
// "tx_factoids_interests[number]":Number
// },
success:function (data) {
// do something with your json
alert('performAjaxCall Load was performed.');
}
});
return false;
}
PPS: the request uri from this method now looks like this:
http://...xyz.com/undefinedindex.php?id=111&tx_factoids_interests%5Baction%5D=ajaxfacts&tx_factoids_interests%5Bcontroller%5D=Factoid&cHash=0e805af8af888ebd7fec5e207f64b5f7
and current javascript:
function performAjaxCall( Topics, Extraids, Divid) {
//alert("performAjaxCall");
$.ajax({
type: "POST",
dataType: "json",
url: $('base').attr('href') + $('#form1').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('#form1').serialize(),
// url: actionsPathFromViewHelperSetInTheView,
// data:{
// "tx_factoids_interests[uid]":Topics,
// "tx_factoids_interests[extraids]":Extraids
// },
success:function (data) {
// do something with your json
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
items += "<span class="+ikey+">" + ival + "</span><br/>" ;
});
$(id).html(items);
});
// $(".factoid1").html();
// $(".factoid2").html();
// $(".factoid3").html();
//alert('performAjaxCall Load was performed.');
}
});
}
function getFacts(Divid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid );
return false;
}
and the current template:
<div id="interests">
<f:form action="ajaxfacts" controller="Factoid" id="form1">
<f:form.select id="intereststopics" name="topics" options="{categories}" optionValueField="uid" optionLabelField="content" additionalAttributes="{onchange: 'getFacts(\'#interests\')'}"/>
<f:form.hidden id="interestsextraids" name="extraids" value="2,4,5" />
</f:form>
<div>
<div id="factoid2" class="factoid1"></div>
<div id="factoid4" class="factoid2"></div>
<div id="factoid5" class="factoid3"></div>
</div>
</div>
PPPS: final code
function performAjaxCall( Topics, Extraids, Divid, Formid) {
$.ajax({
type: "POST",
dataType: "json",
url: $(Formid).attr('action'), // now we're using the url generated by Extbase/Fluid
data: $(Formid).serialize(),
success:function (data) {
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
$(id +" ."+ikey).html(ival);
});
});
}
});
}
function getFacts(Divid, Formid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid, Formid );
return false;
}
You didn't set the <f:form action="">.
The calculated cHash is in your case based on the URL generated by <f:uri> which does not contain any information about the other properties you added in your JavaScript. Hereby you're running into the cHash error.
You can prevent that the pageNotFoundHandler is called on a cHash error by disabling $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError'] (Local Configuration).
For more information abount the cHash:
The mysteries of &cHash
The &cHash parameter of frontend plugins might have puzzled quite a few developers but this article will explain how it works and what to avoid in order to make great, reliable plugins with TYPO3.
Solution
Instead of making a custom url you need to use the action from the form generated by Extbase/Fluid.
So your form should look like:
<f:form action="ajaxfacts" controller="Factoid">
And your JavaScript should look like:
$(function() {
$('form').submit(function(e) {
$.ajax({
type: "POST",
url: $('base').attr('href') + $('form').attr('action'), // now we're using the url generated by Extbase/Fluid
data: $('form').serialize(), // serializes the form
success:function (data) {
// do something with your json
alert('Load was performed.');
}
});
return false;
});
});
PPPS Final js code:
function performAjaxCall( Topics, Extraids, Divid, Formid) {
$.ajax({
type: "POST",
dataType: "json",
url: $(Formid).attr('action'), // now we're using the url generated by Extbase/Fluid
data: $(Formid).serialize(),
success:function (data) {
$.each( data, function( key, val ) {
var items='';
var id = '';
$.each( val, function( ikey, ival ) {
if(ikey =='category') id = Divid +" #factoid"+ival;
$(id +" ."+ikey).html(ival);
//items += "<span class="+ikey+">" + ival + "</span><br/>" ;
});
});
}
});
}
function getFacts(Divid, Formid){
performAjaxCall( $(Divid+"topics").val(), $(Divid+"extraids").val(), Divid, Formid );
return false;
}

Load ajax without click button

I have a jquery that makes an AJAX call by clicking a button, but I want them without pressing the button, it should work when loading the page.
This is button
<div>
<form method="post" action="">
<button value="cars" type="submit" id="submitCars">Get Cars</button>
</form>
</div>
Script of button by ajax
<script>
<![CDATA[
$(document).ready(function(){
$('#submitCars').click( function(event) {
event.preventDefault();
var button = $(this).val();
$.ajax({
url: 'search-facet-form',
data: 'button=' + $(this).val(),
dataType: 'json',
success: function(data)
{
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d=document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
return false;
});
});
]]>
</script>
DIV in HTML:
<div id="wines" class="span-7 colborder">
</div>
Javascript will print data in here. Thanks.
Just remove the call to click:
$(document).ready(function(){
var button = $('#submitCars').val(); //You may not even need this, you could just hard code this value
$.ajax({
url: 'search-facet-form',
data: 'button=' + button ,
dataType: 'json',
success: function(data)
{
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d=document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
});
Try to hit the DOM only once when inserting elements. IF you need the submit button then:
function loadCars() {
$.ajax({
url: 'search-facet-form',
data: 'button=' + $(this).val(),
dataType: 'json',
success: function (data) {
$('#wines').html('');
var mycars = '';
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
mycars += '<img src="' + imgen + '"/>';
}
}
$(mycars).appendTo('#wines');// hit the DOM only once with images
}
});
}
$(document).ready(function () {
loadCars();
$('#submitCars').click(function (event) {
event.preventDefault();
loadCars();
return false;
});
});
If the submit button is NOT needed then simplify that part and remove the submit button:
$(document).ready(function () {
loadCars();
});
Remove click handler and replace $(this).val() with $('#submitCars').val();
$(document).ready(function () {
var button = $('#submitCars').val();
$.ajax({
url: 'search-facet-form',
data: 'button=' + $('#submitCars').val(),
dataType: 'json',
success: function (data) {
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d = document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
});
Just remove the $('#submitCars').click( function(event) part and have the whole thing float inside the $(document).ready(function()

Resources