AJAX recognizing if the result call is an error or a success - ajax

multiple request to fill different containers?
ajax/javascript example:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function()
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
});
});
});
ajax.php example:
<?php
if($_POST['request']==1) // or several complicated conditions
{ ?><div>This is a success</div>
//if success I would like to load another piece of html inside an id="container2".
<?php }
if($_POST['request']==0)
{ ?><div>This is a disaster</div> <?php }
?>
That's the question if the response is 1 (or This is a success) I would like to load another piece of html code inside a container (container2) with a different id from the original container id used for the request within the post method(in this case "container1").
Is there a way to do it?
Thanks for your thoughts and answers!

$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$.post("ajax.php", {request : $var}, function(a,b)
{
if(b=="error"){
Do Somthing...
} else{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
});
});
});

Related

How to refresh content when using CrossroadJS and HasherJS with KnockoutJS

I was following Lazy Blogger for getting started with routing in knockoutJS using crossroads and hasher and it worked correctly.
Now I needed to refresh the content using ajax for Home and Settings page every time they are clicked. So I googled but could not find some useful resources. Only these two links
Stack Overflow Here I could not understand where to place the ignoreState property and tried these. But could not make it work.
define(["jquery", "knockout", "crossroads", "hasher"], function ($, ko, crossroads, hasher) {
return new Router({
routes:
[
{ url: '', params: { page: 'product' } },
{ url: 'log', params: { page: 'log' } }
]
});
function Router(config) {
var currentRoute = this.currentRoute = ko.observable({});
ko.utils.arrayForEach(config.routes, function (route) {
crossroads.addRoute(route.url, function (requestParams) {
currentRoute(ko.utils.extend(requestParams, route.params));
});
});
activateCrossroads();
}
function activateCrossroads() {
function parseHash(newHash, oldHash) {
//crossroads.ignoreState = true; First try
crossroads.parse(newHash);
}
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
$('a').on('click', function (e) {
crossroads.ignoreState = true; //Second try
});
}
});
Crossroads Official Page Here too I could not find where this property need to be set.
If you know then please point me to some url where I can get more details about this.

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

Handling MVC action result using JQuery post method

I am calling MVC action something like below:
var RestaurantDetailsUIforForeignWidget = {
frmId: '',
onFormSubmit: function () {
var frm = $(RestaurantDetailsUIforForeignWidget.frmId);
var divResult;
$('.offerbox').hide();
$.post(frm.attr('action'), frm.serialize(), function (html) {
// $('#section-time-slots').html(html)
$('#contentAll').html(html);
DisplayOffer();
});
return false;
},
updateTimeDesc: function () {
$('#time').val($('#SittingTime option:selected').html());
},
init: function (frmId) {
RestaurantDetailsUIforForeignWidget.frmId = frmId;
$('#SittingTime').bind('change', RestaurantDetailsUIforForeignWidget.updateTimeDesc);
$(frmId).bind('submit', RestaurantDetailsUIforForeignWidget.onFormSubmit);
RestaurantDetailsUIforForeignWidget.updateTimeDesc();
}
};
As you can see $('#contentAll').html(html); updates whole view content with the result. What I want is to get a single div from html output and update the $('#section-time-slots') instead.
Please help me guys... thanks :)
Try this:
$.post(frm.attr('action'), frm.serialize(), function (html) {
$('#section-time-slots').html($("#IdOfRequiredElementInResponse", html).html());
DisplayOffer();
});

multiple xhr.get s with dojo

how do I do two xhr.gets one after the other using dojo ?
I have ....
require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
function(xhr, dom) {
// Using xhr.get, as very little information is being sent
xhr.get({
// The URL of the request
url: "inc/etl2json.php?item=Execs",
// The success callback with result from server
load: function(execContent) {
dom.byId("Execs").innerHTML = execContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});
});
I would like to do another xhr.get to "inc/etl2json.php?item=Execs" and assign it to dom.byId("Elapsed").innerHTML = elapsedContent;
just call again xhr.get() inside the load function, well that if the content is supposed to change, else you could just use the same data retrieved the first time:
xhr.get({
load:function(data){
//use the first data you retrieved
xhr.get({
load: function(data2){
//do what you like with the nuew data
}
});
}
});
Although nesting is a straightforward solution it almost always leads to unreadable code, so I would do the same as #Ricardo did, but use the advantage of Dojo's Deferred (+ here) and employ chaining:
var requestUrl = "inc/etl2json.php?item=Execs";
xhr.get({ url: requestUrl})
.then(function(results) {
dom.byId("execs").innerHTML = results;
})
.then(function(results) {
return xhr.get({ url: requestUrl});
})
.then(function(results) {
dom.byId("elapsed").innerHTML = results;
})
See it in action at jsFiddle: http://jsfiddle.net/phusick/73X88/
I think you should add another xhr call for the elapsedContent. I don't see any relation between the two calls so you should make them separate. Nesting one in another is not necessary.
just add
xhr.get({
// The URL of the request
url: "inc/etl2json.php?item=Execs",
// The success callback with result from server
load: function(elapsedContent) {
dom.byId("Elapsed").innerHTML = elapsedContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});

AJAX call each() and find() application

The message alert does not appear after the post call under ajax.
Given the following ajax call:
var val= 1;
$.post("ajax.php", { information: val }, function(result)
{
$(result).find("div").each(function()
{
if($(this).text()=="OK")
{
alert("OK");
}
});
});
and the ajax.php file:
<?php
if($_POST['information']==1)
{
?><div>You must fill all the fields</div><?php
?><div>The title must be between 10 and 30 characters</div><?php
?><div>Please insert your email in the field</div><?php
?><div id="answer">OK</div><?php
}
?>
Thanks for your help!
EDIT: corrected errors found by Benny. corrected post syntax and $(result) syntax
In your example you have faulty $.post syntax.
$.post("ajax.php"), { information: $val }, function(result){
// Callback code
});
The correct syntax would be.
$.post("ajax.php", { information: $val }, function(result){
// Callback code
});
Also using $ as part of the $val variable name is confusing. It can trick developers into thinking that it has something to do with the jQuery variable, even though it's just part a local variable name. I would recommend doing just...
var val = 1;

Resources