Display Ajax loader before load data - ajax

Hello friends i want to show Ajax loader before Data load in particular div but problem is the data is coming dynamically on same page but my script calling data from another file Script.php please see my code below
Script
<script>
function loadingAjax(div_id)
{
$("#"+div_id).html('<img src="ajax-loader.gif"> saving...');
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
HTML
<body onload="loadingAjax('myDiv');">
<div id="myDiv"></div>
<div id="xyz"><img src="ss/image/abc.jpg" /></div>
</body>
Its working fine but i want to load data in same page please help me
Thanks in advance ....
EDIT
I want to show loader before load data #xyz into #myDiv

you can try with following html -
<body onload="loadingAjax('myDiv');">
<div id="myDiv">
<img id="loading-image" src="ajax-loader.gif" style="display:none;"/>
</div>
</body>
and the script -
<script>
function loadingAjax(div_id) {
var divIdHtml = $("#"+div_id).html();
$.ajax({
type: "POST",
url: "script.php",
data: "name=John&id=28",
beforeSend: function() {
$("#loading-image").show();
},
success: function(msg) {
$("#"+div_id).html(divIdHtml + msg);
$("#loading-image").hide();
}
});
}
</script>

you can try with following script
<script>
function ajax()
{
var options = {};
options.url = '';
options.type = 'post';
options.data = '';
options.dataType = 'JSON'; // type data get from sever
options.contentType = 'application/json';// type data post to sever
options.async = false;
options.beforeSend = function () {
};
options.success = function (data)
{
};
options.error = function (xhr, status, err) {
console.log(xhr.responseText);
};
$.ajax(options);
}
</script>

Related

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

Post with AngularJS doesn't work

I would like to send a post request to my API. It works with jQuery :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
url: "api.php?option=inscription",
data: {lol : "mess"}
});
</script>
But it doesn't with AngularJS :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
{{1+1}}
<script>
$http.post('api.php?option=inscription', {lol : "mess2"})
.success(function(){alert('cool');});
</script>
If someone can help me. Thank you !
UPDATE :
Thank for your answers, I wanted to simplify but it wasn't clear anymore. So with your help, this is my new code, and the problem is the same. The data in the backend is empty ;
frontend :
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<div ng-controller="MainCtrl"></div>
{{data}}
<script>
var app = angular.module('myApp', []);
app.service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
var back = $http.post(dataUrl, dataTobePosted);
back.success(function(data){
console.log(data);
return data;
}).error(function(data, status, headers, config) {
return status;
});
}
});
app.controller('MainCtrl', function($scope, $http, SomeService){
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
$scope.data = SomeService.readData(url, dataTobePosted);
}
$scope.readData('api.php?option=inscription');
});
</script>
</html>
For clarity, I am suggesting a simple implementation. However, further reading may needed in order to understand the behaviour precisely.
angular.module('myApp').service('SomeService', function($http) {
this.readData = function(dataUrl, dataTobePosted) {
// read data;
return $http.post(dataUrl, dataTobePosted)
.then(function(res) {
return res.data;
}, function(res) {
return res;
}
}
return this;
});
angular.module('myApp').controller('MyController', function($scope, SomeService) {
$scope.readData = function(url) {
var dataTobePosted = {"lol": "mess"};
SomeService.readData(url, dataTobePosted)
.then(function(res) {
$scope.data = res;
}, function(res) {
// Display error
}
}
$scope.readData('api.php?option=inscription');
}
Usage in the HTML page
<div ng-controller="MyController">
{{data}}
</div>
You're using AngularJS as if it's jQuery. It's not. AngularJS works with dependency injection, so you need to wrap your $http call inside a controller.
You should probably read up on AngularJS. A few useful links:
https://docs.angularjs.org/guide/introduction
https://docs.angularjs.org/guide/controller
https://docs.angularjs.org/guide/di
"Thinking in AngularJS" if I have a jQuery background?
My bad, my problem came from my backend in the php I just get my data with :
$data = json_decode(file_get_contents("php://input"));
and not with $_POST

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

jQuery ajax - outputting files from an ajax request

is it possible to output a file as a response from a ajax call?
i've wrote a function for outputting zip files using an ajax call, this is the code:
<script type="text/javascript">
$(document).ready(function () {
$(".ziplink").click(function (e) {
e.preventDefault();
var url = $(this).attr('href');
var spinner = $(this).parent().children(".spinnerbox");
spinner.show();
$.ajax({
url:url,
type:"GET",
dataType:"application/x-zip-compressed",
success:function (data) {
console.log('success');
spinner.hide();
},
error:function () {
console.log('ko');
spinner.hide();
}
});
});
});
</script>
now, from the firebug console everything is ook, but i dont have file output. what is missing?
Although this is fully functional in the non-ajax way (a simple link to the action), i'd like to have the spinner animation while server process the request.
thanx - LuKe
$(".ziplink").click(function (e) {
e.preventDefault();
var _self = $(this);
$('.spinner').show();
$.ajax({
type : 'HEAD',
url : _self.attr('href'),
complete : function(){
$('.spinner').hide();
var _tmp = $('<iframe />')
.attr('src', _self.attr('href'))
.hide()
.appendTo(_self)
setTimeout(function(){
_tmp.remove();
},5000);
}
});
});
Demo http://jsfiddle.net/4sMsr/3/

$.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