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

getDeals();

    setTimeout(function () {
        timelineController();
    }, 300);

    createDefaultProps();
    loadSocialData();
  
    
    loadLeadData();

    loadActData();
    getJr();
    getJrTimeline();

Open in new window


here is my list of functions which each has a ajax function, how do i tell these functions to wait until ajax is complete ? and run in order
1
C++ 11 Fundamentals
LVL 12
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Quick overview of JSON tokens

please provide me a few sentences to explain JSON tokens. I have worked with JSON on various full stack positions, and wonder how JSON tokens fit in.

Thanks
0
Hello everybody,

I have a bunch of AJAX scripts that fetch and give data from and to PHP but the one I'm trying to make, I have no idea how to do it or which is the best way to do it. Here's the scenario:

  1. User selects 1st option form combo box and second combo box gets filled (AJAX)
  2. User selects 2nd option from second combo box and a table with check boxes appears at the bottom (AJAX)
  3. User selects/un-selects options (check boxes), hit SAVE and it supposedly saves the changes into the DB using AJAX and PHP

The problem is that the table rows with its check boxes are generated dynamically. Normally I would iterate through all the check boxes creating variables which would be passed as POST to a PHP function in another page using AJAX but, since in this case the check boxes are created dynamically I can't do that as I don't know the number of variables (check boxes) I will have to deal with or their IDs.

I've made a function in jQuery to fetch all check boxes generated in PHP and sent to the page and got this:

<input type=​"checkbox" data-render=​"switchery" id=​"author-11" name=​"author-11" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" id=​"author-12" name=​"author-12" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" id=​"author-13" name=​"author-13" data-theme=​"default" checked>​
<input type=​"checkbox" data-render=​"switchery" 

Open in new window

0
Hello everybody, hope you had a wonderful start for 2019.

I'm having problems with a jQuery/AJAX + PHP autofiller. I'm trying to fetch all the posibble results for the users in my DB, no matter what the user search for (could be username, name or last name). So far I've managed to fetch everything from my DB using PHP with the following script:

$sql
=
"
SELECT user_id, apellido, primer_nombre, nombre_usuario
FROM dbo.v3_usuarios
WHERE (nombre_usuario LIKE :parte_usuario)
OR (primer_nombre LIKE :parte_usuario2)
OR (apellido LIKE :parte_usuario3)
"
;

try
{
	
	$parte_usuario = '%' . strval($parte_usuario) . '%';
	
	$core = Core::getInstance();
	$stmt = $core->dbh->prepare($sql);
	$stmt->bindParam(':parte_usuario', $parte_usuario, PDO::PARAM_STR);
	$stmt->bindParam(':parte_usuario2', $parte_usuario, PDO::PARAM_STR);
	$stmt->bindParam(':parte_usuario3', $parte_usuario, PDO::PARAM_STR);
	
	if ($stmt->execute())
	{
		
		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		
		$usuarios = array();
		
		foreach ($result as $key => $value) {
			
			array_push($usuarios, $value['user_id'], $value['apellido'], $value['primer_nombre'], $value['nombre_usuario']);
			
		}
		
		echo json_encode($usuarios);
		
	} else { echo 'Couldn\'t connect to DB'; }

	$stmt = null;
	$core = null;

} catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); }

Open in new window

And I've managed to fetch it using AJAX with:

$('#usuario-buscar').typeahead({
	source: function (query, result) {
		$.ajax({
			url: "somepage.php",
			data: 'query=' + query,            
			dataType: "json",
			type: "POST",
			success: function (data) {
				// console.log(data);
				result($.map(data, function (item) {
					return item;
					//console.log(item);
				}));
			}
		});
	}
});

Open in new window

This is taken from an example in phppot.com and I can make it work with only one field, but I would like to show the results like "USERNAME - Lastname Fisrtname".

Any chance to get help with this? All the tries I've made repeat tens of times each result in the "dropdown" it creates for the textbox.

BTW the user_id, while I don't want it displayed in the auto fill dropdown, will be used to populate some hidden text box or something for the form to grab.

Thanks in advance!
1
I am trying to generate an HTML from an AJAX call, Below please find my code.

The content should display HELLO WORLD in bold. However, I am getting <strong>hello world</strong>

Any assistance is highly appreciated


AJAXHTML.CFM
============
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            $("#loadLink").click(function(e) {
                e.preventDefault();
                $.ajax({
                    type: "GET",
                    url: "ajaxHTML.cfc?method=createHTML",
                    contentType: "application/json; charset=utf-8",
                    dataType: "html",
                    success: function(message) {
                        $("#mydiv").html(message);
                    }
                });
            });
        });
    </script>
    
</head>

<body>
    <a href="" id="loadLink">Load Query</a>
    <!-- empty div to load dynamcically generated table into -->
    <div id="mydiv"></div>
</body>

Open in new window


AJAXHTML.CFC
============
<cfcomponent displayname="Generate HTML" output="false">


<cffunction name="createHTML" displayname="Create HTML" description="Creates HTML to output with jQuery." access="remote" output="false" returntype="string">

    <!--- SET VARIABLE TO RETURN --->
    <cfset VARIABLES.html = "">

    <!--- SAVE CONTENT --->

    <cfsavecontent variable="VARIABLES.html">
    	<strong>hello world</strong>
    </cfsavecontent>
    <!--- RETURN SAVED CONTENT --->
    <cfreturn VARIABLES.html>

</cffunction>

</cfcomponent>

Open in new window

0
Hello everybody,

I'm trying to figure out why something has stopped working after I changed from a MySQL DB to a MS-SQL DB. Everything else seems to work fine and it makes no sense, but this just stopped working. In the site, I have a modal that is shown when the user need to add a new tag name. Then it records the tag using AJAX and reloads the page to show the newly added tag name into the list. Here's what I've got:

Modal that is shown:
<div class="modal" id="modal-tag">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">Add new Tag</h4>
			</div>
			<div class="modal-body">
				<form id="form-new-tag">
					<fieldset>
						<div class="form-group row">
							<div class="col-md-12">
								<label for="tagNameInput">Tag name:</label><br>
								<input type="text" class="form-control" id="tagNameInput" name="tagNameInput" placeholder="" data-required="false" maxlength="30" />
							</div>
						</div>
						<button id="submittagbutton" name="submit" type="button" class="btn btn-sm btn-primary m-r-5">Save</button>
						<a href="javascript:;" class="btn btn-white" data-dismiss="modal">Cancel</a>
					</fieldset>
				</form>
			</div>
		</div>
	</div>
</div>

Open in new window

Ajax script:
<script>
	
	var division = <?php echo $userData['division']; ?>;
	var uid = <?php echo $userData['user_id']; ?>;
	
	$(document).ready(function() {
		
		$('#submittagbutton').click(function() {
			var newtag = $('#tagNameInput').val();
			if (newtag == "") { 
				return false;
			}
			
			var dataString = 'newtag='+ newtag +'&division='+ division +'&uid='+ uid;
			
			$.ajax({
				type: 'POST',
				url: 'joblog_addtag.php',
				data: dataString,
				success: function(d) {
					if (d.status == 'ok') {
						$('#modal-tag').modal('hide');
						location.reload();
					}
				},
				error: function() {
					alert("Error ! In fetching data.");
				}
			});
		});
	});
	
</script>

Open in new window

PHP page that is called by ajax:
require_once 'functions.php';
sec_session_start();

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

	header('Content-Type: application/json');
	if (v3AddNewTag($_POST['newtag'], $_POST['division'], $_POST['uid'])) {

		echo json_encode(array('status' => 'ok'));

	} else {

		return false;

	}

} else {

	header('HTTP/1.0 403 Forbidden');
	die('You are not allowed to access this script.');

}

Open in new window

And the PHP function is called:
function v3AddNewTag($tagText, $division, $uid) {

	$sql
	=
	"
	INSERT INTO dbo.v3_joblog_tags (tag, tag_division, tag_active, tag_created_by)
	VALUES (:tag, :tag_division, :tag_created_by, :tag_created_by)
	"
	;
	
	try
	{
		$tag = latinChars($tagText);
		$tag_active= 1;
		
		$core = Core::getInstance();
		$stmt = $core->dbh->prepare($sql);
		$stmt->bindParam(':tag', $tag, PDO::PARAM_STR);
		$stmt->bindParam(':tag_division', $division, PDO::PARAM_INT);
		$stmt->bindParam(':tag_active', $tag_active, PDO::PARAM_INT);
		$stmt->bindParam(':tag_created_by', $uid, PDO::PARAM_INT);
		
		if ($stmt->execute())
		{
			
			return true;
			
		} else { echo 'Couldn\'t connect to DB'; }

	} catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); }

}

Open in new window

Now, if I take the v3AddNewTag function and run it alone in a test page with hand-made data, it works so I know the INSERT query works. I've also tested the data sent to AJAX using alerts and it also works. What can be the problem?

Thanks a lot in advance and happy holidays!
0
Hello Experts!

Please what is wrong with my code? No return data in table but when I checked header (developer tool), I got something (attached).
I think the problem is from select option values and how they are being passed through AJAX. I said this because when I used hard-coded value  (1 or 0) in my PHP script and request AJAX call when page loads NOT onchange, the table populated correctly.

The HTML select:
<select name="user_status" id="user_status">
    <option value="">--User Status--</option>
    <option value="1">Active Users</option>
    <option value="0">Inactive Users</option>
</select>

Open in new window

AJAX:
var myTable = 
    $('#lockUsersTable').DataTable({
    "pageLength": 25,
    select: {style: 'multi'},
    columns: [
        { data: 'count' },
        { data: 'initials' },
        { data: 'username' },
        { data: 'user_type' },
        { data: 'status', orderable: false },
        { data: 'lock', orderable: false }
    ]
});

$('#user_status').on('change', function() {
    $('#tableResponse').html('<i class="ace-icon fa fa-spinner fa-spin blue bigger-115"></i> Please wait...');

    $.ajax({
        method : 'post',
        url : '../../lockUsers_Data',
        data : { userStatus : $('#user_status').val() },
        dataType : 'json',
    }).done(function(data) {
        myTable.clear().draw();
        myTable.rows.add(data).draw();

        var statusVal = $('#user_status').val();

        if ( myTable.data().any() ) {
   

Open in new window

1
Hello Experts!

I need help on the following.

I have a html Table ( with Child rows that show extra / detailed information ). See attached. There's a form in this Child Row where System Admin can send message to individual user. Because the table is populated via while loop, the Send button only recognizes the first row resulting in server to send back empty input error.

I want the AJAX to recognize the Send button just for the selected user.

array_button.pngXHR_Header.png
As you can see above, though I selected the user 3 (row 3), the onclick event picks inputs from row 1.

The form part of the Table:
<form method="post" id="msgForm" action="">
  <div class="form-group">
    <input type="hidden" name="to_user_id" id="to_user_id" value="<?= $user->UserId; ?>">
    <input type="hidden" name="to_initials" id="to_initials" value="<?= $user->Initials; ?>">
    <input type="hidden" name="from_user_id" id="from_user_id" value="<?= $session_Id; ?>">
    <input type="hidden" name="from_initials" id="from_initials" value="<?= $session_initials; ?>">
    <textarea class="width-100" name="msg_content" id="msg_content" resize="none" placeholder="Type message here…"></textarea>
  </div>

  <div class="hr hr-dotted"></div>

  <div class="clearfix">
    <label class="pull-left">
      <input type="checkbox" class="ace" />
      <span class="lbl"> Send me a copy</span>
    </label>
    <button class="pull-right btn btn-sm btn-primary btn-white 

Open in new window

1
Hello Experts!

I need help on the following:

I have a DataTable that is populated via AJAX. The're are four columns with text inputs for scores. So, each row has some associated text inputs to it (CA1, CA2, CA3 and Exam). The maximum scores for these inputs are 10, 10, 10 and 70 respectively.

I've already put in place a server-side validation that checks all these values. Now, I want a client side validation. Something like onblur or onkeyup for each input. I want an alert to trigger and inform the user of wrong input and focus / and add error class (border-color: red) on such input box immediately not until the submit button is clicked.

I believe it's easy for guru but I'm still learning. Thanks to Experts on EE.

On a single column input, I tried this but no luck.
<script>
function checkValue() {
  var value = document.getElementsByName('cass1[]');
     for (i=0; i<value.length; i++)
	 {
	    if (value[i].value > 10)
               {
	          alert('The value is gtreater than 10');		
	          return false;
	       }
         }
}
</script>

{
    orderable: false,
    "className": "table-readonly",
    render: function (data, type, row) {
    return '<input type="hidden" name="id[]" value="' + row.Enroll_ID + '"><input class="form-control input-sm" type="text" maxlength="2" name="cass1[' + row.Enroll_ID + ']" onkeyup="checkValue()" value="' + row.CA1 + '" ' + getReadonly() + '>';
	}
}

Open in new window

Here is my code:

Open in new window

1
Hello Experts!

I normally populate DataTable with the following combination. When a button is clicked, the table is populated through AJAX call as long as there's at least 1 row of data. But if there're no data in the table from MySQL, nothing happens. So, I want a message to return when there's no data coming from database.

Please help me manipulate this:

<?php 

require_once '../.../db_connection.php';

$stmt = $conn->prepare( "SELECT ... FROM ... WHERE ..." );
$stmt->bind_param( "ssssi", $_POST['session'], $_POST['term'], $_POST['class'], $_POST['subject'], $_POST['limit'] );
$stmt->execute();

$assessment = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
die( json_encode($assessment) );
?>

Open in new window



Here is my AJAX:
$('#loadStudents').click(function() {
   $.ajax({
   method : 'post',
   url : '../data/ass1_Data',
   data : { session : $('#session').val(), term : $('#term').val(), class : $('#c_taught').val(), subject : $('#s_taught').val(), limit : $('#process_limit').val(), },
   dataType : 'json',
   }).done(function(data) {
      myDt.clear().draw();
      myDt.rows.add(data).draw();
   });
});

Open in new window


Thank you in advance.
0
OWASP: Avoiding Hacker Tricks
LVL 12
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Hello Experts!

Please why am I getting
Notice: Undefined index: subject in C:\...\createTable.php on line 6
?
NOTE: I can populate the table using DataTable but I don't want to us DataTable for this. If you know how I can do populate HTML Table using AJAX, please help.
HTML Form:
<form method="post" id="enrollmentForm" action="">
   <div class=" form-group center">
      <input type="hidden" name="session" id="session" value="<?= $default_session ?>">
      <input type="hidden" name="term" id="term" value="<?= $default_term ?>">
         <select name="c_taught" id="c_taught">
	   <option value="">Select Class...</option>
	   <?php echo fill_class_box($conn); ?>
	</select>

       <select name="s_taught" id="s_taught">
	<option value="">Select Subject...</option>
	<?php echo fill_subject_box($conn); ?>
       </select>
   </div>
   <div class="form-group center">
      <button type="button" name="loadStudents" id="loadStudents" class="btn btn-sm btn-primary btn-white btn-round">
         <i class="ace-icon fa fa-refresh bigger-150 middle orange2"></i>
         <span class="bigger-110"> Load Students</span>
      </button>
   </div>
</form>

Open in new window


My Ajax:
$(document).ready(function(){
  $("#loadStudents").click(function(){
    //disable the submit button
    $(this).attr('disabled','true');$(this).css('cursor','not-allowed');$(this).html('Processing');
    $.ajax({
      method : 'post',
      url : 'createTable',
      data : { class : $('#c_taught').val(), subject : $('#s_taught').val() },
      data : 'json',
      success: function(data)
      {
      	$('#enrollTable').html(data);
        //enable the submit button
        $('#loadStudents').css('cursor','pointer');$('#loadStudents').html('Submit');$('#loadStudents').removeAttr('disabled');
      },
      
    }); 
  });
});

Open in new window

Then, createTable.php
<?php
session_start();

include('../../db_connection.php');

$s_taught = $_POST['subject'];

$stmt = $conn->prepare( "SELECT ... WHERE Class_Name = ? AND ".$s_taught." = 0 AND Total_Subjects < 12 AND Status = 1 ORDER BY Roll_No" );
$stmt->bind_param( "s", $_POST['class'] );
$stmt->execute();
$students = $stmt->get_result();

$data = array();

while ( $student = $students->fetch_object() ):

    $data[] = array(
        "roll_no" => $student->Roll_No,
        "student_id" => $student->Student_ID,
        "student_name" => $student->Student_Name,
    );

endwhile;

$response = array(
    "data" => $data,
);

echo json_encode($response);
    
?>

Open in new window


Thank you  for your help.
0
We were talking about replacing out Grid.MVC with jQuery DataTables.

Suppose we have 10 pages. Each page has a grid but goes to a different datasource to get the data. Different columns, etc.

The developer on our team mentioned something about having a generic jQuery/AJAX code .... only ONE ... for all the pages. How would that work? is he correct that we can only have one jQuery file?

Ex: User is on page1 and want to get data from table1.  If it's true that we can only have one jQuery code to make an AJAX call...how can we tell it to this is page1 and go to table1. Then, how can we tell it this is page2 and go to table2 to get data?
1
Is it possible to destory a bind on the DOM and recreate it ? let say i add data to a table from a Ajax request i would need to rebind that to the dom for the new inserted data ?
1
Hi Guys,
I am using asp.net mvc.
I built a method in  the backend that let me stream file and download to my dom:
Here is my backend method.

Public Function DownloadFiles(attachmentsSelected As String, zipFileName As String) As FilePathResult
        Dim obj As FileDownloads = New FileDownloads()
        ''get file list user choose to download
        Dim filesCol = obj.GetFile(attachmentsSelected).ToList()

        Dim fileSavePath As String = IO.Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/DownLoadAttachments"), zipFileName)
        Using stream = New FileStream(fileSavePath, FileMode.Create)
            Using ziparchive = New ZipArchive(stream, ZipArchiveMode.Create, True)

                For i As Integer = 0 To filesCol.Count - 1
                    'ziparchive.CreateEntryFromFile(filesCol(i).FilePath + "\" + filesCol(i).FileName, filesCol(i).FileName, CompressionLevel.Optimal)
                    ziparchive.CreateEntryFromFile(filesCol(i).FilePath, filesCol(i).FileName, CompressionLevel.Optimal)
                Next
            End Using
        End Using

        Return File(fileSavePath, "application/zip", "Attachments.zip")
    End Function

Open in new window


Now from the front end I do something like that.

 window.location = "/DocumentViewer/DownloadFiles?attachmentsSelected=" + func.downloadFilesList + "&zipFileName=" + uuid;

Open in new window


The issue I have with this approach is - I want to delete the file from my server after the client download it so I need another call to the server ..let's say with ajax and delete, but the problem is I can't predict the time when this URL finish the process of downloading in the backend

Does anyone have an idea how to do it? I was trying Promise but it doesn't really work in this scenario.

Thank you.,
0
Modal is not working after 1st page when click on "Change" button  in datatable bootstrap:



View Info Modal :
<div id="dataModal" class="modal fade">  
      <div class="modal-dialog">  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Customer Details</h4>  
                </div>  
                <div class="modal-body" id="customer_detail">  
                </div>  
                <div class="modal-footer">  
                     <button type="button" class="btn btn-gradient-light btn-fw" data-dismiss="modal">Close</button>  
                </div>  
           </div>  
      </div>  
 </div>

Open in new window


Change Info Modal:
 <div id="changeModal" class="modal fade">  
      <div class="modal-dialog">  
           <div class="modal-content">  
                <div class="modal-header">  
                     <button type="button" class="close" data-dismiss="modal">&times;</button>  
                     <h4 class="modal-title">Change Status</h4>  
                </div>  
                <div class="modal-body" id="change_detail">  
                </div>  
                <div class="modal-footer">  
                     <button type="button" class="btn btn-gradient-light btn-fw" data-dismiss="modal">Close</button>  
                </div>  
           </div>  
      </div>  
 </div> 

Open in new window


JQuery :
 $(document).ready(function(){  
      $('.view_data').click(function(){  
           var book_id = $(this).attr("id");  
           /*alert(employee_id);*/
           $.ajax({  
                url:"ajax/viewCustomer.php",  
                method:"post",  
                data:{book_id:book_id},  
                success:function(data){ 
                     $('#customer_detail').html(data);  
                     $('#dataModal').modal("show");  
                }  
           });  
      });  
 });
  $(document).ready(function(){  
      $('.change_data').click(function(){  
           var book_id = $(this).attr("id");
           $.ajax({  
                url:"ajax/updateServiceStatus.php",  
                method:"post",  
                data:{book_id:book_id},  
                success:function(data){ 
                     $('#change_detail').html(data);  
                     $('#changeModal').modal("show");  
                }  
           });  
      });  
 });

Open in new window

1
When I click on "Make Payment" button then only ajax run but paypal sandbox not works.
There should be 1st paypal will open and then email send after registration.

Paypal_url = https://www.sandbox.paypal.com/cgi-bin/webscr.
ajax id = registerform.

HTML Code:
.
.
.
<form method="POST" class="dzForm paypal form-inline" action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="registerform" id="registerform">
.
.
.
<input class="btn btn-medium btn-transparent-orange" type="submit" name="insert" value="Make Payment">

Open in new window

.
.
.
AJAX Code:
$("#registerform").submit(function(e) {
			e.preventDefault();
			$("#msg").html("");
			var name = $("#name").val();
			$("#submitbtn").prop('disabled', true);
			$.ajax({
				type: "POST",
				data: $("#registerform").serialize(),
				url: "php/register.php",
				cache: false,
				beforeSend: function (){
						$("#submitbtn").val('Sending..Please wait');
				},
				success: function (response) {
						if(response==1){
							$("#msg").html("Thank you "+name+" ! You have been registered successfully.");
							$("#submitbtn").prop('disabled', false);
							$("#submitbtn").val('Register Now');
							$("#registerform").trigger('reset')
						} else{
							$("#msg").html("<span style='color:red'>"+response+"</span>");
							$("#submitbtn").prop('disabled', false);
							$("#submitbtn").val('Register Now');
							$("#registerform").trigger('reset')
						}
				}
			});
			return false;
		});

Open in new window

0
I have jQuery/Javascript on my page at:
http://www.domain-a.com/page.html

...and I am trying to do a jQuery $.post to:
https://www.domain-b.com/script.asp

But I get this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...

On www.domain-b.com I have the following in web.config (this is an IIS server):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

Open in new window


...however, I still get the error. I don't have access to .htaccess or anything else on www.domain-a.com. Is it possible for me to resolve this issue, or is it not possible because I don't have access to the www.domain-a.com server? It isn't clear to me if I need to add Access Control to the server where the web page resides, or the server where the target script resides.

Thank you.
0
Here is a simple CSRF class I am using:

<?php
 
namespace Core;
 

/**
 * CSRF protection
 */
class CSRF
{
    /** 
     * Get and store a new CSRF token
     *
     * @return string  A 32-character token
     */
    public static function getToken()
    {   
        $token = new \App\Token();
        $value = $token->getValue();
        $_SESSION["csrf_token"] = $value;
 
        return $value;
    }
 
    /** 
     * Check the token value
     */
    public static function checkToken()
    {   
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ( ! isset($_POST['csrf_token'])) {
               header('HTTP/1.0 403 Forbidden');
               exit('Missing CSRF token');

            }
 
            // Get the token from the session and remove it
            $token = $_SESSION['csrf_token'] ?? '';
            unset($_SESSION['csrf_token']);
 
            if ($_POST['csrf_token'] != $token) {
                header('HTTP/1.0 403 Forbidden');
                exit('Invalid CSRF token');

            }   
        }   
    }   
}

Open in new window


Then I have the token in a hidden form field:

<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">

Open in new window


This is my controller:

 
   public function createAction()
    {
        if($_SERVER['REQUEST_METHOD'] === 'POST') {
            
            $response = [];
            
            $customer = new Customer();
            if($customer->save($_POST)) {
                
                $response['success'] = true;
                $response['message'] = 'Customer successfully added';
                
             } else {
                
                $response['success'] = false;
                $response['message'] = $customer->errors;
            }
            
            echo json_encode($response);
        }
    }

Open in new window


If I wasn't using Ajax and I just called that method in the controller like:

CSRF::checkToken();

Open in new window


then it works fine and the 403 occurs. But since I am using Ajax, the page just hangs and the error shows up in console. So, I click submit and the form validation takes place. If there are errors then I use jQuery /json to show the errors:

        .done(function (data) {
            if (!data.success) {

                unblockUI();
                $.each(data.message, function(index, item) {
                    $( '.alert-danger' ).append(item + "<br>").fadeIn();
                });

Open in new window


Is it possible to make the 403 happen or would I need to do something else? It is no good as is that the page just freezes up and the 403 error is shown in console. In theory, genuine users should never have this happen, but I still want to handle it more elegantly anyway.
0
Hi Guys,
I have implemented progress bar with js and html progress tag.

Here is my sample implementation

<progress id="progressBar" value="0" max="100" style="width:300px; height: 40px;"></progress>
    <span id='status'></span>

  function Progressbarsx(perc) {
      var bar = document.getElementById('progressBar');
      var status = document.getElementById('status');
      status.innerHTML = perc + "%";
      bar.value = perc;
      perc++;
      var sim = setTimeout("Progressbarsx("+ perc +")", 100);
      if(perc == 100){
          status.innerHTML = 100;
          clearTimeout(sim);
      }
    }
    var amountrun = 0
    Progressbarsx(amountrun)

Open in new window

:

That is working fine.
Now I have a scenario in my production environment when I run a lot of ajax call for returning data from server.

I used to using spinning bar that spin until ajax function finish, but now I want to show progress bar and calculate the time until the return come back. exactly like I show in my example.
Now I want to do something like that:

 $(document).ajaxStart(function (val) {
        //call to my progress bar in a real time 
    }).ajaxStop(function (val) {
        //end the call after ajax stop.
    });

Open in new window


Please, let me know what is the idea of doing something like that.

Thank you.
0
HTML5 and CSS3 Fundamentals
LVL 12
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Hello Experts!

Please, help. I don't know why this code is not opening modal to a specific record. It only opens the first record on the list. The second link shows the first record when clicked. If I refresh the page and click on the second link first, it shows nothing.

I already tested the id for each list, that is fine.

the message.php
<?php while ($message = $result->fetch_object()): 
  $timestamp = $message->msg_date;
  $date = new DateTime($timestamp);
  $date_posted = $date->format('d M Y h:i A');
?>
                                
<div class="content" id="noticeMessage">
  <a class="content-title" href="#"><?= $message->title; ?></a>
  <p class="content-date"><?= $message->category; ?> | <?= $date_posted; ?></p>
  <p class="content-body"><?= $message->description; ?></p>
  <a class="light-green feed-link learnMore" href="#" data-toggle="modal" data-target="#noticeModal" data-id='<?= $message->msg_id; ?>'>Learn more</a>
</div>
<?php endwhile; ?>

Open in new window

modal dialog:
<div class="modal fade" id="noticeModal" tabindex="-1" role="dialog" aria-labelledby="noticeModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title" id="noticeModalTitle">Message Content</h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div id="getNoticeContentDiv"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Open in new window

the modal gets data from: notice_modalForm.php:
<?php
require_once '../.../connect.php';

$query = $conn->prepare("SELECT * FROM tbl_message WHERE msg_id = ?");
$query->bind_param("i", $_POST['id']);
$query->execute();
$result = $query->get_result();
$message = $result->fetch_object();

?>

<div class="content">
	<a class="content-title"><?= $message->title; ?></a>
	<p class="content-date"><?= $message->category; ?> | <?= $message->msg_date; ?></p>
	<p class="content-body"><?= $message->description; ?></p>
	<p class="content-body"><?= $message->details; ?></p>
</div>

Open in new window

using this code:
$('#noticeMessage').on('click', '.learnMore', function(e) {
            e.preventDefault();
            $.ajax({
                url     : 'views/notice_modalForm',
                method  : 'post',
                data    : { id : $(this).data('id') }
                })
                .done(function(data) {
                    $('#getNoticeContentDiv').html(data);
                    $('#noticeModal').modal('show');
                });
            });   
            
        });

Open in new window

Thank you for your help
0
Screen-Shot-2018-10-29-at-11.10.05.png

              $(document).on('click', '#action-unSub', function(){
        $.ajax({
            url: "unsubscribe-manual.php",
            type: "POST",
            data: { email:<?=$v_item['CONTACT_EMAIL'];?> },
            success: function(html){
            
             
            },
            error: function(html){
               
            }
        });
    });

Open in new window


what is the issue ?
0
I am using Ajax to request the data. I am making an array and send it with json_encode so that I will receive the data in my Ajax Success function.
Now, here is my code:

$sql = "SELECT * FROM  mydata where id=15";		
			$rst = mysqli_query($conn,$sql) or die(mysqli_error($conn));					
			if (mysqli_num_rows($rst) > 0)
			{				
				while( $proj_gall_img = mysqli_fetch_array($rst) )
				{							
					$project_gallery_images[] = $proj_gall_img['img_name'];
					//$project_gallery_images.= $proj_gall_img['img_name']."|";
				}
				
			}
			
$projects_name[] = '<span data-id="' . $projects_row['id'].'" data-title="' . $projects_row['project_title'].'" data-detail="' . $projects_row['project_detail'].'" data-mimage="' . $projects_row['project_image'].'" data-mgallery="' . @$project_gallery_images.'"  class="li-txt" style="color:#ff0000;"><a id="myAnc" href="#">'.$projects_row['project_title'].'</a></span>';

Open in new window


The Problem:
I am easily fetched the value of following data attributes, data-id, data-title, data-detail, data-mimage but I am unable to get the value of data-mgallery in my ajax success function because this is an array.

In my this function I need to fetch this data:
jQuery('body').on('click', 'span.li-txt, span.li-txt2', function() {

var pid = jQuery(this).data('id');
var title = jQuery(this).data('title');
var detail = jQuery(this).data('detail');
var mimage = jQuery(this).data('mimage');	

var gallery = jQuery(this).data('mgallery');	
alert('length='+gallery.length);

Open in new window

The value of pid, title, detail and mimage retrieve successfully, but the value of gallery is Array. How to retrieve it?

Alternatively, how can I fetch the data in Ajax Success method?

Need help in this regard.

Thanks
0
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.

Thanks in Advance
0
I need to get information from a XML file where this file is auto upload every 30 seconds.
I want to show this information in a website.

Just to show an example, my website is a radio, and I want to show to users what music he listen.
0
I have the code below. I am trying to update the table when an attachment is being add and/or deleted.  The table is in a partial view.  The issue is that my model.Attachments is not being updated when I go to submit the entire request.  The table displays the row but the model isn't being updated with the new data.  What am I doing wrong?

<div class="form-group row">
                <div class="col-sm-6">
                    @Html.EditorFor(model => model.AttachmentsJSON, new { htmlAttributes = new { @class = "form-control" } })
                    <table class="table" id="ListofFiles">
                        <thead>
                            <tr>
                                <th>Filename</th>
                                <th>Attachment Type</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Model.Attachments.Count() != 0)
                            {
                                var idCount = 0;

                                foreach (var item in Model.Attachments)
                                {
                                    idCount = idCount + 1;
                                    <tr id="@idCount">
                                        <td>@item.Filename</td>
                                        <td>@item.AttachmentType.Type</td>
                                        <td>@item.Description</td>

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.