I am responding by sending a post in jquery. But div also writes when the div is closed and when the div is opened.
I need to leave only after closing
the code I wrote
<script>
jQuery(document).ready(function() {
jQuery(".button").bind("click", function() {
var name = jQuery('.nameField').val();
var surname = jQuery('.surnameField').val();
var age = jQuery('.ageField').val();
jQuery('.surnameField').val('');
jQuery.ajax({
url: "../ajax/db.php",
type: "POST",
data: {
name: name,
surname: surname,
age: age
}, // Передаем данные для записи
dataType: "json",
success: function(result) {
if (result) {
jQuery('.comments-list div').remove();
jQuery('.comments-list').append(function() {
var res = '';
for (var i = 0; i < result.users.name.length; i++) {
res += '<div class="media last-child"><a class="media-left" href="#">' + result.users.id[i] + '</a><div class="media-body"><h4 class="media-heading user_name">' + result.users.name[i] + '<small>' + result.users.age[i] + '</small></h4><p>' + result.users.surname[i] + '<p></div></div><hr class="invis">';
}
return res;
});
console.log(result);
} else {
alert(result.message);
}
return false;
}
});
return false;
});
});
</script>
Related
I created an ajax function that returns my items Price by fetching from my DB. I'm sure there isn't any problem with my php but sometimes I get the same result twice!
jQuery
$('.removemore___').click(function(e) {
var item_id = $(this).attr('data-item');
var col_id = $(this).attr('data-col');
var value = $(this).attr('data-value');
if ($(this).attr('data-trash') == 'trash') {
newPopuper('alert_sure__', 'flex', 'blackScreen');
$('.__aggtoyes').attr('data-item', item_id);
$('.__aggtoyes').attr('data-col', col_id);
$('.__aggtoyes').attr('data-value', value);
} else {
$.ajax({
type: "POST",
url: "includes/chekavailableitem.php?remove",
data: {
item_id: item_id,
col_id: col_id,
value: value
},
dataType: "text",
success: function(response) {
var iNum = parseInt(value);
iNum--;
if (response == 'done') {
$('.value__cart[data-item=' + item_id + '][data-col=' + col_id + ']').html(iNum);
$('.removemore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
$('.addmore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
if (iNum == 1) {
location.reload();
}
} else if (response == 'deleted') {
location.reload();
}
},
error: function() {
$('#wrong-signup').html(': 102');
},
timeout: 5000
});
}
$.ajax({
type: "POST",
url: "includes/get_finalize_cart.php",
data: {},
cache: false,
async: true,
dataType: "json",
success: function(response) {
// var final_price = $.parseJSON(response)
console.log(response);
if (response[0] == 'done') {
$('.final_price__').html(response[1] + ' <span style="font-size: .786rem;font-weight: 400">تومان</span>');
} else {
}
},
error: function() {
$('#wrong-signup').html(': 101');
},
timeout: 5000
});
e.stopImmediatePropagation();
return false;
});
Here is full function in jQuery
<?php
include 'db.php';
include 'function.php';
$user_id = extractUserId();
$chekcart = "SELECT * FROM `box` WHERE `user_id`='$user_id'";
$result_cox_cart_cheker = connectANDdie($chekcart);
$sum_price = 0;
while($row_items = mysqli_fetch_assoc($result_cox_cart_cheker)){
$price = $row_items['item_price'];
$value = $row_items['value'];
$sum_price = $sum_price + ( $price*$value );
$final_value = number_format($sum_price);
$result = ['done',$final_value];
$result1 = json_encode($result);
echo $result1;
}
and I'll also show a screenshot from console page so you can see what my result is:
You're not waiting for chekavailableitem.php?remove to complete before you call get_finalize_cart.php. Since AJAX is asynchronous, the latter might be processed first, so you'll get a duplicate of the old value.
You should put the second $.ajax() call in the sucess: function of the first $.ajax() call, or use a promise.
i want to check whether is a valid item or not before saving the values. then i create java-script function to check validation and return result. but the problem is this function returns before validate items, the always true the condition above if condition. my code is below. could anyone help me please?
this is series of ajax call and i'm not aware of how to use callback for this..
if(IsValidItems() != ''){
//Do something
}
function IsValidItems() {
var IsvalidStatus = '';
var lineqty = 0;
var LineNumber = -1;
var allRowData = jQuery("#tblJQGrid").jqGrid("getRowData");
for (var i = 0; i < allRowData.length - 1; i++) {
if (allRowData[i].BulkItem != "False") {
if (allRowData[i].quantity != '') {
lineqty = parseInt(allRowData[i].quantity);
LineNumber = i + 1;
var postURL = "/BookingDetail/GetItemAvailablity?ItemCode=" + allRowData[i].itemCode + "&StartDate=" + allRowData[i].StartDate + "&EndDate=" + allRowData[i].EndDate + "&srno=" + allRowData[i].srno + "&locationID=" + allRowData[i].Location;
$.ajax({
url: postURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "",
type: "POST",
async: true,
dataFilter: function (data) {
return data;
},
success: function (result) {
if (lineqty > parseInt(result)) {
IsvalidStatus = IsvalidStatus + "," + LineNumber;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
}
}
return IsvalidStatus;
}
I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Size:Under 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!
I can't figure it out... The ajaxscript won't run. Until the script is called, everything works fine, the function doesn't seem to be called. Without calling it, it works fine.
So I found code to get my facebook friends. Script works nice, but I want to write this to my PHP-database.
This is the code I added:
function geefNaam(id, naam){
$.ajax({
type: "POST",
url: "schrijfrecord.php",
data: { id: id, naam: naam },
success: window.alert("whatever")
});
}
</script>
this is the full script
<!DOCTYPE html>
<head>
<script>
function geefNaam(id, naam){
$.ajax({
type: "POST",
url: "schrijfrecord2.php",
data: { id: id, naam: naam },
success: window.alert("bam!")
});
}
</script>
</head>
<body>
<script src="jquery.js"></script>
<header>
</header>
<center>
<button id="fb-auth">login</button>
</center>
<div id="result_friends"></div>
<div id="fb-root"></div>
<script>
function sortMethod(a, b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
window.fbAsyncInit = function() {
FB.init({ appId: '<?= $sApplicationId ?>',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
FB.api('/me/friends?limit=<?= $iLimit ?>', function(response) {
var result_holder = document.getElementById('result_friends');
var friend_data = response.data.sort(sortMethod);
var results = '';
for (var i = 0; i < friend_data.length; i++) {
var id = friend_data[i].id;
var naam = friend_data[i].name;
results += '<div><img src="https://graph.facebook.com/' + id + '/picture">' + naam + '</div>';
**geefNaam(id, naam);**
}
// and display them at our holder element
result_holder.innerHTML = '<h2>Result list of your friends:</h2>' + results;
});
button.onclick = function() {
FB.logout(function(response) {
window.location.reload();
});
};
} else { // otherwise - dispay login button
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
window.location.reload();
}
}, {scope:'email'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
Wrap your success method in an anonymous function:
function geefNaam(id, naam){
$.ajax({
type: "POST",
url: "schrijfrecord.php",
data: { id: id, naam: naam },
success: function() { window.alert("whatever"); }
});
}
As it is, you're just calling the alert right there, and setting it's return value (which is nothing) to your success method. When you wrap it with an anonymous function, the return value is a function, which is what success is looking for.
I have an input text box which fires each time when the user enters data and fills the input text.I'm using bootstrap typehead. Problem is when i enter a letter a it does fire ajax jquery call and fetch the data but the input text box is not populated.Now when another letter aw is entered the data fetched against letter a is filled in the text area.
I have hosted the code here http://hakunalabs.appspot.com/chartPage
Ok so here is part of my html code
<script type="text/javascript">
$(document).ready(function () {
$('#txt').keyup(function () {
delay(function () {
CallData();
}, 1000);
});
});
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
</script>
<input type="text" id="txt" runat="server" class="span4 typeahead local remote" placeholder="Search..." />
And here is my javascript code
var DataProvider;
function CallData() {
DataProvider = [];
var vdata = $('#txt').val();
if (vdata != "") {
var urlt = "http://examples/search?keyword=" + vdata + "&callback=my_callback";
$.ajax({
type: "GET",
url: urlt,
jsonpCallback: "my_callback",
dataType: "jsonp",
async: false,
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
}
function my_callback(data) {
var NameArray = new Array();
var descArray = new Array();
for (var i = 0; i < data.count; i++) {
NameArray.push(data.response[i].days_till_close + " Days Left | " + data.response[i].name + " | " + data.response[i].description);
}
for (var i = 0; i < data.count; i++) {
descArray.push(data.response[i].description);
}
DataProvider = [];
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: NameArray[i], description: descArray[i] };
DataProvider.push(dataObject);
}
var vdata = $('#txt').val();
var urlp = "http://example.com/v1/members/search?keyword=" + vdata + "&my_callbackMember";
$.ajax({
type: "GET",
url: urlp,
jsonpCallback: "my_callbackMember",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
function my_callbackMember(data) {
var memberArray = new Array();
for (var i = 0; i < data.count; i++) {
memberArray.push(data.response[i].name);
}
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: memberArray[i] };
DataProvider.push(dataObject);
}
localStorage.setItem("name", JSON.stringify(DataProvider));
var sources = [
{ name: "local", type: "localStorage", key: "name", display: "country" }
];
$('input.typeahead.local.remote').typeahead({
sources: [{ name: "", type: "localStorage", key: "name", display: "name"}],
itemSelected: function (obj) { alert(obj); }
});
}
Your issue is that typeahead can only present to you the results that are already in localstorage at the moment when you do a key press. Because your results are fetched via AJAX, they only show up in localstorage a second or so AFTER you've pressed the key. Therefore, you will always see the results of the last successful ajax requests in your typeahead results.
Read the bootstrap documentation for type aheads http://twitter.github.com/bootstrap/javascript.html#typeahead and read the section about "source". You can define a "process" callback via the arguments passed to your source function for asynchronous data sources.