[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

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 calling a WEB API method with parameters from Jquery.
When i run in debug mode on the WEB API side, the parameter always appears null.

On the client side, when the value in the dropdown changes, i call the WEB API method. I have an alert there and i can see the proper value.

Why is the parameter showing up as null on the WEB API side?

My Web API code:
  [EnableCors(origins: "*", headers: "*", methods: "*", SupportsCredentials = true)]
        [Route("api/Services/GetAllServiceItemsForSelectedProgram")]
        [HttpPost]
        public IEnumerable<ServiceItems> GetAllServiceItemsForSelectedProgram(List<LoginParameters> loginParam)
        {
            
            List<ServiceItems> retSvcItem = new List<ServiceItems>();
            object cidString = null;
            //
         }

Open in new window


Jquery Ajax call:
function GetSvcItemsForSelectedProgram(selectProgID) {
            
            alert(selectProgID.value); // value coming good here
            $.ajax({
                type: 'POST',
                url: '/api/Services/GetAllServiceItemsForSelectedProgram',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ UserName: 'jeri', CompanyID: 'Shah' , ServiceProgramID : selectProgID.value }),
                success: function (data) {
                    $.each(data, function (i, item) {
                        $('#ddSvcProg').append('<option value="' + item.ServiceProgramID + '">' + item.ServiceProgram + '</option>');
                    });
                },
                failure: function (data) {
                },
                error: function (data) {
                }
            });
        }

Open in new window


Internet explorer - developer tools:
I can see the parameters that i sent and the response is 200.
WebApiParams.pngThanks in Advance
0
CompTIA Network+
LVL 12
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

I'm trying call this following function in this ajax call,  var myReturn = processLinkedDocuments(reportId, localInvoiceFormatType); but is skipping it at every single time. Not sure if it's because I have it between some if/Statement but no luck... It never call the processLinkedDocuments function

 $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: '@Url.Action("PrintInvoiceStoreData", "InvoicePrinting")',
                    data: data,
                    success: function (response) {
                        if (response.Success) {
                            reportId = response.Message;

                            var reportCount = 0;
                            if ($('#s3foCallAheadList').prop('checked')) {
                                reportCount++;
                                var url = '@printInvoicesCallAheadReportUrl'.replace("CBNR", reportId);
                                console.log("test1");
                                window.open(url);
                            }

                            if ($('#s3foSchedule').prop('checked')) {
                                reportCount++;
                                var url = '@printInvoicesScheduleUrl'.replace("CBNR", reportId);
                                console.log("test2");
                                window.open(url);
                            }

                            if ($('#s3foWorksheet').prop('checked')) {

Open in new window

0
Hi- I am reworking an email form that was using server side script to client side. The issue, is that the Javascript navigation does not working correctly with the new Ajax scripts added to page, but if you hit refresh in browser, then the navigation seems to work ok. I am thinking perhaps there is a need to force reload the javascript after the new ajax based scripts load.

The page is here: http://dev.alphagraphicsseattle.com/contact.aspx

The new Ajax code added to the page is here (and we should not alter this vendor supplied code:

<!-- XMPL library -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link type="text/css" href="https://ajax.xmcircle.com/ajax/libs/xmpl/1.9.1/xmp/css/xmp.css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="https://ajax.xmcircle.com/ajax/libs/xmpl/1.9.1/xmp/js/xmp.min.js"></script>
<script type="text/javascript" src="https://cdn.121.ag/sem/ag/skin2/xmpcfg/2gagsemhttps/xmpcfg.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.121.ag/sem/ag/skin2/css/xmpl.css" />
<!-- XMPL library -->

Open in new window


The javascript that manages the navigation style is here:

http://dev.alphagraphicsseattle.com/js/main092718.js

Attached are two screens. One shows how the navigation is not wide enough on page load / before refresh. The other screen shows how the navigation should look / after refresh.

I've tried moving the scripts around in the header, putting them after the body, added defer or async to the javascript lines. If there is a change to main092718.js, that is possible for us to add, but the other ajax scripts, we cannot change.

Is there some way to force the main092718.js to re initialize after ajax scripts or is there something to change in main092718.js? main092718.js has been working forever ok, but the addition of the new scripts has caused issues. Thank you for any direction.  Mark
before-refresh-notworking.png
after-refresh-working.png
0
Hello,

I am trying to call a WCF Service from Jquery.
When i run the application as of now, it goes into error.
All i get is :         XHR: [object Object]

Earlier i was getting CORS issues.
I Included "            "Access-Control-Allow-Origin" under Application_Beginrequest of global.asax file.


Just to make sure the service is working good, I tried calling the service from a server side button control click and it works good and returns the data.
However, when i call it form Jquery, it goes into error and does nothing.

Can you point out what is wrong with this code?  Why is it failing.



Service

namespace EnrSvcOut
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IServiceEnrollmentOutcome
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetServicePrograms")]
        List<SvcEnrOutProgram> GetServicePrograms();
    }
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }

Open in new window

1
i have page to add new package with inputs and i have multi row dynamic create row for more details to this package inside this page

and also i have multi image uploader the same idea for invoice but add to this multi images

i have this photos to help you think my case
newpackage.php

<?php include "header.php"; ?>      
		<?php

			/// validate vars
										
			$num=" SELECT MAX( package_id ) as package_id FROM packages ";
			$query=mysqli_query($connect,$num);
			if($query){
				$row = mysqli_fetch_array($query);
				if($row){
					$max= $row['package_id'];
					if($max > 500){
						$package_id= $max + 1 ;
					}
					else{
						$first= 500 ;
						$package_id= $max + 501 ;
					}
					$filter_package_id=$package_id;
				}
			}
		?>

		<script src="../tinymce/tinymce.min.js"></script>
			<script>
			tinymce.init({
			selector: '.mytextarea'
			});
		</script>
      <!-- Right side column. Contains the navbar and content of the page -->
      <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1>
            Packages
            <small>Control panel</small>
          </h1>
          
        </section>

        <!-- Main content -->
        <section class="content">
          
          <!-- Main row -->
          <div class="row">
            <!-- Left col -->
            <section class="col-lg-12 connectedSortable">
              

              <!-- quick email widget -->
    

Open in new window

1
when I submit sign in form then I got a pop "403 Forbidden. Please reload and try again. Thank you!!"

                                                                                                                                OK


I am working CodeIgniter project. I think this is the problem with Ajax.  So, could anyone help me out how to get this?
ajax.PNG
0
In this example I try to read and save the textarea data with HTML content (tables) the code saves text for example: "Ok" this text if it is saved but it contains HTML tables the changes of the editor are not saved inside the database.

I think the problem is to send HTML content with tables by POST and save it as special characters.

The example is simple, show text in the editor with tables, edit and save the changes in the database.


///////////////// SCRIPTS

<script> ///////////////// SAVE DATA
	$(document).on('ready',function(){
	$('#btn-send').click(function(){
       var content = tinyMCE.activeEditor.getContent({format : 'raw'});
       $('input[name=datatext]').val(content);
       tinyMCE.triggerSave();
		var url = "update.php";                                      
		$.ajax({                        
		   type: "POST",                 
		   url: url,                    
		   data: $("#form").serialize(),
		   success: function(data)            
		   {
                        M.toast({html: data})
		   }
	       });   
	  });
	});
</script>

<script> ///////////////// LOAD DATA ON EDITOR
    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, options);
  });
    $(document).ready(function(){
    $('select').formSelect();
    $('body').on('change', '#menu_template', function() { 
	       $('input[name=templates_id]').val($(this).val());
	       

Open in new window

0
do you know any ajax javascript codes i can use when a button is clicked? I hope to gray out the background and have animated refreshing round loading for 3 seconds., and hope that work well for both desktop and phone..

THanks
0
Hello guys good evening... I have dataTable with Drop Down sorting using their unique ID's
 i want to filter dataS to table by Branch... How can I achieved it using server side pdo jquery here is my code

Drop Down
<label>Branch</label>
<select id="branch" class="form-control">
<option value="">Select Branch</option>
<option value="1'">First Branch</option>
<option value="2'">Second Branch</option>
<option value="3'">Third Branch</option>
</select>
<!----Table Item Data------>
<br/>
		<div class="container box" style="width:100%;">
			<div class="table-responsive">		
				<table id="itemdata" class="table table-bordered table-striped" width="100%">
					<thead>
						<tr>
						<th width="10%">Branch</td>
						<th width="10%">Outlet</td>
						<th width="15%">User</td>
						<th width="15%">Item</td>
						<th width="10%">Brand</td>
						<th width="10%">Serial No.</td>
						<th width="10%">Purchase Date</td>
						<th width="20%">Remarks</td>
						</tr>
					</thead>
					<tfoot>
						<tr>
						<th>Branch</td>
						<th>Outlet</td>
						<th>User</td>
						<th>Item</td>
						<th>Brand</td>
						<th>Serial No.</td>
						<th>Purchase Date</td>
						<th>Remarks</td>
						</tr>
					</tfoot>
				</table>
			</div>
		</div>

<script>
$(document).ready(function () {
	var dataTable = $('#itemdata').DataTable({
		"dom": '<"#buttons">lrti<"clear">',
		"bFilter": true,
		"bInfo": false,
		"scrollY":        "50%",
		"footer": true,
		"header": true,
        

Open in new window

0
I have a textbox field. User can type a desire keyword and then click on Search button or Press ENTER key.This will call a JS function which actually runs an AJAX code to perform a search

Also the keywords are appended with browser url like :
http://www.mydomain.com/search?keywords=2018
(I have a short js code for this which append keywords with url)


The Issue:

If user directly open this url
http://www.mydomain.com/search?keywords=2018
Then search function is not called.

Also if user change the search keywords like
http://www.mydomain.com/search?keywords=hello
Then search function must be called with these parameters

I want that user can also enter  search keywords via the URL also

Here is my code

jQuery("#SearchKeyword").keypress(function(e) {
    if(e.which == 13) {
        inputNewsSearch();    
    }
});

Open in new window


And this is the function code

function inputNewsSearch(){

    var SearchKeyword = jQuery("#SearchKeyword").val();	
	
            jQuery.ajax({
        type: "POST",
		url: base_path+'sites/all/themes/nexus/templates/news-search.php?',	
        data: {SearchKeyword:SearchKeyword,path_base:path_base,lang_name:lang_name},
        async: true,

        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status);
            alert(textStatus);
            alert(errorThrown);
        },
        success: function(result) {
			
		if (history.pushState)
		{
          var newurl = 

Open in new window

0
OWASP: Forgery and Phishing
LVL 12
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Populated Dropdown data is not inserting into database table

<div id="div5">
                <input type="text" placeholder="Sub Category Name" required="" id="subcatname" name="subcatname" />
    <script>

        $(document).ready(function(){

        	 $.ajax({
              type: "Post",
              url: "getAttribute.php",
              success: function(data) {
                    var obj = $.parseJSON(data);      
                    var result = "<select id="+ this['catname'] + " ><option>select Parent Category</option>";
                    $.each(obj, function() {
                        result = result + "<option value=" + this['catname'] + ">"+ this['catname'] +"</option>" ;
                    });
                    result = result + "</select>"
                    $("#result1").html(result);
              }
        }); 
            $("#subcat").click(function(e){
                   e.preventDefault();
                //var color=$("#color").val();
                var subcatname=$("#subcatname").val();
                var subcat=$("#subcat").val();
                 var catname=$("#catname").val();
                
                $.ajax({
                    url:'color.php',
                    method:'POST',
                    data:{
                       
                       subcatname:subcatname,
                        subcat:subcat,
                        catname:catname
                    },
                   success:function(data){
   

Open in new window

0
Hi, Experts, I need to know how it's possible to include in the manifest="offline.manifest" a messages from the server computer via Ajax and that message will store at the same time in the session storage and will be used during offline. I'm trying to develop an offline browser but getting difficult how to achieve that goal.  I used body onload event to trigger the Ajax and obtain the messages from the server thru ASP. <body onload="return GetMsg()"> My goal here is to retain or include the messages in the session storage and be used during offline. Any help please!  

<script>var msg;</script>
<script>
function GetMsg()
{
    debugger;
    var str = "E"
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() 
        {
          debugger;
            if (this.readyState == 4 && this.status == 200) 
            {
                msg = this.responseText;
            }
        };
        xmlhttp.open("POST", "GetHint.asp?q=" + str, true);
        xmlhttp.send();
    } 
}

</script>

Open in new window


The offline.manifest
CACHE MANIFEST
styles.css
jquery-1.4.min.js
offline.js
index.html

Open in new window

0
Hello guys I'm having trouble sending data via aJax post to other page.
my code explain it all how might it supposedly works.

I want to send data from test.php to page.php while page document loads and dispaly also page.php to test.php if it really works.
To make it short how can I echo data:{tablename:tablename} to page.php

Here is my code
test.php
<?php
include ('include/head.php');
?>
<html>
<body>
<div class"showme" id="showme"></div>
</body>
</html>
<script>
$(document).ready(function(){
var tablename = "tbl_released";
{
	$.ajax
				({
					url:'page.php',
					method:'POST',
					data:{tablename:tablename},
					success:function(data){
					
					 }    
				});
				$("#showme").load("page.php");
			}
});
</script>

Open in new window

page.php
<?php
if(isset($_POST["tablename"])){
echo $_POST["tablename"];
}
?>
<html>
<body>
<h1>I am page.php</h1>
</body>
</html>

Open in new window

0
I want to position an AJAX post in the context of a loop. The challenge is grabbing a value that's coming from the previous POST.

How could I pull that off?

Here's what I've got so far:

First off, on the main page, the user clicks on a button and that "gets" the hello.php page:

$(document).ready(function() {
	
	$('.print_forms').click(function() {
		var empID = $(this).data('empid');
		var hID=$(this).data('hid');
		var itemSel=$(this).data('item_sel');
		var cpID=$(this).data('cpid');
		var orderID=$(this).data('orderid');
		var quantity=$(this).data('quantity');
		var primeID=$(this).data('prime_id');
		var laps=$(this).data('laps');
		//alert(empID);
		$.get('hello.php?empID='+empID+'&hID='+hID+'&item_sel='+itemSel+'&cpID='+cpID+'&orderID='+orderID+'&quantity='+quantity+'&primeID='+primeID+'&laps='+laps,
		function(data) {
			$('.centered').show();	
			$('.centered').html(data);
		});
	});
		
});

Open in new window


The "hello.php" page has some minimal HTML that displays a loading graphic. At the bottom of that page is where I'm running into the challenge...

var laps=<?php echo $laps-1;?>;
		for(i=1;  i<=laps; i++)
		{
			setTimeout(function() {
				var out = {
				'empID': <?php echo $empID;?>,
				'hID' : <?php echo $hID;?>,
				'cpID' : <?php echo $cpID;?>,
				'orderID': <?php echo $orderID;?>, 
				'quantity':<?php echo $quantity;?>,
				'PrimeID': <?php echo $bob;?>, 
				'laps':<?php echo $laps-2;?>
				};
				$.post("hello_again.php?PrimeID=", out, function(data) {
					console.log(PrimeID);
					$('#gear_text').html(data);
				});
			},2000);

Open in new window


Can you smell what I'm cooking?

The idea is that I've got a known number of "laps" that I have to complete. Each lap goes out and "GETS" the next round of records based on the previous PrimeID.

THAT's my struggle!

How do I get the most recent PrimeID - the value that's arriving in the context of the "data" returning from my POST?

Any ideas?
0
The codes below is extracted from mvc razor view page / c#.
My question is how to pass pair name/value back  to mvc controller.

Thanks,


<script>
        function Validator() {
            return true;
        }
        function UpdateEventCost() {
            if (Validator() == true) {
                var totalCount = document.getElementById("totalcount").value;
                alert("Success");
                var inputs = document.getElementsByTagName("input");
                for(x=0; x<=inputs.length;x++)
                {
                    var id_name = inputs[x].getAttribute("id");
                    var id_value = document.getElementById(id_name).value;
                }
                //window.location.href = "/Home/MotorhomeEdit/15";
            }
            else {
                alert("Error");
            }
        }
</script>

Open in new window

0
Ajax Success callback doesn't work.
Hello this is my second question i have problem with success callback of my ajax function... it doesn't reload my data table after deleting rows... how can I correct it my code is
<script>
        $(document).on('click', '.delete', function() {
            var that = this;
            swal({
                title: "Are you sure?",
                text: "You will not be able to recover this imaginary file!",
                type: "warning",
                buttons: true,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                closeOnConfirm: false
            }).then(function(yes) {
                if (yes) {
                    var id = $(that).attr("id");
                    $.ajax({
                        url: "delete.php",
                        method: "POST",
                        data: {id: id},
                        success: function (data) {
                        dataTable.ajax.reload();
                        }
                    });
                }
                else {
                    return false;
                }
            })
        });
    </script>

Open in new window

my success code
                        success: function (data) {
                        dataTable.ajax.reload();
                        }

Open in new window

How Can I correct this guys?
0
I'm new to mysql and need some help. I have populated a multi-select drop down with my first query. The dropdown populated correctly and I want to use the value or values from the dropdown to get results from a second query. I will try to explain some more.

I have a multi select dropdown named students that is populated with Names and values that are numbers. I want to select one, two or all and use those values in a second query. The dropdown will have values like 390, 234, 5421, 461. If you look at the query below you will see the student_id = 461 that value is what I want to get from the dropdown. This query works if I place in the student_id.

SELECT *, student_id, SUM(handled) FROM stats WHERE student_id = 461

From there I
echo "Handled: " . $row["SUM(handled)"]. "";
and that works just fine.

Thanks for any help.
0
AJAX call to insert data into MYSQL database.  While testing I found the data was not being saved to the database.  I found that there was an error the SQL command.  How can I trap the SQL error so I can return a response to the AJAX call and know if the data was successfully saved to the database?

My dode is as follows:

Ajax call:

<script>
 <!-- Ajax call for save Work Done record -->
      function ResolveTicket() {
                  // Create our XMLHttpRequest object
                  var hr = new XMLHttpRequest();
                  // Create some variables we need to send to our PHP file
                  var url = "ResolveTicketSV.php";
                  var RESTicketNum = document.getElementById("RESTicketNum").value;
                  var RESTicketWD = document.getElementById("RESTicketWD").value;
                                    
                  var vars ="RESTicketNum="+RESTicketNum +"&RESTicketWD="+RESTicketWD;
                              
                  hr.open("POST", url, true);
                  // Set content type header information for sending url encoded variables in the request
                  hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                  // Access the onreadystatechange event for the XMLHttpRequest object
                  hr.onreadystatechange = function() {
                        if(hr.readyState == 4 && hr.status == 200) {
                              var return_data = hr.responseText;
                              // Check Results            
                                    // Trim Return Data
                                    var str = return_data.trim();
                                                            
                              document.getElementById("RESTicketNum").value = "";
                              document.getElementById("RESTicketDate").value = "";
                              …
0
Checkout this link for DEMO:

http://science-emporium.com.pk/map-test/test-map.php#

Open in new window



1) After opening of link you will see  a button. 'Show Map'. Click on it and a map will be displayed
2) You will see a selectbox with countries names.
3) Just select 'Russia' and you will see List of Projects on right side
4) Click on first project entitled 'Russia Project 1'.
5) A new div will open and in white background it shows the the Project Details

You will see Pagination at bottom with titles 'Next Project' and Previous Project.

How can i implement that paging with jquery. Click on Next Project will show next project and if no project exist then NExt PAge should be disabled.
As country 'RUSSIA' have 2 projects so clicking on next will show Russia Project 2.

Hope you got my point

Thanks
0
Starting with Angular 5
LVL 12
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

I am using a JS library to drag the controls on my PAGE to perform different functions. Checkout the demo by clicking on this link:
http://iamfashionphotographer.com/del/cb-m-1/final.html

Open in new window


1) When the page loads, see the right side and click on the icon.
2) Then you will see a snippet there. Just drag it on the page.
3) After that a button will be visible on PAge. Click on it and fill the form fields and fill the data with integer values and click on save.
4) The values are stored in DB.

What I want:
1) When you click on Table or button, you will notice that some additional buttons/controls  will appear. Click on the last icon which is a delete icon. You will notice that control will be deleted from the page. But values are still saved in Database.

I want that if user click on delete icon then its data from the table must be deleted from the database.

Need code help that on which event I will set the ajax call to delete data against that control.

Note: If user drag a control on page then following event is called:
	$('.ui-droppable').on('sortstop', function(e,i) {
	});

Open in new window


Looking for expert opinion

Thanks
0
I am getting 401 error with the below ajax call. How do I fix this issue?

full error: ..................................................................................................................
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:64327' is therefore not allowed access. The response had HTTP status code 401.
/...................................................................................................................................

var call = $.ajax({
           
            url: "https://name.com/web/lists('Call Management')/items?$select=Item_x0020_ID,State,Description&$filter=(Item_x0020_ID eq %27BBB000126%27)",
            type: "GET",
            dataType: "json",
            crossDomain: true,            
            headers: {
                Accept: "application/json;odata=verbose"
            },
            success: function (result) {
                alert("it worked");
               
            }
        });
0
I've got a dropdown box which is populated with ajax according to what option i choose from another dropdown. I need to duplicate the dropdown box keeping the same options loaded via ajax, this is what i've done o far. Many thanks for your help

This is the code to get tha value from the first dropbox and then use it for ajax

$('#flatGroup').on('change',function(){
        var countryID = $(this).val();
        console.log(countryID);
        if(countryID){
            $.ajax({
                type:'POST',
                url:'../controllers/ctrl_admin_group_table_app/ctrl_admin_get_building_table.php',
                data: {

                  group_id: countryID

                },

                success:function(html){
                    $('#flatTable-1').html(html);
                    $(".bs-select").selectpicker('refresh');

                }
            }); 
        }

    });

Open in new window


This is the code i'm using to close the second dropbox that receive the option from ajax

// start repeating form tabelle
        //Start repeating form group add limit
        var maxGroup1 = 5;
        //add more fields group
        var fieldGroup1= $(".fieldGroup1").clone();

        $(".addMore1").click(function() {

          var fgc1 = $('body').find('.fieldGroup1').length;

          if (fgc1 < maxGroup1) {

            var fieldHTML1 = '<div class="form-group fieldGroup1">' + fieldGroup1.html() + '<div class="col-md-1"><label 

Open in new window

0
I'm trying to include a live test for unique email and name.    The concept is to initially disable the submit button, and then re-initialize it if the credentials check-out to be unique. At this point clicking the submit button would initial the signup.php routines. Otherwise, the user would receive an error message to try again.

I have include the code "name_check' : 1," and "email_check' : 1," as ajax({ data arguments; because I've seen them in other code found online. But I don't understand what they mean: Is username_check a standard ajax function? I couldn't find any reference in the documentation.  Does this code assign the value 1 to username_check?

$('document').ready(function(){

    let name_state = false;
    let email_state = false;

    $("input[type=submit]").attr('disabled','disabled');


    // Verify user name is unique in database
    //
    $('#name').on('blur', function(){
        let name = $('#name').val();
        if (name == '') {
            name_state = false;
            return;
        }
        $.ajax({
            url: 'check_credentials.php',
            type: 'post',
            data: {
                'username_check' : 1,
                'name' : name,
            });
            .done function(response){
                if (response == 'taken' ) {
                    name_state = false;
                } else if (response == 'not_taken') {
                    name_state = true;
                }
            }
        });
    

Open in new window

0
Hey all I am using the following code on my local machine to give me a temporary WCF service:
    using System;
    using System.Windows.Forms;
    using System.ServiceModel;
    using TestService;
    
    namespace TestClient
    {
        public partial class Form1 : Form
        {
            IService1 patientSvc = null;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2202/PatientService"));
                NetTcpBinding binding = new NetTcpBinding();
                ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
                patientSvc = factory.CreateChannel();
            }
        }
    }

Open in new window

And the class1:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.Runtime.Serialization;
    
    namespace TestService
    {
        [ServiceContract()]
        public interface IService1
        {
            [OperationContract]
            Patient GetPatient(Int32 index);
    
            [OperationContract]
            void SetPatient(Int32 index, Patient patient);
        }
    
        [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
        public class PatientService : IService1
        {
            Patient[]

Open in new window

0
FORM: 'application.php'
ELEMENT:  a listbox named: 'lstgroup'

when the user select a item, the value (group_id)  is needed in sql WHERE clausule  (application.php)
variable 'group_id' is send with AJAX to application.php

-Function postgroupid() works fine
-$AJAX works fine
-Call php function sendgroupid() works fine

But the $_POST['group_id'] is empty and echo returns :"Hello php! But no group_id"
I spend a week to find a solution with all kind of suggestions from internet, but nothing helps me
Here is my code:

<script type="text/javascript">

   function postgroupid() {
   
    var x = document.getElementById("lstgroup").selectedIndex;
    var y = document.getElementById("lstgroup").options;
    var group_id = y[x].value;
    document.getElementById("edtgroupid").value=group_id;
       $.ajax({
                    type: "POST",
                    url : 'application.php';
                    data: { 'group_id' : group_id }
                   }).done(function(response){alert('succes');
                  }).fail(function(jqXHR, textStatus, errorThrown){
  alert('FAILED! ERROR: ' + errorThrown);
});
 
var result="<?php sendgroupid();?>";
alert(result);
return false;
  }
 
</script>

Open in new window

<?php
function sendgroupid()
{
if (isset($_POST['group_id']) && !empty($_POST['group_id'])) {
    echo $_POST['group_id'];
  }
   else
   {
   echo 'Hello php! But no group_id';
   }
}
?>

Open in new window

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.