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

i am finding it difficult to get radio button value in php using jquery ajax. every thing work fine if i comment the radio button variable in the php file  below, but if i remove the comment , nothing works. i have been on this for more then a day now. thanks for the help!!!

here is the html and jquery file :
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Form Validation</title>
	<style>
		.error{
			color:red;
		}
		
		.emai{
			border: solid 2px green;
		}
		
		.error2{
			color: green;
		}
		.textBoxError{
			border: solid 2px red;
	       color: red;
		
		}
	</style>
</head>
<body>



<form method="POST" id="form" name="form" action="">
    <label for="email" >Enter your email</label>
    <input id="email" class="emai" name="email">
	<p id="result"></p>
	<label for="email">Enter your first name</label>
	<input id="firstname" name="firstname">
	<label for="address">address</label>
	<input id="address" name="address">
	 Yes: <input type="radio" name="opt" value="yes">
    No: <input type="radio"  name="opt" value="No" checked="checked">
	<p id="result2"></p>
    <button id="submitform">Submit</button>
	<p id="result3"></p>
</form>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$( document ).ready(function() {
    $(function(){
        $('#submitform').on('click',function(e){
            e.preventDefault();  // do not allow the default form action
            var 

Open in new window

0
Independent Software Vendors: We Want Your Opinion
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I have a form that posts via javascript / jquery / ajax

I am trying to validate some fields server side before actual submission I was doing this to set the variable

myVar=$('#myVarFormID').val();

Open in new window


when I check the console, my variable is set appropriately and shows as intended, but when I go like this after setting it
nextFunction(myVar);

Open in new window


The function thinks the variable is [htmlInputElement]

I dont understand why the output shows fine but the script function wont take it in.  Is there something extra I need to do to pass this form element into a different function?
0
I've been using an iframe to embed content from a 3rd party vendor for over a year now but recently, particularly in Chrome, the content on the page is flashing and not fully loading, ever, so it seems. I haven't changed my code (see below) so I'm not sure what the problem is. I'm researching solutions but they all seem very complicated at that point, if they would even work. Some involve php and I'm not familiar with that AT ALL so I don't know if that is even an viable option. Please help?

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SFATouchTasks.aspx.cs" Inherits="SFATouchTasks" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .page
        {
            width: 1150px;
            height: 100%;
        }        
        .header
        {
            background: #FFF;
            width: 100%;
        }        
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div id="divEmbed" style="height: 300px;">
        <iframe id="ifm" name="ifm" width="100%" height="300%" frameborder="0" src="http://x.x.xxx.xxx:xxxx/app/main#/dashboards/589e1fed677202f430000031?embed=true"
            scrolling="auto" style="float: left;"></iframe>
    </div>
</asp:Content>

Open in new window

0
I'm trying to be 100% sure that I get responses from AJAX regarding the current state of the process.

I wrote the following as a simulation and its waiting and showing both success and complete at the same time.

$(function() {

	$('#submit').click(function(e){
		e.preventDefault();

		$.ajax({
			
			type: "POST",
			url: "ajaxPost.php",
			data: $("#aiForm").serialize(), // serializes the form's elements.

			success: function(){
				console.log('imStartingNow');
			},

			error: function(jqXHR, textStatus, errorThrown) {
				alert(errorThrown);
			},

			complete: function(){
				alert('im all done!');
			}

		});

	});

});

Open in new window


This all looks fine on the surface.  I am receiving the post variables as expected, however in real life, this post request does some processing that takes awhile so I want to know when it starts and when its done so I made my php script look like this to simulate a wait

<?php 
         sleep(5);
          echo "OK DONE";
?> 

Open in new window


What happens is that NOTHING occurs for the 5 second wait and then both success and complete fire off at the same time.

I was thinking it might be the sleep simulation that is causing the issue, but on my real page where its an actual post with some long processing afterward, it too will hang until done and show both success and complete.  I need some education on the proper way to set up this request where I can separate and identify the success vs the complete.
0
I am trying to get the id value in the url via ajax like this but don't know how to get the url parameter (id value in this case) via jquery.

$.ajax({
		url: 'functions/selected-cat.php',
		type: 'GET',
		dataType: 'json',
                data: {}
	})

Open in new window


When I try to console.log() the request I get a console error that says the id is an undefined index.


$safe_url = filter_var($_GET['id'], FILTER_SANITIZE_URL);

Open in new window


I put that into an array and json_encode it so that part is right. Is it not possible to get a url value in this way? Does it have to be done using javascript/jquery as opposed to php?
0
I have a page that generates this json output
{"address":"1234 East Main Street","city":"Anywhere"}

Open in new window


I created it using this PHP function on an index.php page
$address="1234 East Main Street";
$city="Anywhere";
echo json_encode(array('address'=>$address,'city'=>$city));

Open in new window


I then have the script shown below attached to the top of the index page that includes this ajax script that should be parsing and returning the values in my console.  I only get error messages

$(function() {

    $.ajax({
        url : 'index.php',
        type : 'POST',
        data : {"address":"address","city":"city"},
        dataType : 'json',
        success : function (result) {
           alert(result['address']); // alert box
           console.log(result['city']) // city in console
        },
        error : function () {
           alert("error");
        }
    });
});

Open in new window


Im very new to ajax so I'm hoping im just overlooking something simple but if there is a better way to do it altogether im open to that too. Thanks!
0
I am working on an AJAX application and I had the basic parts working.  However when I started thourough testing I started receiving HTTP/1.1 414 Request-URI Too Long.  I tried to convert it to use POST instead of GET but it is not working.    I have tried looking for examples online but I have not found one that makes it clear to me

The attached code works if I use:
 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
         handleupdaterec();
     }
var myParams = "updaterec.php?acctNBR=" + tableID + "&recID=" + recID + "&myXML=" + myXML;
xmlHttp.open("get", myParams , true);
xmlHttp.send(null)


but not if I use:
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        handleupdaterec();
    }
var myParams="acctNBR="+myAcct+"redID="+recID+"&myXML="+myXML2 ;
xmlHttp.open("post", 'trans.txt' , true);    
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(myParams);


In all the examples I saw 'trans.txt' was a url or filename.   What does this refer to?   I tried a non-existent file, an empty file and the calling web page.  Do I need to set special permissions on the file?  

I am receiving no error messages in the debugger or in the apache2/error_log.  I walk through the debugger line by line i see it executing xmlHttp.open,  xmlHttp.setRequestHeader and xmlHttp.send(myParams); but nothing happens.   one of the first lines in updaterec.php writes a record to the error log to let me know it got…
0
I have a select menu which values are populated via jquery/ajax/php. They are category names. I also have a single text field where users can add new categories on the same page. This is also done via jquery/ajax/php. When the user adds a new category, I want it to then show that newly added category on the dropdown menu without the user having to refresh the page.

This is the current php code I have which is called via ajax. I get the last inserted id and just to test it, I put it in the success message and alert that via jquery after inserting. This works fine.

// validation here. $message indicates that there was an error and validation fires

if($message) {
		
		$response['success'] = false;
		$response['message'] = $message;
		
	} else {
		
		$stmt = $link->prepare("INSERT INTO `product_cat` (`cat_name`) VALUES (?)");
		$stmt->bind_param("s", $_POST['category']);
		$stmt->execute();
		$stmt->close();
		
		$last_id = $link->insert_id;
		
		$stmt = $link->prepare("SELECT `cat_name` FROM `product_cat` WHERE `id` = ?");
		$stmt->bind_param("i", $last_id);
		$stmt->execute();
		$result = $stmt->get_result();
		if($result) {
			$row = $result->fetch_assoc();
			$cat_name = $row['cat_name'];
			
		}
		
		$response['success'] = true;
		$response['message'] = $cat_name;
		
		
	}
	
	echo json_encode($response);

Open in new window



The jQuery/ajax

function add_category() {

    $("#cat_error").hide();

    $("#add_category").on("click", function() {

        var 

Open in new window

0
i have an example program to do slides in asp.net and ajax. but the <asp:toolkitscriptmanager> is no longer there. what do i put there for it to work
below is the full code.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Slide</title>
    <style>
        .slideTitle
        {
            font-weight: bold;
            font-size: small;
            font-style: italic;
        }

        .slideDescription
        {
            font-size: small;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div style="text-align:center">
               
            <asp:Image ID="Image1" runat="server" Height="355px" ImageAlign="Left" ImageUrl="~/New/pic1.JPG" /><br />    
 <ajaxToolkit:SlideShowExtender ID="SlideShowExtender1" runat="server"
     TargetControlID="Image1"
     SlideShowServiceMethod="GetSlides"
     AutoPlay="true"
     ImageTitleLabelID="imageTitle"
     ImageDescriptionLabelID="imageDescription"
     NextButtonID="nextButton"
     PlayButtonText="Play"
     StopButtonText="Stop"
     PreviousButtonID="prevButton"
     PlayButtonID="playButton"
     Loop="true" />
           
        </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;…
0
I have a function that calls an AJAX request so I can have data returned.  Currently when I step through the code everything works, but when I get to the AJAX it steps over it but my web method (vb.net) does not fire.  I've double and triple checked my ajax url, added async:false, added  error handling, and even added the function inside of the function to try and get this to work.  If I expose the ajax outside of the function everything seems to work fine except it fires when the page loads and not when a button is pressed.


Below is my code:

function writeTable(SectionID, tableid,year) {


    var json = get_Data();
....

Open in new window


function get_Data() {
    $(function () {
        $.ajax({
            type: "Get",
            contentType: "application/json; charset=utf-8",
            url: "Test.aspx/Get_Results",
            data: JSON.stringify(),
            dataType: "json",
            async: "false",
            success: function (response) {
                alert('sucess');
            },

            error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
          

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE
LVL 4
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

I have a log in page, I want that if the status is canceled

<?php 
session_start();
require "../new_connection.php";

$email = isset($_POST['email']) ? $_POST['email'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;

if($email=="" || $password == "")
{
	header("Location: ../");
}
if(!empty($email) && !empty($password)) {
	
    $email = mysqli_real_escape_string($conn,$email);
    $password = mysqli_real_escape_string($conn,$password);
    //$pass = md5($password);
    
    $pass_validate = "SELECT * FROM users WHERE email = '$email'";
    $r_pass_validate = mysqli_query($conn,$pass_validate);
    if(mysqli_num_rows($r_pass_validate) == 0)
    {
    	 header("Location: ../login/?i=1");
    	die();
    
    }
    $row_pass_validate = mysqli_fetch_assoc($r_pass_validate);
    
    $hash = $row_pass_validate['password_digest'];
    
    if (password_verify($password, $hash)) {
    	
	$is_canceled = $row_pass_validate['is_canceled'];
    $zip = $row_pass_validate['delivery_zip'];
    $query_zip_code = "select * from ZipCodes where zip_code = '$zip'";
    $result_zip_code = mysqli_query($conn,$query_zip_code);
    if(mysqli_num_rows($result_zip_code) == 0)
    {
    	$id = $row_pass_validate['id'];
    	$_SESSION['id'] = $id;
    	header("Location: ../not-exist");
    	die();
    
    }
    $row_zip_code = mysqli_fetch_assoc($result_zip_code);
    $in_area = $row_zip_code['in_delivery_area'];
    if($in_area == '0')
    {
    	

Open in new window

0
Hi,

We have a problem with passing a variable from JS to Java class. Here is our code:

<script type="text/javascript">
function displayModal(buttonClicked, waitMessage) {

    $.ajax({
            //url:'xxrsv.oracle.apps.ibe.tcav2.EndCustomer',
            data:{value123: document.querySelector('#csu').value},
            type:'post',
            cache:false,
            success:function(){
                console.log('success');
                otherTransactionSubmit (buttonClicked); // bug 9860747, scnagara
            },
            error:function(){
                console.log('error');
            }
        }
    );
 }
</script>

<%@ page import="xxrsv.oracle.apps.ibe.tcav2.EndCustomer" %>

Open in new window


public class EndCustomer extends HttpServlet{

    public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {
        String id = request.getParameter("value123");
        EndCustomer.setEndCustomer(id);
    }

Open in new window


Please advise.
0
I have two links, one that says add colour and the other that says add size.

If I click on 'add colour' for example, then using jQuery, a hidden multi select menu appears and the user can choose colours. I then post these via ajax and perform server side validation. The issue I have is that if the user doesn't want to add any colours and they never click the 'add colour' link, the validation shouldn't fire as they don't have to select any colours. The validation should only occur if the colour multi select is visible.

<div class="form-group" id="colour">
	<select multiple data-title="Select colour" name="colour[]" class="selectpicker colour" data-style="btn-block">
		<option value="Red">Red</option>
		<option value="Green">Green</option>
		<option value="Blue">Blue</option>
		<option value="Orange">Orange</option>
		<option value="Black">Black</option>
		<option value="White">White</option>
	</select>
</div>

Open in new window



$.ajax({
			 url: 'functions/add-product.php',
			 type: 'POST',
			 dataType: 'json',
			 data: {product_name: product_name, price: price, description: description, form_token: form_token, colour: colour, size: size},
			 beforeSend: function() {
			 	$( "#add_product" ).prop("disabled", true).html("Submitting...");
		 	},
		 })

Open in new window


if(empty($_POST['colour'])) {
		
		$message .= "Select a colour <br />";
	}

Open in new window

0
Hi,

I'm having an problem with displaying the placeholder in my input textbox.
the problem is that I have to click on the textbox in order for me to see the text of the placeholder message.
instead what I want it to do is to show the placeholder text upon creating the textbox.

the problem is with this code:
placeholder="if Px = "
placeholder="32851,32568 "
it create the placeholder text but I have to click on the textbox to see it instead of have it show up when the text has been created.


this is what I have so far:

 <script language="javascript" type="text/javascript">

var counter = 0;
function AddConditionValue()
{
	
  var div = document.createElement('DIV');

  div.innerHTML = '<input placeholder="if Px = " style="width:310px;color:#555555;font-size:12px;" id="Conditiontxt' + counter + '" name = "Conditiontxt' + counter + 
    '" type="input" />' +

	'<input placeholder="32851,32568 " style="width:310px;color:#555555;font-size:12px;" id="Valuetxt' + counter + '" name = "Valuetxt' + counter + 
    '" type="input" />' +
	
    '<button style="width:105px;border: 0; background: transparent;cursor:pointer;" id="BtnConditionValue' + counter + '" type="button" ' + 
    'value="Remove" onclick = "RemoveTxt(this)" >' +
	
	'<img src="../images/DeleteTrashCan_Icon.jpg" alt="Previous" style="width:20px;" />' + 
	'</button>';

  document.getElementById("ConditionValueContainer").appendChild(div);

  counter++;
  
  $('#TextCount').val(counter);
  
} 

Open in new window

0
I have two buttons on my page. One to open a dialog to add new contacts. The second button opens a different dialog to edit contacts.
I can open and close the "Add Contacts" dialog no problem but when I click on the "Edit Contact" button the edit dialogue content is no longer displayed under tabs correctly.

If I refresh the page, I can open and close the "Edit Contact" dialog repeated times not problem but when I open the "Add Contacts" dialog the tabs in the add contact dialog this time no longer display correctly.   - So the problem works either way.

The add dialog code is:

$("#addagencyref-window").dialog(
                        {
                        autoOpen: false,
                        maxWidth:850,
                        maxHeight: 700,
                        width: 850,
                        height: 700,
                        draggable: true,
                        modal: true,
                        buttons: {
                          "Save": function () 
                          { 
                          $.post("./add_agencyreferral_process.php", $("#addagencyrefForm").serialize(), function(response)
                            {
                            if(!response)
                            {
                            location.reload(true);
                            $(this).dialog("close");
                            }
                            $("p#errors6").html(response);            
                            

Open in new window

0
Hello,
Im just trying to get to grips with using Modals and Bootstrap, can anyone look at :

http://dnx.org/eno/

And tell me why the button launches a modal, but the content is not replace with ajax content (from content.html )?


Thanks,
0
This function along with the PHP is sending the email.  What it is not doing is hiding the form and saying "Thanks"...so it is only half working!

The Function
<script>
$(function() {
  $("#myform").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: 'send_mail.php',
      dataType: 'json',
      data: $("#myform").serialize()
    }).done(function(d) {
      if (d.success==true) {
        $("#myform").hide();
        $("#results").text("Thanks!").show();
      }
    });
  });
});
</script>>

Open in new window


The PHP
<?php

$webmaster_email = "ds@mediascrubber.com";
$email_address = $_REQUEST['email_address'] ;

function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = '/$inject/i';
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}

if (!isset($_REQUEST['email_address'])) {
header( "Location: $feedback_page" );
}

elseif ( isInjected($email_address) ) {
header( "Location: $error_page" );
}

else {
mail( "$webmaster_email", "Feedback Form Results", "From: $email_address" );
header('Content-Type: application/json');
echo json_encode($data);

}
?>

Open in new window

0
I am using ajax to output filtered list results on a page. Is it possible to go back to the previous filtered results? Please note I am not wanting to go back to the previous url using history.back()

What would be the best way to do this? Would I need to use URL parameters?
0
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
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

I have a REST call using jQuery Ajax and it works fine on every browser except for IE11.  When I make this POST call,  I get back a 400 error and the data doesn't get written.

Any advise on this would be greatly appreciated.
0
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
I have been messing around creating an Ajax application using OpenSUSE, MariaDB, php and Firefox.   I had most of it working but now i can not get it to process the returned xml from my php application  

I have walked through the code using firebug and when i get to  xmlHttp.onreadystatechange = handleStatus(lineID);   handleStatus is called but after xmlHttp.send(null);  I just execute the next line (just a filler to set a breakpoint) and then exit the function, handleStatus is not called so I don't process the xml.  

If I examine the xmlHttp object it shows xmlHttp.readyState is 4 and the xml returned from chInfo.php

I have checked the error logs and there are no issues with my PHP code.  It just does a read of a database table, builds the xml and returns it.  

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><subBox><name>sub4</name></subBox><lines><select><ID>24</ID><desc><line1<desc></select></lines><response>

Any ideas on what I have done wrong?
Ajax1.txt
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

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.