Load ajax without click button - ajax

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

Related

How to use SweetAlert success with OK button?

I have created a SweetAlert using the code below. After I used this, the result was shown BUT I am not pressing OK yet, already jumped to URL that I set.
This is a SweetAlert script I created (I save in my script when I want to use then I take it from because I'm using Laravel framework).
<script type="text/javascript">
function showSuccessSwal(message) {
Swal.fire(
'Success',
message,
"success"
);
}
function showErrorSwal(message) {
Swal.fire(
'Error',
message,
"error"
);
}
</script>
And this is a script I'm using:
<script type="text/javascript">
$('#somthing-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
}
});
});
</script>
I want the result to work like this:
I press a submit button.
Display a SweetAlert with an OK button.
Wait for the user to press the OK button then go to the URL I set (not straight jump to URL before I press OK button).
you need to call the swal before you call the ajax
swal({
title: 'Are you sure to go ahead?,
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, please!'
}).then(function(result) {
if (result.value) { // when you click `yes, please!`
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
});
}
});

Show Button after ajax function success

I want to show a button "Reload Game" after function success instead of this bootstrapDialog box
I need this button to fit over my <div class="tilting"></div> Instead of showing somewhere else on page
You need to use below code inside the success method,
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
If you are using jQuery Ajax try it below way,
function loadDoc() {
$.ajax({
type: 'POST',
url: 'APUC',
data: 'productName=' + productName,
dataType: 'html',
cache: false,
success: function (result) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
},
});
}
If you are using pure Ajax, try it like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

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;
}

Toggle partial view with AJAX

In my MVC-project I have this code for rendering a partial-view:
Method:
public ActionResult ShowArtCollection()
{
var model = new ViewModel();
model.ArtWorks = db.ArtWorks.ToList();
return PartialView("_artcollection", model);
}
AJAX:
$("#btnArt").click(function () {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
}
});
});
I would like my #btnArt to be able to toggle the partial view. I mean that when the _artcollection is rendered by the click of the button, the next click should "unrender" the view. Any tips on how to achieve this?
you can put a flag and check if rendered next time unrender on click:
var rendered = false;
$("#btnArt").click(function () {
if (!rendered) {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
rendered = true;
}
});
} else {
$('#artworks').html("");
rendered = false;
}
});
this will do the trick for you.

$.submit form and replace div using ajax has strange jquery behaviour on the new partialview

I think the problem is with jQuery, i don't know for sure.
Let me explain the situation.
Screenshot 1
I fill in the partialView and click on submit.
The submit is a jQuery event handler with the following code:
_CreateOrEdit.cshtml
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
$.post(action, serializedForm, function (data) {
$("#main-content").html(data);
});
return false;
});
</script>
This all works fine on the first-run.
Then when i submit the form when it is invalid (Screenshot 1),
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
context.Clients.Add(client);
context.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(client);
}
Then it tries to redisplay the same form again (Controller Client, Action Create), but something isn't triggered right (Screenshot 2). The layout is wrong (buttons still hidden), the tabs aren't working (javascript), ...
Worst of all, i don't get any error in Firebug, Chrome Console, ...
Does anyone have an idea what could be the problem, because i really haven't got a clue what's happening. It seems to me that nothing has changed, but it did :s
Fyi, an equivalant for the post function is :
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
request.done(function (msg) {
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Before submit, everything loads fine
After submit, same form is called. jQuery isn't working anymore and form is getting bricked (i think this is "side" behaviour from the jQuery breaking)
Edit: (on request)
Here is the partialView in full
_CreateOrEdit.cshtml doesn't contain any javascript for now, the result is the same, so i only posted Create.cshtml.
Create.shtml
#model BillingSoftwareOnline.Domain.Entities.Client
<div class="container_12 clearfix leading">
<div class="grid_12">
#using (Html.BeginForm("Create", "Client", FormMethod.Post, new { #class="form has-validation", id="CreateOrEditSubmit"}))
{
#Html.Partial("_CreateOrEdit", Model)
<div class="form-action clearfix">
<button class="button" type="submit">
OK</button>
<button class="button" type="reset">
Reset</button>
</div>
}
</div>
</div>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.itextclear.js")"> </script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.uniform.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery.tools.min.js")"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
});
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
</script>
Since this markup is returned as a partial, you need to reinitialize your javascript.
This is hacky, but try putting your script in the partial view, instead of _CreateOrEdit.cshtml, and see if that works.
Update
After seeing the cshtml, it looks like it is not working because $(document).ready() has already executed, before the ajax load. Try this instead:
$(function () {
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(window).bind('drilldown', function () {
$(".tabs > ul").tabs("section > section");
});
$("#CreateOrEditSubmit").submit(function () {
//get the form
var f = $("#CreateOrEditSubmit");
//get the action
var action = f.attr("action");
//get the serialized data
var serializedForm = f.serialize();
// $.post(action, serializedForm, function (data) {
// $("#main-content").html(data);
// });
var request = $.ajax({
type: 'POST',
url: action,
data: serializedForm,
success: function (data) {
$("#main-content").html(data);
},
dataType: 'HTML'
});
return false;
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
});
Add the following instructions to the end of your ajax callback, so that the styling is applied after the form has been injected to the DOM:
$('input[type=text], input[type=password], input[type=url], input[type=email], input[type=number], textarea', '.form').iTextClear();
$("input:checkbox,input:radio,select,input:file").uniform();
$("input[type=date]").dateinput();
$(".tabs > ul").tabs("section > section");

Resources