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 need to submit a form prior to running Ajax to ensure the data is committed to the database when the Ajax command runs, how can I do this.

Originally, I thought I could set the focus on the submit button and click it, but this does not run sequentially and thus the Ajax command seemed to execute prior to the form data being committed.  What is the proper way to handle such a situation (save without closing modal and run next command in the sequence)?
0
Bootstrap 4: Exploring New Features
LVL 13
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Javascript - Character's Remaining.  I have a character's remaining script that is not working. The character count does not diminish and one can put in as many characters as they desire.

      
<script>
<!--
var limit = 300;
var left = limit;

function chlimit(what){
        var count = what.value.length;
        left = limit - count;
  
        if (left < 0) {
                what.value = what.value.substring(0,limit)
                placeholderobj.innerHTML = lengthleft
        }
        document.getElementById("div1").innerHTML="Characters Left = " + left;
}
// -->
              </script>
      
    </p>
            <p><h3>Post A Notice</h3>
<?php 

// Need the form functions script, which defines create_form_input():
require ('./includes/form_functions.inc.php');	
?>
</h3>
	
    <form action="PostANoticeYE.php" method="POST" accept-charset="utf-8">
        
         <p><label for="description" class="SmallHeading"><strong>Description</strong></label>
Please enter a brief description. You have up to 300 characters.
      <div id="div1">Characters Left = 300</div>
<?php create_form_input('description', "textarea", $PostANoticeYE_errors,"maxlength='300' onkeyup='return chlimit(this)' "); ?>

Open in new window

0
i have the following codes, and everything is working except the outhtml's size is too big but i do not know how big.
so I added some settings on webconfig but it is till not working.
Can you share with me whatelse I need to do to max the size of accepting data size?
[HttpPost]
        public JsonResult GetAgingReport(string invoicestartandenddate, string receiptstartandenddate, string chargecode)
        {
             
            Domain.Accounting.Report r = new Domain.Accounting.Report();             
            r.invoicestartdate = invoicestartdate;
            r.invoiceendate = invoiceenddate;
            r.receiptstartdate = receiptstartdate;
            r.receiptenddate = receiptenddate;
            r.chargecode = chargecode;
    
            MasterController.ServiceAccounting sa = new MasterController.ServiceAccounting();
            List<Domain.Accounting.Report> agingInDetail= sa.AgingInDetails(r);
            string returnStrInHTML = sa.AgingInDetailsInHTML(agingInDetail);
       
             r.outputHTML = returnStrInHTML;
            return Json(r, JsonRequestBehavior.AllowGet);
        }

Open in new window

  $.ajax({
                url: "/Accounting/GetAgingReport",
                datatype: "text",
                data:
                {
                    'invoicestartandenddate': invoicestartandenddatevalue,
                    'receiptstartandenddate': depositstartandenddatevalue,                   
                    'chargecode': chargecodevalue
                },
                type: "POST",
                success: function (data) {
                    var id = data.outputHTML;
                    alert("Success");
                         
                },
                error: function (error) {
                    alert("Error " + error);

                }
            }); 

Open in new window

 <system.web>
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.6.1"/>
    <httpRuntime targetFramework="4.6.1" executionTimeout="100000" maxRequestLength="214748364" />
  </system.web>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483647" />
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.webServer>
     <security>
      <requestFiltering>
        <requestLimits  maxAllowedContentLength="2147483647"  />
      </requestFiltering>
    </security>
  </system.webServer>

Open in new window

0
I want to create a button to email an ASP.NET MVC view. More specifically, I want to send content that is inside a div tag on the view. I have been searching for the past few weeks and am running into roadblocks. The best I came up with is using jquery and ajax. If you need to see the model, I can provide that as well. I'm sure I just screwed up the syntax or am trying to do something jquery and ajax can't do.

Portion of SupplyRequest view:

@model Intranet.Models.Product

@{ViewBag.Title = "Supply Request";}

<div class="col-md-12" id="Envelopes">
    <h2>
        Envelopes
    </h2>

    <p>
        Please enter the quantity and click submit email to send an email to the appropriate purchasing department.
    </p>
    <p>
        <table class="table" id="EnvelopeTable">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>@Html.DropDownList("Products", "Select Products")</td>
                    @*<td><input type=""</td>*@
                </tr>
            </tbody>
        </table>
    </p>
    <div>
        <p>
            <script>
            $(function () {
            //send email button click event
                $(".button").click(function (emailEnvContent) {
                //get the div content
                var divvalue = "<div id=Envelopes>" + $(".div").html() + "</div>";
          

Open in new window

0
Save CSV  file to temp directory.  How do I save these 2 files to a temp director?  I am saving 2 files and then want to zip them for download.  This is where I am but it's not working yet.

This file, download.php is called by an AJAX call.

I'm not writing the CSV files correctly and that is where I am stuck

 function download() {
        $con = getdb();

        $query = "SELECT * FROM ItpSurgeon";

        $output = fopen("test.csv", "w");

        $output = array('ID', 
            'Record ID ', 
            'Parent ID', 
            'User ID',
        );

        $result = mysqli_query($con, $query);
        while ($row = mysqli_fetch_assoc($result)) {
            fputcsv($output, $row);
        }
         $write = fopen("test.csv", "w");
         fwrite ($write,$row);
         fclose ($write);
         
    }
      function download_b() {
        $con = getdb();

        $query = "SELECT * FROM ItpChild";

        $output_b = fopen("test_b.csv", "w");

        $output = array('ID', 
            'Record ID ', 
            'Parent ID', 
            'User ID',
        );

        $result_b = mysqli_query($con, $query);
        while ($row_b = mysqli_fetch_assoc($result_b)) {
            fputcsv($output_b, $row_b);
        }
         $write_b = fopen("test_b.csv", "w");
         fwrite ($write_b,$row_b);
         fclose ($write_b);
         
    }
    download();  
    download_b();  

    $zip_name = 'csv.zip';
$zip = new ZipArchive;
$zip->open($zip_name, 

Open in new window

0
AJAX not working.  I'm not sure what I am doing wrong here.  If someone clicks "Bookmark This Page" I am sending an ajax request to store the url that was bookmarked.  Here is what I have but I don't believe I am passing the variable correctly.

<script>
 var urldata = window.location.href;

        $('#bookmark-this-page').click(function () {

            $.ajax({
                url: 'https://URL/js/bookmark.php',
                method: 'post',
                data: urldata,
            }).done(function () {

            });
        });
<?php>
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // turn on exceptions


$url = isset($_POST['data']) ? $_POST['data'] : "";

$date = date('m-d-Y');
//var_dump($url); die();
try {

    $sql = "INSERT INTO bookmark ( date, url) VALUES (:date, :url.);";

    $returns = $db->prepare($sql);

    $returns->execute([
        ':url' => $url,
        ':date' => $date,
    ]);
} catch (exception $e) {
     $e->getMessage();
}

Open in new window

0
I use bootstrap controls with ajax update panel in Modal

if I use the  postback the controls lose the css  , and the dropdownlist the search is disabled

this is the controls befor postback

this is the controls after postback
0
I am trying to build a Url.Action by passing the selected value in my dropdown.  How can I concatenate the url.action in the javascript section of my html file and have the browser recognize it as the relative path?

 url: '@Url.Action(selectedDDValue, "ListManager")' => does not work

var selectedDDValue = $("#SelectedDDLOptions :selected").val();

            $.ajax({
              url: '@Url.Action(selectedDDValue, "ListManager")',
                data: { listManager: selectedDDValue },
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",  
                error: function (err) {
                    alert(err.statusText);
                },
                success: function (result) {
                    var row = '';
                    $("#ddlNameColumn").html(selectedDDText);
                    $("#ddlNumberColumn").html("#");
                    $("#DDLList tbody").empty();

                    $.each(result, function (i) {

                        row += "<tr>" +
                            "<td>" + (i + 1) + "</td>" +
                            "<td style='display: none;'>" + result[i].ID + "</td>" +
                            "<td>" + result[i].Value + "</td>" +
                            "<td><a href='#' class='btn btn-danger btn-sm' onclick='DeleteListItem(\"" + result[i].ID + "\")'><i class='glyphicon glyphicon-trash'></i></a><a href='#' class='btn btn-warning btn-sm' 

Open in new window

0
I'm trying to use jQuery UI's "sortable" with Ajax. I have a test table With the columns ID (the auto-incrementing ID), sampleText (like "test item 1", "test item 2" etc.) and displayOrder which, theoretically, is an integer for the order the item should be displayed in. My code gets the information from the database and loops over it. When I drag and drop or use the up/down arrows, DevTools shows that the appropriate URL is being pinged but the table isn't updating and I'm not getting an alert (that the attempt was successful/there was an error.) This is the code for the page:

<cfquery name="qGetStuffToOrder" datasource="#APPLICATION.ds#">
	SELECT * FROM test_reordering 
	ORDER BY  displayOrder
</cfquery>
<table class="table table-striped">
	<tbody id="tabledivbody">
		<cfoutput query="qGetStuffToOrder">
		<tr class="sectionsid" id="sectionsid_#ID#">
			<td>#sampleText#</td>
			<cfif CurrentRow NEQ recordCount>
				<td><a href="javascript:void(0)" class="movedownlink"> <span class="glyphicon glyphicon-arrow-down">down</span></a></td>
			</cfif>
			<cfif CurrentRow NEQ 1>
				<td><a href="javascript:void(0)" class="moveuplink" > <span class="glyphicon glyphicon-arrow-up">up</span></a></td>
			</cfif>
		</tr>
		</cfoutput>
	</tbody>
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> 
<script>
		 $("#tabledivbody").sortable({
        items: 

Open in new window

0
I used to use a lot of JQUERY AJAX calls in our code, but recently I have been moving to using modern plain Javascript, such as fetch and promises.

A typical API block would look something like this:
$.ajax({
     url: '/piece.json',
     type: "GET",
     dataType: "json",
     success: function (data) {
         alert(data);
     }
});

Open in new window


I want to start writing my API calls using Promises, but I am a little confused, especially when it comes to chaining and error checking.

Could someone show me an example using chained promises that does the following psuedocode?

Example Login Functionality
let username = "john";
let password = "123";

if username doesn't exist
-- doesn't exits
     show message, return false
-- it exists
     check password. Is it correct?
     -- No
         Show error message, return
    -- Yes
         send then on their way to dashboard or something

Open in new window


So I know the basics of Promises, but when it comes to chaining something like that...

I know how to check them individually ( I think I am doing it correctly anyways ):

let getUserName = function(email){
    return new Promise(function(resolve, reject){
        // Apply any logic here, call our API
       //  Mock response
        if(email == "john@gmail.com"){
            resolve("found");
        }

        reject("Not found!");
    });
}

Open in new window


Then I could use my Promise like this, right?

getUserName("john@gmail.com").then((response) => {
    alert("Your username was: " + response);
    }, (e) => {
        // Handle error if we want to. BUT what error???
    alert("Error: " + e);
});

Open in new window


So even here, I am unsure of what error I am trapping. Am I just catching the reject here? Anyways...

Let's say I want to use that Promise, or something similar, but chain it as I described above. How?

Can someone help me with an example of a Promise based login using my psuedocode example code, to help me get going? Seeing it sure would help I think.

Thanks!

John
0
JavaScript Best Practices
LVL 13
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

What are your advices and technologies to design a Web portal UI for our customers to be robust, reliable, light and modern?
Note: The web portal will integrate with another Web applictions.
0
Hello Experts!

Please I want the ENTER KEY to perform the same function as the Submit button in the code below.

I've tried this:
$('.chat_message').keypress(function (e) {
	 var key = e.which;
	 if(key == 13)  // the enter key code
	  {
	    var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../controllers/insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
	    return false;  
	  }
	});

Open in new window

Each time I press ENTER KEY, the page reloads and bootstrap modal disappears.

modal_content += '<input name="chat_message_'+to_user_id+'" id="chat_message_'+to_user_id+'" placeholder="Type your message here ..." type="text" class="form-control chat_message" autocomplete="off"><span class="input-group-btn"><button name="send_chat" id="'+to_user_id+'" class="btn btn-sm btn-info no-radius send_chat" type="button"><i class="ace-icon fa fa-share"></i>Send</button></span></div></div>';

Open in new window


AJAX:
$(document).on('click', '.send_chat', function(){
        var to_user_id = $(this).attr('id');
        var chat_message = $('#chat_message_'+to_user_id).val();
        if (chat_message == ""){
            toastr.error("Your message is empty");
            return false;
         }
        var to_username = $('#to_username_'+to_user_id).val();
        $.ajax({
            url:"../../insert_chat",
            method:"POST",
            data:{to_username:to_username, to_user_id:to_user_id, chat_message:chat_message},
            success:function(data)
            {
                $('#chat_message_'+to_user_id).val('');
                $('#chat_history_'+to_user_id).html(data);
            }
        })
    });

Open in new window

0
Actually, Iam new to JQuery. I have a question that when we click the button. it doesn't go to that demo_test.txt file.Actually i had created demo_test.txt file locally.But for button click event the control doesn't went to there.
could you please help in regarding this.


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $.ajax({
                    url: "demo_test.txt", success: function (result) {
                        $("#div1").html(result);
                    }
                });
            });
        });
    </script>
   
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

    <button>Get External Content</button>
</body>
</html>
1
Hello Experts!

I need help on how to effectively upload image to the folder and insert the directory in MySQL Database.

I've tried in many ways. I was able to upload and insert but I don't like the way my code is handling it. I couldn't validate the image properly. I don't know how.

I tried the following but no response:

my html form (modal):
<div class="modal fade" id="modal-media">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Profile Picture</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    <span class="sr-only">Close</span>
                </button>
            </div>
            <form id="profilePic" action="user_img_controller.php" method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="col-md-12 text-center">
                        <img class="img-circle hs-img-disp profile-image" src="../assets/img/no-photo-3.png" alt="Profile Picture">
                        <div id="updateError"></div>
                        <input type="file" name="fileToUpload" id="fileToUpload" class="profile_img" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
                        <button id="fileSelect" class="btn btn-primary">Select 

Open in new window

1
Is there any working solution to block AJAX popup divs in Chrome and Firefox?
0
I would like to create a button on a php page that would table the records from the file on the server and load it into a mysql table.

This is a php page. It has records in the form of a table on the page. I will have the button id, the same as the file I would like to load into the mysql table. The files already reside on the server in a folder called uploaded.

Here is what I can do so far.

1. Capture the name of the file on the table with the id using jquery and ajax to push the file name to a php file that is to write the rows in the the csv file to the table.

A simple example with a field or two would be very helpful. All my fields are text as there is some characters that make the input from the csv file a little unpredictable.  

Please note the first row will have the field headings in the csv, so would need to start at row 2 and loop through the rest of the rows.
0
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
Starting with Angular 5
LVL 13
Starting with Angular 5

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

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
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
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

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.