I have a problem with my html webpage, I am trying to use a code to show determinate window's login, the problem is no matter what statement(if-else, if-if, or other) I use...always display the same window (mean always display the window I coded on deslogeado.php, I can't make display the window coded on logeado.php).
Some details: msg is an string which can bring the word 'cero'(here will display a window to user can login) or other word (here will display a window where user is already logged).
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
console.log(msg);
if(msg === flag)
$('#apDiv7').load('deslogeado.php');
if(msg !== flag)
$('#apDiv7').load('logeado.php');
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
tipo=typeof msg;
console.log(msg,flag);
if(msg == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "getSesion.php",
success: function(data)
{
var flag='cero';
console.log(data,flag);
if(data === flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
})
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data)
{
if(data.message == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
});
</script>
Tried with 1,2 and 3 equal on if, I don't know if an html attribute problem or what. I really hope someone can help me! My regards!
When sending data via ajax in the future, consider formatting it with JSON, which will alleviate the ambiguity of free text (with possible spaces before/after).
You are using AJAX which is asynchronous. You should use the "success" callback, or the done() method of the Deferred Ajax call.
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data) {
if(data.message == flag) {
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
Your php script should return a json formatted object like:
{ "message":"cero" }
Related
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
i am building a webapp to keep track of some customers details and other various information
what im chasing is a simple ajax function that i can reuse multiple times in the same page the send data to another page from various forms like a new customer form and say new lead form or do i need to create different ajax functions for each
i have this demo code from my login page however its for a specific form i would like for it to be able to just be given a varibale of the form name and submit all the fields in that form to another page is this possible
<script type='text/javascript'>
$('#form').on('submit',function(event){
event.preventDefault();
var wa_username = $('#wa_username').val();
var wa_password = $('#wa_password').val();
var datas='wa_username='+wa_username+'&wa_password='+wa_password;
$.ajax({
type: 'POST',
url: '/limitless/functions.php',
dataType: 'json',
data: datas,
success: function(data) {
if(data.status == '1')
{
document.location.href = '/limitless/dashboard';
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
})
});
</script>
The .serialize() method on a form creates a text string in standard URL-encoded notation.
$(this).serialize() //this produces wa_username=test&wa_password=123
you could split this like below or instead of creating the datas just call the line above
$('#form').on('submit',function(event){
event.preventDefault();
postForm($(this).serialize());
});
function postForm(formData){
$.ajax({
type: 'POST',
url: '/limitless/functions.php',
dataType: 'json',
data: formData,
success: function(data) {
if(data.status == '1')
{
document.location.href = '/limitless/dashboard';
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
})
}
Hi i currently having a problem with firing .ajaxComplete function, whereby it should be working on a demo site. I'm refer to this function from here http://www.bitrepository.com/a-simple-ajax-username-availability-checker.html
Here are my code :
<SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html
*/
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#userID").change(function() {
var usr = $("#userID").val();
if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "userID="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == "OK")
{
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
}
});
});
//-->
</SCRIPT>
I had try to alert the msg , the check.php able to return back the msg value, but it stop on the .ajaxComplete() there where it does not trigger the function after the .ajaxComplete(). Please guide me through this. Thanks
From the document
As of jQuery 1.8, the .ajaxComplete() method should only be attached
to document.
So
$(document).ajaxComplete(function(event, request, settings){
});
But in your code, there is no need to use ajaxComplete, the success callback will be called only when the ajax call is finished, so you can just check the value of msg directly in it.
$.ajax({
type: "POST",
url: "check.php",
data: "userID=" + usr,
success: function (msg) {
if (msg == "OK") {
$("#userID").removeClass('object_error'); // if necessary
$("#userID").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
$("#userID").removeClass('object_ok'); // if necessary
$("#userID").addClass("object_error");
$(this).html(msg);
}
}
});
What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}
Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))
I was wondering how to limit the search result in the Javascript file, my JS file details as following:
/* JS File */
<script>
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
</script
I just need to add similar to following code to be able to load a loading images before the result and limit the results into five or whatever, and if possible add load more later.
<script>
function loadSearch(query) {
document.body.style.overflow='hidden';
if (typeof xhr != "undefined") {
xhr.abort();
clearTimeout(timeout);
}
if (query.length >= 3) {
timeout = setTimeout(function () {
$('#moreResults').slideDown(300);
$('#search_results').slideDown(500).html('<br /><p align="center"><img src="http://www.tektontools.com/images/loading.gif"></p>');
xhr = $.ajax({
url: 'http://www.tektontools.com/search_results.inc.php?query='+encodeURIComponent(query),
success: function(data) {
$("#search_results").html(data);
}
});
}, 500);
} else {
unloadSearch();
}
}
function unloadSearch() {
document.body.style.overflow='';
$('#search_results').delay(100).slideUp(300);
$('#moreResults').delay(100).slideUp(300);
}
</script>
I have got the 2nd code from another template page, and I am just failing to adjust it to fit my search template (1st code), I'd appreciate it if someone could help me to adjust it, thanks a lot.
If you want to do this on the javascript side, you can use slice.
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html.slice(0, 5);
}
});
I would personally suggest that you do the limiting of rows on the server side to minimize the amount of data you transfer between the client and the server.