AJAX

12K

Solutions

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.

Share tech news, updates, or what's on your mind.

Sign up to Post

Here I come again with this question on how to achieve dynamic content loading when user scroll to the bottom of the page. Currently, my code is loading all the content from the db at once using ajax, but I don't want to load everything at once. I want it to load just like twitter or facebook. Below is my code and what I've been trying to do.

HTML
<html>
<head>
<script>
function yHandler() {
    var wrap = document.getElementById('homeFeed');
    var contentHeight = wrap.offsetHeight;
    var yOffset = window.pageYOffset;
    var y = yOffset + window.innerHeight;
    if (y >= contentHeight) {
        // Ajax call to get more dynamic data goes here, how do I integrate the ajax call here? 
    }
}
window.onscroll = yHandler;

function feed() {
    var xhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.onreadystatechange = function(response) {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("homeFeed").innerHTML = this.response;
        }
    };
    xhttp.open("GET", "functions/feedUpdate_New.php", true);
    xhttp.send(null);
}
feed();
</script>
</head>
<body>
<div id="homeFeed"></div>
</body>
</html>

Open in new window



PHP - feedUpdate_New.php

<?php
include_once(db_connect.php);
$sql = "SELECT message, audio, firstname, lastname FROM once WHERE username='myname'";
$query = mysqli_query($db_connect, $sql); 
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
                    $message = $row['message'];
                    $audio = $row['audio'];
                    $firstname = $row['firstname'];
                    $lastname = $row['lastname'];

echo '<div id="parentContainer">';
      echo $message.'<br />';
      echo $firstname.''.$lastname;
echo '</div>';
}
?>

Open in new window


I have more than 1000 lines returned from my database query back to the ajax call. But I want to use the
function yHandler()

Open in new window

to achieve the dynamic loading, but I'm not just getting how to integrate the ajax call inside my
function feed()

Open in new window

into the yHandler to get the dynamic loading working.
Do I need to add LIMIT into my sql statement? Or is there any other way to get this done?
0
Announcing the Most Valuable Experts of 2016
LVL 6
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Hi Experts,

I have a page which has a Ajax call to a search function, which is working fine with the search button, which calls it. When I added a function to capture the enter key to trigger the click attribute of the search button, now the the function is firing, pulls back the correct search records for a flash, but then the page completely reloads with the original value of the page. What I'm not understanding is how the default value of the page is loading, since it's not hitting the database call again. Any ideas?

Thanks,
Steve
0
Hi,

I have a contact form with an XML that loads the contact information in the contact form. I am busy adjusting this. Instead of a dropdown, I want to build an ajax life search. Can someone help with that? I like to hear it

Thanks
test.xml
test3.php
0
I am using a jQuery tabs package (SolidTabs) to present several jQuery/BootStrap (BootGrid) Ajax forms on the same page. iframes are not an option. As its name implies, BootGrid displays a table of records, along with the ability to add a new record or edit an existing one, taking advantage of Ajax, using json and PHP.
I have not wanted to mess with the main js file. I'm thinking I should just be able to change the various HTML id's, and I should be fine. So far, that has not been successful.

My perhaps naive question is - other than using an iframe, is there some way of containing these separate grid forms so that I could use the same id assignments on the same page?
0
I am using code provided by Marco Gasi, and I made some modification to the php to give me 2 results. How can I post the two different results from the php file

<?php

$price = 7.99;

$qty = filter_input(INPUT_POST, "qty");

$total_price = 0;

$total_tax = 0;

if (isset($qty)){

      $shipping = $qty <= 4 ? 9.95 : 14.95;

      $total_price = ($price * $qty) + $shipping;

        $total_tax = $total_price * .0825;
}

echo $total_price;
echo $total_tax;

HTML :   (I want two separate results PRICE and TAX, and the way it is working right now is 1 string file with BOTH results)

<h3><font size="6">Total price is <span id="total-price">$ 15.98</span></font></h3>
                              <h3><font size="6">Taxes <span id="total-tax">$ 1.32</span></font></h3>
      </td>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"  integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0="  crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
            <script type="text/javascript">
                  $(document).ready(function () {
                                //reset quantity value when page reloads
                        $('#qty').val(2);
                                // intercept 'change' event for the quantity input
                        $('#qty').on('change', function () {
                                        // get the value of the quantity input
                              var qty = $(this).val();
                                        //perform an Ajax call…
0
I am trying to upload a file with my form submission using ajax but I keep getting and undefined index error for the "file" field.


$(document).ready(function() {
   $('form').submit(function(e) {
      e.preventDefault();
      var form = $("#form1").serialize();
      $(".alert").hide();
      $.ajax({
       url: 'functions/add-news-ajax.php',
       type: 'POST',
       dataType: 'json',
       data: form,
       beforeSend: function() {
        $("#btn-add").hide();
        $("#loader").show();
       },
      })

      .done(function(data) {
         if (!data.success) {
        // validation errors

Open in new window


This isn't the final upload script I will use. I just grabbed it off the net for testing. I have tried other scripts and I get exactly the same error:

 $fileName = time().'_'.basename($_FILES["file"]["name"]);
    
    //file upload path
    $targetDir = "../uploads/";
    $targetFilePath = $targetDir . $fileName;
    
    //allow certain file formats
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    $allowTypes = array('jpg','png','jpeg','gif');
    
    if(in_array($fileType, $allowTypes)){
        //upload file to server
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
            //insert file data into the database if needed
            //........
            $response['message'] = 'ok';
        }else{
            $response['message'] = 'err';
        }
    }else{
        $response['message'] = 'type_err';
    }

Open in new window


My file field:

<div class="form-group">
	<label for="usr">Image to upload:</label>
	<input id="uploadImage" type="file" name="file">
</div>

Open in new window


The form:

<form id="form1" method="post" enctype="multipart/form-data">

Open in new window

0
What am I doing wrongly in these code? I want to update user password without refreshing the page, but this is not working as my code stops at  
_("pmessage").innerHTML = 'please wait ...';

Open in new window

on the jquery/ajax code. The Ajax seems not to be firing as my DB is not updated with the new password. Below are my codes:

HTML
<form id='pform' method='post'>
<div id='entercurrent'>Enter Current Password:</div>
<input id='current' name='current' type='password'>
<div id='enternew'>Enter New Password:</div>
<input id='newpwd' name='newpwd' type='password'>
<div id='enterconfirm'>Confirm New Password:</div>
<input id='confirmpwd' name='confirmpwd' type='password'>
<input id='passsubmit' type='submit' value='Update Password'>
</form>
<div id='pmessage'></div>

Open in new window


Ajax
$(document).ready(function() {
    $("#passsubmit").click(function(event) {
        event.preventDefault();
        var cp = $("#current").val();
        var np = $("#newpwd").val();
        var cf = $("#confirmpwd").val();
        dataString = "cp=" + cp + "&np=" + np + "&cf=" + cf;
        _("passsubmit").style.display = "none";
        _("pmessage").innerHTML = 'please wait ...';

        $.ajax({
            type: "POST",
            url: "functions/changePwd.php",
            data: dataString,
            success: function() {}
        });
    });
});

Open in new window


PHP -  functions/changePwd.php
if(isset($_POST['cp'])) {
    $currentpwd = $_POST['cp'];
    $newpwd = password_hash($_POST['np'], PASSWORD_DEFAULT);
    $confirmnewpwd = password_hash($_POST['cf'], PASSWORD_DEFAULT);
}
$sql = "UPDATE users SET password='$newpwd' WHERE username='$log_username'";
$query = mysqli_query($db_connect, $sql);

Open in new window

0
I am displaying records from the database like this:

$(document).ready(function(){
			$.ajax({
				url: 'functions/list-articles-delete.php',
				dataType: 'json',
				method: 'POST',
				success: function(data) {
				 $.each(data, function(item){
					var tr_str = "<tr>"
					+ "<td>" + data[item].n_title + "</td>"
					+ "<td>" + data[item].n_dateTime + "</td>"
					+ "<td><button class='btn btn-danger' id='deletebut' data-id='" + data[item].id + "'>Delete</button></td>";
					 $( "#output" ).append(tr_str);
						
					 $( "#deletebut" ).on('click', function(){
						// display id of associated record
				}); 
			});			
		},
	});
});

Open in new window


When I click on any of the buttons I want it to console.log() the id of the associated record but not quite sure how to do this?
0
I'm trying to reload ajax data on click event which pops up a modal

implementationlog is a global variable as well as impviewlogjobid

any help much appreciated

$('#implementationLogModal').on('shown.bs.modal', function (e) {

            report = 8;
            var logparam = "{'report':'" + report + "','jobid':'" + impviewlogjobid + "'}";
            var logparameters = JSON.stringify(logparam);

            if ($('#implementationLogTable th:contains(Log)').length == 0) {
                var header = '<thead id="implementationLogTable-Header"><tr><th class="text-center">Log</th><th>Log Date</th></tr></thead>';
                var footer = '<tfoot id="implementationLogTable-Footer"><tr><th class="text-center">Log</th><th>Log Date</th></tr></tfoot>';
                $("#implementationLogTable").append(header);
                $("#implementationLogTable").append(footer);

                implementationLog = $("#implementationLogTable").DataTable({
                    dom: 'lfrtip',
                    oSearch: { "bRegex": false, "bSmart": true },
                    deferRender: true,
                    bFilter: true,
                    bSearchable: true,
                    processing: false,
                    bRetrieve: true,
                    bSortable: true,
                    lengthMenu: [[10], [10]],
                    stripeClasses: [],
                    destory: true,
                    ajax: {
                        "url": 

Open in new window

0
Hi experts I am using a small script (posted below) to get the location for my web form. I am able to display the location. I want to turn that location into a php variable to use in a text input somewhere else on my web form. Any suggestion on how I should do this? I  tried to use $_GET but I may have done it wrong.
Script:
<script>

$.get("https://ipinfo.io/json", function (response) {
   
   $location=$("#address").html("Location: " + response.city + ", " + response.region);
    //$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
</script>

Open in new window

Area in html I am trying to put the script result into
Address:<input type="text" name="Address"   style="width: 150PX;" value="(location here)">

Open in new window


Thankyou for any feedback
0
[Live Webinar] The Cloud Skills Gap
LVL 4
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

I had this question after viewing how to get id from url using php and Jquery.

This is the php:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title`, `n_dateTime`, `n_article` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
	$row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	$n_dateTime = sanitize(row['n_dateTime']);
   $n_article = sanitize($row['n_article]);
	
	$news_detail[] = array(
	
		"n_title" =>$n_title,
		"n_dateTime" => $n_dateTime,
           "n_article" =>$n_article
	
	);
	
} else {
	
	echo "No record found";
}

$stmt->close();
echo json_encode($news_detail);

Open in new window


This is the jQuery/Ajax:

myApp.onPageInit('article', function (page) {
   var id = page.query.id;
   $$.ajax({
	   url: "news-detail.php",
	   type:"GET",
           data: {id: id}, 
	   success: function(data) {
		console.log(data);
		 
	   },
   });
});

Open in new window


Perhaps I want to show the title at the top of the page and the date at the bottom of the page. Do I need to put everything into divs?

So, at the top of the page I would have <div id="news-headline"></div> and at the bottom of the page I might have <div id="article-date"></div>.

Is that the correct way to do it? And if so, how would I get the values into those divs? When using a while loop for lost of records I used:

$$.each(data, function(item) {

Open in new window


but since I am not looping through records, and only getting one row, I am not entirely sure how to get that data.
0
I want to store 1 when checkbox is checked and 0 when not checked. But my code is only able to store 1 in my database, even though my function returned both 'true' and 'false' appropriately, my database only shows 1 for both checked and unchecked. Below is my code:

Jquery/Ajax

function checkCheckboxState() {
    if ($('input[id*="mobile"]').prop('checked') == true) {
        // execute AJAX request here
        $.ajax({
            type: 'POST',
            url: 'functions/mobilecheck.php',
            data: { 'checked': true },
        });

    } else {
        $.ajax({
            type: 'POST',
            url: 'functions/mobilecheck.php',
            data: { 'checked': false },
        });
    }
}

Open in new window


PHP
<?php
if(true){
    $sql = "UPDATE useroptions SET mobilecheck='1' WHERE username='$log_username'";
    $query = mysqli_query($db_connect, $sql);
} else {
    $sql = "UPDATE useroptions SET mobilecheck='0' WHERE username='$log_username'";
    $query = mysqli_query($db_connect, $sql);
}

?>

Open in new window

0
I am using ajax and jQuery to to query the database and display records from the database. I am then appending the results. The trouble I am having is that when the user taps (this is a mobile app) the article they want to view, it should take them to the details of that particular article. In order to do that I need to send the ID of that article to the detail page.

This is the jQuery  (I am using Framework7 which uses $$ instead of $). This lists the articles.

function newsFeed() {
	$$.ajax({
		url: "newsfeed.php",
		type: "POST",
		dataType: "json",
		success: function (data) {
			$$.each(data, function (item) {
				$$("#newsFeed").append(`

					<li>
						<a href="article.html?$id={data[item].id}" class="item-link item-content">
							<div class="item-media"><img src="img/${data[item].n_pic}" width="80"></div>
								<div class="item-inner">
								<div class="item-title-row">
									<div class="item-title news-headline">${data[item].n_title}</div>
								</div>
							<div class="item-text"></div>
									<div class="date-time">${data[item].n_dateTime}</div>
							</div>
						</a>
					</li>	
				`);
			});
		},
	});
}

Open in new window


I want to GET that id that is being sent in PHP:

$url = filter_var($_GET['id'], FILTER_SANITIZE_URL);
$stmt = $link->prepare("SELECT `n_title` FROM `news` WHERE `id` = ?");
$stmt->bind_param("i", $url);

if (!$stmt->execute()) echo "Execute Error: ($stmt->errno)  $stmt->error";
$result = $stmt->get_result();

if ($result) {
        $row = $result->fetch_assoc();
	$n_title = sanitize($row['n_title']);
	echo $n_title;
	
} else {
	
	echo "No record found";
}

$stmt->close();

Open in new window


This is the jQuery that is trying to get the results:

myApp.onPageInit('article', function (page) {
   $$.ajax({
	   url: "news-detail.php",
	   type:"POST",
	   success: function(data) {
		   console.log(data);
	   }
	   
   })
});

Open in new window


The error I get is:

Undefined index: id

So, I guess that php is not able to get the id being passed in the jQuery.
0
So, I am really trying to get my head around JSON and I have tried this which works but I wanted to know if there is a better way to do it or if this okay. I am actually playing around with developing a hybrid mobile app which uses a php and mysql backend. I have to use ajax to retrieve data and I want to also use JSON.

This is the jQuery/Ajax. The double dollar signs are not a typo, that is the correct syntax for the application but it is identical to jQuery as far as I know.

$$( "#submit" ).click(function(e){
		$$.ajax({
			url:"content.php",
			type:"POST",
			dataType:"json",
			success: function(data) {
				var len = data.length;
				for(var i = 0; i<len; i++) {;
					var user_name = data[i].user_name;
					$$( "#phpcontent" ).append(`
					<li class="item-content">
						<div class="item-inner">
						<div class="item-title">${user_name}</div>
						</div>
					</li>
					`);
				}
			}
		});
	});

Open in new window


This is the php for content.php

$stmt = $link->prepare("SELECT `user_name` FROM `users` ORDER BY `user_name` DESC");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
	while($row = $result->fetch_assoc()) {
		$user_name = sanitize($row['user_name']);
		
		$return_array[] = array(
		
			"user_name" => $user_name
		
		);
	}
}
$stmt->close();
echo json_encode($return_array);

Open in new window


What I have noticed in all the examples I have looked at is that the database results have to be put into an array in order to use json_encode. Am I correct in saying that or is it just a coincidence that every example I looked at did that?
0
I've got an AJAX form dynamic happening. Everything is working just like the client wants with the exception of what happens when a user goes to login and nothing is found in the database.

When the user clicks the "submit" button, here's the code that is called:

$('#findPortalUser').click( function(event){
			
			event.preventDefault();
			
			if (validateForm()) {
				$("#verify_form").hide();
				
				var out = {
					'usrDOB' : $('#usrDOB').val(),
					'usrEEID' : $('#usrEEID').val(),
					'cpID' : 574,
					'displayLinks' : $('#displayLinks').val()
					};
					
				$.post('api_bmcjax.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)
				{
					$('#window').html(data);
				});
			}
		});

Open in new window


Notice the "$('#verify_form').hide()" command.

If nothing is returned, I need that div to be visible.

How?
0
I'm working on a page that I didn't write and I want to understand what I'm doing and what's happening.

Here's a portion of the code that has me puzzled. I want to explain to you what I comprehend and then ask whoever's willing to fill in the gaps.

$.post('api_woodward.php?p=verify&displayLinks=false&linkType=surveyevents', out, function(data)

This is a JQuery AJAX form function. The first part is the URL the form content is being posted to (woodward.php). The second part, "out" - I've no clue. The last part, function(data) - I'm looking at https://api.jquery.com/jquery.post/ and it seems like this is code to display what happens in the event of a successful form transmission.

As far as "out" is concerned, I think I know what it is, but I want some other eyes on it.

When the content is posted to the api_woodward.php page, "p=verify" steers the content to a specific function on the page. Within that function, there's another piece of syntax that kicks into gear based on the linkType being "surveyevents." If that's the case, you have this:

        if ($linkType == 'surveyevents') {
            $result['usrID'] = encryptVals($result['usrID']);
            $out .= <<<OUT
				<script>
				$('#verifyUseryes').click(function($event){		
					//event.preventDefault();
					$.post('api_woodard.php?p=d11', {'ui':'{$result['usrID']}', 'ei':'{$result['empID']}'}, function(data){
						$('#window').html(data);
					});
				});
				

Open in new window

0
Hello,
I am trying to add a header and tabs with info about the XML data file to .xml file in SAS code. How exactly this can be done? Please see what I have currently I have for my SAS code. I can see the XML data file as my output but the Header (tab and tab2) with all info about the XML file does not show up yet in the XML file.
 
libname xmldir xmlv2 '/basepath/examples/XMLData.xml' xmltype=generic;

/* Req. 1: Macro variables to provide appropriate tab spacing. */
%let tab="    ";
%let tab2="        ";

/* Req. 2: XML file information and header*/
data _null_;
   file xmldir;
  
    put '<?xml version="1.0" encoding="UTF-8"?>';
    put '<Schema Name>';
    put &tab. '<Header>';
    put &tab2. '<SampleDate>2017-06-14</SampleDate>';
    put &tab2. '<CaseCount>30</CaseCount>';
    put &tab2. '<Action>Initial</Action>';
    put &tab2. '<YearPeriod>2017</YearPeriod>';
    put &tab. '</Header>';
    put &tab. '<Payload>';
run;

/* Req. 3: Writing two SAS datsets to xmldir library and creating XMLData.xml data file*/ 
data xmldir.dataname1(label="dataset name1 from sashelp library");
       set sashelp.dataset1(obs=10);
run;

data xmldir.dataname2(label="dataset name2 from sashelp library");
       set sashelp.dataset2(obs=20 keep=var1 var2); 
run; 

libname xmldir clear;

/* Req. 4: XML File End*/
data _null_;
   file xmldir mod;

    put &tab'<Payload>';
    put '</Schema Name>';
run;

Open in new window


So, currently only Req. 3 is working.
Any comments or suggestions will be greatly appreciated!
0
I have an asp.net application in which i'm uploading file into the database. In Aspx i have a Updateprogress with Postbacktrigger in UpdatePanel. It is working fine when i remove my Localhost from the Compatibility View in IE11 but when i add localhost in compatibility view UpdateProgress does not appear.

i'm also using Following JavaScript Function to make Updateprogress appear:

<script type="text/javascript">
        window.onsubmit = function () {

            var updateProgress = $find("<%= UpdateProgress1.ClientID %>");
            window.setTimeout(function () {
                updateProgress.set_visible(true);
            }, 100);

        }
    </script>
0
Hello experts,

I am trying to call the ajax function only if there are values in 'stepname' and 'altmethod' else show and alert. When I include the following code, the else part gets executed all the time though there are no values. Could anyone kindly help me with this.

$(document).on("click", '#nextstep', function(e) {

    e.preventDefault();
 var stepname = $('#stepname').val(); 
 var chosen_altmethod = $('#chosen_altmethod').val();
 var altmethod = $('#altmethodname').val();

 
var formData = new FormData();
formData.append('stepname',stepname);
formData.append('altmethod',altmethod);
formData.append('chosen_altmethod',chosen_altmethod);
 formData.append('action','nextstep');

 console.log(stepname,"stepname");
console.log(altmethod, "altmethod");
console.log(chosen_altmethod,"chosen_altmethod");

if((stepname=="undefined") && (altmethodname=="undefined")){
  alert('please choose a step');
}else{
        $.ajax({
             type: 'POST',
            url: "<?= base_url() ?>index.php/variants/fetchstep1/",
             data: formData,
             processData: false,
      contentType: false,
             success: function (data) {

   $("#steplist").remove();
 $("#replacelist").html(data);
   $('html, body').animate({ scrollTop: 0 }, 0);
             }
         });
}
     });

Open in new window


Thank you in advance
0
What does it mean to be "Always On"?
LVL 4
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Hi,
Using these codes

        public static List<HouseData> GetHouseList()
        {
            List<HouseData> houseList = new List<HouseData>();
            using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn3"].ConnectionString))
            {
                using (SqlCommand sqlCmd = new SqlCommand("SELECT house_name, address1, address2, price, price_curr, raised_by_user_id FROM house_tab", sqlConn))
                {
                    sqlConn.Open();
                    sqlCmd.CommandType = CommandType.Text;
                    SqlDataAdapter sqlAd = new SqlDataAdapter(sqlCmd);
                    DataTable sqlDt = new DataTable();
                    sqlAd.Fill(sqlDt);
                    sqlConn.Close();
                    if (null != sqlDt)
                    {
                        houseList = sqlDt
                                        .AsEnumerable()
                                        .Select(dataRow => new HouseData
                                        {
                                            house_name = dataRow.Field<string>("house_name"),
                                            address1 = dataRow.Field<string>("address1"),
                                            address2 = dataRow.Field<string>("address2"),
                                            price = dataRow.Field<decimal>("price"),
                                            price_curr = 

Open in new window

0
I am trying to validate using remote options, but it is always validate as failed
<div class="row">
										<div class="col-sm-12 col-xs-12">
											<input type="text" name="userName" placeholder="Username" class="form-control input-lg" required="required" data-bv-remote="true"/>
										</div>
									</div>

Open in new window

 userName: {
                message: 'The username is not valid',
                validators: {
                    notEmpty: {
                        message: 'The username is required and can\'t be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: 'The username must be more than 6 and less than 30 characters long'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\.]+$/,
                        message: 'The username can only consist of alphabetical, number, dot and underscore'
                    },

                    remote: {
	                    url: '/includes/website.cfc?method=checkusername',
	                    message: {
	                        en_US:  "This usenrame is already taken, please choose another one",
	                    },
	                    data: {
	                        type: 'userName'
	                    },
	                    type: 'POST',
	                    delay: 1000
	                }


                }
            },

Open in new window

<cffunction name="checkusername" output="true" returntype="any" access="remote" returnformat="JSON" >
          <cfargument name="username" required="true" type="string" />
          <!--- set the default value to false --->
          <cfset var emails = StructNew() />
          <cfset emails.valid = "false" />


          <!--- code to check email in system --->
          <cfquery name="findemail" datasource="#request.datasource#">
               select username
               from users
               where username = <cfqueryparam  value="#arguments.username#" cfsqltype="cf_sql_varchar" />
          </cfquery>
          <cfif findemail.RecordCount eq 0>
               <cfset emails.valid = "true" />
          </cfif>
          <cfoutput>#SerializeJSON(emails)#</cfoutput>
     </cffunction>

Open in new window

0
Having a problem with getting fn2 to fire after fn1.  I am sure it is because the google call is asynchronous but not sure how to resolve.

Sample here

    function fn1(searchMethod, searchValue) {
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?' + searchMethod + '=' + searchValue + '&key=someGoogleKey',
            dataType: 'json',
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            },
            success: function(googleData, searchMethod) {
                alert('google done');
                console.log(googleData);
            }

        }).done(function(locData) {
            dfd.resolve();
        });
    }

    function fn2() {
        alert('second function')
    }

    var dfd = $.Deferred();
   
    (function() {
        //function one passes 2 parameters
        //in this case address telling to search for the New York ZIP 12345
        $.when(fn1('address', '12345')).done(function() {
            fn2();
        });

    })();
0
hi , i'm working on a web application (a platform for conferences in a company )
i want to integrate a video chat system inside this website . that's mean that any one registered on the site can have an online chat with somebody else (registered also )
any suggessions please
0
I have created a bootstrap popup login page . When the client click on the login button it will launch the popup and the client will be asked to either login or register. Once login button is clicked I need to validate the credentials and log them in. If the login is not successful I Need to keep them on the same page and show the error message.

Also   I have 2 options forgot user name and forgot password I need to incorporate that within the same popup so it slides and another form is shown
<li class="login-link"><a href="#" data-toggle="modal" data-target="#myModal">Login</a></li>

<div id="myModal" class="modal fade" role="dialog">
			<div class="modal-dialog">
			    <!-- Modal content-->
			    <div class="modal-content">
			    	<div class="modal-header">
			        	<button type="button" class="close" data-dismiss="modal">&times;</button>
						<h2 class="modal-title">Account Login</h2>
			    	</div>
					<div class="modal-body">
						 <form data-toggle="validator" role="form">
			        	<h3>Welcome to I Drive Smart. Please log-in to access your account.</h3>
			        	<div class="form-group">
			        		<input class="modal-username" type="text" name="firstname" class="form-control" data-error="Please enter name field." placeholder="Username" required="required">
			        			<div class="help-block with-errors"></div>
			        	</div>
			        	<div class="form-group">
			        		<input class="modal-password" type="password" 

Open in new window

0
Hi,

I am hoping someone can help me with an issue I am having whilst using Jquery and Classic ASP.

This code works perfectly..


  <script type="text/javascript">

    $(document).ready(function() {
             $('ul.sf-menu').sooperfish();
    });

</script>


BUT as soon as I add in the code for my ajax form submit it does not work..


  <script type="text/javascript">
    $(document).ready(function() {
       
        
         $('#submitButton').click(function() {
    $.ajax({
            type: "POST",
            url: "test.asp",
            data:  $("#form1").serialize(),
            cache: false,
            dataType: "html",
            success: function(responseText){
                alert(responseText);
            },
            error: function(resposeText){
                alert(resposeText);
            },
        });

    return false;
});

        
             $('ul.sf-menu').sooperfish();
 
    });
0

AJAX

12K

Solutions

7K

Contributors

Asynchronous JavaScript and XML (AJAX) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. HTML and CSS can be used in combination to mark up and style information. The Document Object Model (DOM) is accessed with JavaScript to dynamically display and allow interaction with the information presented.