Jquery and live act wired but act ok after force refresh in IE - internet-explorer-8

somthing is wrong with my code and i can't get what it is...
i have a div id = "personaltab"
i have a form in side it to login the user with username and password. if success the jquery empty the div and puts in the form of the bidding.
if the user try to bid the other ajax that assign to the button is working but for some reason skips the empty and just adding the responded ajax to the div
i have checked that in IE and chrome and it is working fine in chrome
here are my codes
$("#login").click(function() {
var id = $("input#pid").val();
var user = $("input#puser").val();
var pass = $("input#ppass").val();
var dataString = 'id='+ id + '&user='+ user + '&pass=' + pass;
if (user == "") {
alert("error");
$("input#puser").focus();
return false;
}
if (pass == "") {
alert("error");
$("input#ppass").focus();
return false;
}
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
if (msg=="False") {
alert("error");
$("#personaltab").show();
}
else {
$("#personaltab").fadeOut("normal",function(){
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").slideDown();
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
return false;
});
$("#sendbid").live("click", function(){
var startat = $("input[name=startat]").val();
var sprice = $("input[name=sprice]").val();
if (parseInt(sprice)<=parseInt(startat)) {
alert("error");
$("input[name=sprice]").focus();
return false;
}
else {
var payment = $("select[name=payment]").val();
if ($('input[name=credit]').is(':checked') ){
var credit = true;
}
var prodid = $("input[name=id]").val();
var dataString = 'id='+ prodid + '&price='+ sprice + '&payment=' + payment + '&credit=' + credit;
$.ajax({
type: "POST",
url: "loginpersonal.asp",
data: dataString,
success: function(msg)
{
$("#personaltab").empty();
$("#personaltab").append(msg);
$("#personaltab").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('error');
}
});
}
return false;
});

Solved:
i had inside a and for some reason the div that need to get the ajax by his id was duplicated
don't ask :-)

Related

Getting Error in codeigniter ajax dropdown changing

Getting Error in codeigniter ajax dropdown changing
[![enter image description here][1]][1]
function fun1(sid) {
//alert(sid);
var obj;
if (window.XMLHttpRequest) {
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP")
}
obj.open("post", "https://99shopin.com/register/getcity?val=" + sid, true);
obj.send();
obj.onreadystatechange = function() {
if (obj.readyState == 4) {
document.getElementById('div1').innerHTML = obj.responseText;
} else {
document.getElementById('div1').innerHTML = "";
}
}
}
Try this, and check Is there still an error?
function fun1(sid){
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('register/getcity'); ?>",
data: ({val: sid}),
//dataType: "json",
success: function (data) {
document.getElementById('div1').innerHTML = data.responseText;
}
});
}

Combine AJAX and API calls

I am working with APIs. My logic is 1st add a grade (POST), 2nd get the gradeID (GET), 3rd add grades to students (PUT). My problem is that I have to use the gradeID in the API call to add the grades.
How do I do using AJAX to get the result from one call and then pass to another call?
here is my ajax:
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) {
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
$("#responseFieldLabel").removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
Is there a way tho have an ajax inside of other?

jQuery Form plugin doesn't calls Method in IE 8

I am trying to upload files to server, but when i am submitting form it doesn't calls ActionResult. It works in chrome, FF but not in IE. When i am removing enctype="multipart/form-data" attribute from form in IE, then it calls method, but without file uploading...
I have such input:
<input id="jqueryfileupload" type="file" name="files" data-upload-id="#documentUniqueId"
data-url="#Url.Action(MVC.Profile.Documents().AddRouteValue("documentUniqueId", documentUniqueId))" multiple>
jQuery code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
//input itself is not in the form tag, so i am creating form here and
//submitting it this way
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="POST"></form>');
$this.appendTo(formContainer);
var contentTypeOption = $.browser.msie ? 'text/html' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
//contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
$(formContainer).ajaxSubmit(options);
return false;
});
There are no errors and alerts are not throwing at all in IE. Just method is not called...
Action Method:
[HttpPost]
public virtual ActionResult Documents(IEnumerable<HttpPostedFileBase> files, string documentUniqueId)
{
var result = new ContentResult();
if (files != null)
{
foreach (var item in files)
{
string docName = documentUniqueId + "_" + item.FileName;
var filename = Path.Combine(Server.MapPath("~/App_Data"), docName);
item.SaveAs(filename);
}
var docs = files.Select(x => new
{
url = Url.Action(MVC.Profile.Documents(documentUniqueId + "_" + x.FileName, x.ContentType)),
name = x.FileName,
contentType = x.ContentType,
id = documentUniqueId + "_" + x.FileName
});
result.Content = new JavaScriptSerializer().Serialize(docs);
return result;
}
result.Content = new JavaScriptSerializer().Serialize(new { success = false });
return result;
}
[HttpGet]
public virtual ActionResult Documents(string fileName, string contentType)
{
var docPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
return File(docPath, contentType);
}
I use this plugin : http://malsup.com/jquery/form/
I think you are not inserting the form in the page. that's the problem. you have to add formContainer.appendTo(container);
try this code:
$(document).on('change', '.documents-upload-container #jqueryfileupload', function (e) {
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var container = $this.parents('.documents-upload-container').addClass("current-container");
var formContainer = $('<form action="' + $this.data('url') + '" enctype="multipart/form-data" method="post"></form>');
$this.appendTo(formContainer);
formContainer.appendTo(container);
var contentTypeOption = $.browser.msie ? 'text/plain' : 'application/json';
var iframeOption = $.browser.msie ? true : false;
var options = {
dataType: 'json',
contentType: contentTypeOption,
//iframe: iframeOption,
method: 'POST',
//data: { 'isIE': iframeOption },
success: function (response, textStatus, xhr, form) {
alert(response);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr);
alert(textStatus);
alert(errorThrown);
},
clearForm: true
};
formContainer.ajaxSubmit(options);
return false;
});

jquery $.ajax call for MVC actionresult which returns JSON triggers .error block

I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Resources