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

Hello there,

I don't know where the problem lies, for some reasons, the code bellow doesn't work.

Script:
<?php
require_once '../includes/connection.php';

function clean($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

if (! empty($_POST) ):

    $current_password = clean($_POST["current_password"]);
    $new_password = clean($_POST["new_password"]);
    $repeat_password = clean($_POST["repeat_password"]);
    $username = clean($_POST['username']);
    

    $userPass = $conn->prepare("SELECT Password FROM Users WHERE Username = ? LIMIT 1");
    $userPass->bind_param( "s", $username );
    $userPass->execute();
    $result = $userPass->get_result();
    $userPassword = $result->fetch_object();

    if ( $userPassword->Password == $current_password ):

        $query = "UPDATE Users SET Password = ? WHERE Username = ? ";
        $result = $conn->prepare($query);
        $result->bind_param( "ss", $new_password, $username );

        if ( $result->execute() ):

            $response = "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
                Password changed successfully.</div>";
            die( $response );

        else:

            $response = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span 

Open in new window

0
Cloud Class® Course: MCSA MCSE Windows Server 2012
LVL 12
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

I am listing a table which shows records from the database and each row has a checkbox with an ID value associated with it.

<label class="m-checkbox">
 <input type="checkbox" name="order_id[]" value="<?php echo sanitize($failed->order_id); ?>">
 <span></span>
</label>

Open in new window


Once the user has selected the checkboxes of the records they want to delete, the submit button is pressed and that triggers an ajax request.

$( '.delete-failed' ).on('click', function(e) {
    e.preventDefault();
    var form = $( '#delete-failed' ).serialize();
    $.ajax({
        url: url + '/TransactionsAjax/deleteFailedTransactions',
        type: 'POST',
        data: form,
        dataType: 'json',
        beforeSend: function() {
            $( 'delete-failed' ).prop('disabled', true);
        }
    })
    .done(function (data) {
        if(!data.success) {
            $( '.alert-danger' ).append(data.message).fadeIn();

        } else {


            $( '.alert-success' ).append(data.message).fadeIn();
        }
    })
            .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
            console.warn(jqXHR.responseText);
        });
});

Open in new window


That then goes to the controller:

if($_SERVER['REQUEST_METHOD'] === 'POST') {

    $response = array();
    $message = '';


    $orderId = $_POST['order_id'];

    $data = [

        'order_id' => $orderId
    ];

    if($this->TransactionsModel->deleteFailedTransactions($data)) {
        $response['success'] = true;
        $response['message'] = 'Failed transactions deleted';

    } else {

        $response['success'] = false;
        $response['message'] = 'Something went wrong. Please try again later.';
    }

    echo json_encode($response);    
}

Open in new window


Which is supposed to send the data to the model:

public function deleteFailedTransactions($data)
    {
        $this->db->beginTransaction();

        try {

            $this->db->query("DELETE FROM `order_summary` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);

            foreach($data as $item) {
                $order_id = $item['order_id'];
                $this->db->execute();
            }


            $this->db->query("DELETE FROM `order_detail` WHERE `order_id` = :order_id");
            $this->db->bind(":order_id", $order_id);

            foreach($data as $item) {
                $order_id = $item['order_id'];
                $this->db->execute();
            }

            $this->db->commit();
            return true;
        }

        catch(Exception $e) {
            $this->db->rollBack();
            echo $e;
            return false;
        }
    }

Open in new window


The error I am getting in console is:

undefined index: order_id

It is referring to this line in the model:

$order_id = $item['order_id'];

Open in new window


I am not sure at which point the problem is, is it in the data being sent via ajax, should the foreach loop be in the controller instead, or.....?
0
I want to display 3 comboboxes on a page. Each selection determines how the next combobox is populated.

Is there an example of how to do that with ajax (not using telerik)?

thanks!
0
Hi everyone,

I have the following AJAX call which updates portion of a page at 5s interval. The code works fine excepts that it appears as though the whole page is being refreshed, rather than just the values of the <p>. The page blinks briefly at every call, causing a horrible user experience. Any ideas why?

setInterval(function(){
        $.ajax({
         url:base_url+'dashboard/getLastTickets',
         method:'GET',
        success:function(data)
        {
            data = $.parseJSON(data);
        }
        });

        var ticketContainer = "";
        var i = 0;
        for (i=0; i<data.length; i++){
                ticketContainer = "ticketContainer" + data[i].service_code;
                document.getElementById(ticketContainer).html = data[i].service;
        }
}, 5000);

Open in new window


I did try to include the for loop within the AJAX call, but that did not solve the issue. Thanks for your help.
0
While updating a particular user, I don't want user to update Username to an existing one so I assigned a Unique Key to a field (Username) in Users table to prevent duplicates, so, I like to output the Error message to the user on modal.

How can I trap that error and where to put it in the following script?
<?php

if ( ! empty($_POST) ):

    include('../includes/connection.php');

// Let's see if we have values
    if(!isset($_POST['newSubject'])) { $_POST['newSubject'] = array(); }
    if(!isset($_POST['newClass'])) { $_POST['newClass'] = array(); }
    
    $missingSubjects = count( array_filter($_POST['subject_taught'], function($i) { return $i == ''; }) );
    $missingClasses = count( array_filter($_POST['class_taught'], function($i) { return $i == ''; }) );
    $missingNewSubjects = count( array_filter($_POST['newSubject'], function($i) { return $i == ''; }) );
    $missingNewClasses = count( array_filter($_POST['newClass'], function($i) { return $i == ''; }) );

    if ( empty( $_POST["initial"] ) || empty( $_POST["username"] ) || empty( $_POST["password"] ) || empty( $_POST["role"] ) || $missingSubjects || $missingClasses || $missingNewSubjects || $missingNewClasses ):

        $update_err = "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
        <span class='badge badge-danger'>Required</span> You must fill in all fields.
        </div>";
   

Open in new window

0
I like to personally appreciate gr8gonzo, Julian and especially Chris Stanyon for their unconditional assistance towards my project. Thank you Experts.

When a problem is solved, another is created.

I like to separate the error id and success id from the following codes so I can display errors on the modal before closing it and display success on the main page after closing the modal.

staff_update.php
<?php

if ( ! empty($_POST) ):

    include('../includes/connection.php');

// Let's see if we have values
    if(!isset($_POST['newSubject'])) { $_POST['newSubject'] = array(); }
    if(!isset($_POST['newClass'])) { $_POST['newClass'] = array(); }
    
    $missingSubjects = count( array_filter($_POST['subject_taught'], function($i) { return $i == ''; }) );
    $missingClasses = count( array_filter($_POST['class_taught'], function($i) { return $i == ''; }) );
    $missingNewSubjects = count( array_filter($_POST['newSubject'], function($i) { return $i == ''; }) );
    $missingNewClasses = count( array_filter($_POST['newClass'], function($i) { return $i == ''; }) );

    if ( empty( $_POST["initial"] ) || empty( $_POST["username"] ) || empty( $_POST["password"] ) || empty( $_POST["role"] ) || $missingSubjects || $missingClasses || 

Open in new window

0
I need Experts to look into my code.

I observed the following:

1.   When I click on Update button without clicking on 'addRow' button of the modal form, I get the following errors:
Notice: Undefined index: newSubject in C:\...\staff_update.php on line 10

Warning: array_filter() expects parameter 1 to be array, null given in C:\...\staff_update.php on line 10

Notice: Undefined index: newClass in C:\...\staff_update.php on line 11

Warning: array_filter() expects parameter 1 to be array, null given in C:\...\staff_update.php on line 11

Notice: Undefined index: newSubject in C:\...\staff_update.php on line 50

Warning: Invalid argument supplied for foreach() in C:\...\staff_update.php on line 50

2.   When New Row(s) of (newSubject and newClass) is/are added and filled and Update button is clicked, data inserted properly BUT if the Update button is clicked again, a new row(s) of the same data is/are inserted again. (I know this is happening because I put the Insert code in the Update Script). It makes sense to insert new row only when the user clicked on Update button. addRow button can insert but blank rows.

addRow script:
$(document).on('click', '.addRow', function(){
   var html = '';
   html += '<tr>';
   html += '<td><select name="newSubject[]" id="newSubject" class="form-control newSubject"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select></td>';
   html += '<td><select 

Open in new window

0
Hello Expert!

I need expert help. I'm completely lost in this. I've tried what I could.

Let me explain what I want:

Note: Two tables are involved: Users (no duplicate record) and UserClass (there are duplicate records);
When a user is registered, subjects and classes are assigned - a user can teach 1 or more subject in 1 or more classes, hence, reason for the duplicate records in the UserClass table

So,
1.   The modal should be able to update the user data;
2.   One or more rows in the table section of the modal can be added or removed. Meaning, Subject_Taught and Class_Taught are subject to change. Not only updated but completely removed or new added.
3.   I want a row to be deleted from database (UserClass table) when the red button (delete icon) on the modal is clicked.
4.   I want new row to be inserted if the green button (Add icon) on the modal is clicked as long as the two fields are filled.

getUpdateForm.php
<?php

require_once '../includes/connection.php';

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

$stmt = $conn->prepare("SELECT UserClassId, UserId, SubjectTaught, ClassTaught FROM UserClass WHERE UserId = ?");
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();
$SubClass = $stmt->get_result();

$staffRole = $conn->query("SELECT Role_Name FROM tbl_roles");

Open in new window

0
Hello Experts,

I am trying to convert access to web app using PHP. Having some issues . Attached you will find MS ACCESS FILE.

1st... How to make  CONTINUOUS FORM like access in PHP. ( In attached MS ACCESS file you will see adding trip, when I add some data in first row, then new row is automatically added/generated)

2nd. Auto populate after update of Combo/Dropdown box. ( In attached file you will see when DRIVER is selected then the PHONE field is auto populated. How I can get it done this in PHP.

3rd. I have PARENT form and SUB form, when I open SUB FORM name ADD FUEL by clicking ADD FUEL button, new form is open with same [IDTrip] as parent [IDTrip] also sum of GALLONS & MILES sumsup in PARENT FORM.

Please let me if its possible thorough PHP or JAVASCRIPT./Jsquery.

Thanks million in advance.



Thanks
JB.accdb
0
JS,php,PDO user signup dosn't actually inject data into database, but returns success and shows no errors in Chrome Developer's Tools.
Server error log shows "[26-Jun-2018 18:30:12 America/Denver] PHP Parse error:  syntax error, unexpected 'was' (T_STRING), expecting ',' or ';' in /home/pricelea/public_html/_modules/registration-PDO/register.php on line 51" But I can't see any syntac error here.  How can I track down what's going on?
db_connect.php
signup.htm
main.js
register.php
0
Cloud Class® Course: Microsoft Office 2010
LVL 12
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

0
I am using various ajax calls in my PHP projects. In my jquery ajax request I usually call PHP files. I have few questions related to the security.

1)As Js code is visible by View source option, so a hacker can easily see the name of php file on which ajax request is send. Will hacker download that PHP file?
2) If hacker can download the php file he can view my code which is mostly related to DB operations. In that way he can perform SQL injections or some different attacks.

So how to secure it?

Here is my sample Ajax Request
  jQuery.ajax({
        type: "POST",
		url:"ajax-search.php",        
		data: {input:input,path_base:path_base},
        async: true,

        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status);
            alert(textStatus);
            alert(errorThrown);
        },
        success: function(result) {

            jQuery("#img_search").html(result);
             jQuery("#img_search_result").html("Results: " +  jQuery(".search img").length);
        }
    });

Open in new window



Looking forward for some expert opinions.

Thanks
0
I really don't know how to bind Modal submit button to the Ajax call.

I'm currently using the following script within the same html page:
deleteStaff.php
// sql to delete a staff
if(isset($_POST['delete'])){
	$delete_id = $_POST['user_id'];
		$sql = "DELETE FROM Users WHERE UserId='$delete_id' ";
			if ($conn->query($sql) === TRUE) {
	$success_msg = '<div class="alert alert-success">
		<span class="badge badge-success">Success </span> The Staff was successfully <div class="label label-warning">deleted</div>.
		</div>';
	} else {
	$error_msg = '<div class="alert alert-danger">
		<span class="badge badge-danger">Error: </span> '.$conn->error.' </div>';
	}
}

Open in new window


Modal form:
<!--Delete Staff Modal Alert -->
<div id="deleteModal" class="modal fade" role="dialog">
	<form method="post">
		<div class="modal-dialog">
			<!-- Modal content-->
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close red" data-dismiss="modal">&times;</button>
					<h5 class="modal-title blue bigger"><i class='ace-icon fa fa-exclamation-triangle red'></i> Delete</h5>
				</div>
				<div class="modal-body">
					<input type="hidden" name="user_id" value="">
					<div class="alert alert-danger">You're about to delete <strong id="userInitials"></strong> from database.
						All records related to this Staff will be DELETED PERMANENTLY.
					</div>
					<p class="bigger-110 bolder center grey">
						<i class="ace-icon fa fa-hand-o-right blue bigger-120"></i>
						Are you sure you want to continue?
					</p>
				</div>
				<div class="modal-footer">
					<button type="submit" name="delete" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Delete</button>
					<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> Cancel</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
	</form>
</div><!-- /.modal -->

Open in new window


jQuery:
$('#dynamicTable').on('click', '.deleteUser', function(e) {
		    e.preventDefault();
		    $('input[name=user_id]').val( $(this).data('id') );
		    $('#userInitials').text( $(this).data('initials') );
		    $('#deleteModal').modal('show');
		});

Open in new window


Thanks for your help.
0
Hello Experts!

I need help on Update using Ajax.

I currently insert using this modal:
<!-- new staff modal-->
<div class="modal fade" role="dialog" id="addStaffModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Add New Staff</h4>
      </div>

      <form class="form-horizontal" method="post" id="newStaff-Form" action="staff_data.php">
      <div class="modal-body">

      	<div id="alert_message" class="center"></div>
      	<div id="response" class="center"></div>
      	
        <div class="form-group">
    		<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="initial">Initial<span style=color:red;> *</span>
    		</label>
    		<div class="col-xs-12 col-sm-9">
    			<div class="clearfix">
    				<input type="text" name="initial" class="col-xs-12 col-sm-9" id="initial" placeholder="e.g. AbdulRasheed G. O." autofocus autocomplete="off">
    			</div>
    		</div>
    	</div>

        <div class="form-group">
    		<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="username">Username<span style=color:red;> *</span>
    		</label>
    		<div class="col-xs-12 col-sm-9">
    			<div class="clearfix">
    				<input type="text" name="username" class="col-xs-12 col-sm-9" id="username" 

Open in new window

0
I'm new to Ajax. My DataTable is being populated via Ajax call.

The button that opens the modal is set up as:
<a class='red tooltip-error' href='#delete_{$user->UserId}' data-toggle='modal'>
                <i class='ace-icon fa fa-trash-o bigger-130'></i>
            </a>

Open in new window


The Modal form for confirmation is:
<!--Delete Staff Modal Alert -->
<div id="delete_{$user->UserId}" class="modal fade" role="dialog">
	<form method="post">
		<div class="modal-dialog">
			<!-- Modal content-->
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close red" data-dismiss="modal">&times;</button>
					<h5 class="modal-title blue bigger"><i class='ace-icon fa fa-exclamation-triangle red'></i> Delete</h5>
				</div>
				<div class="modal-body">
					<input type="hidden" name="user_id" value="{$user->UserId}">
					<div class="alert alert-danger">You're about to delete <strong>{$user->Initials}</strong> from database.
						All records related to this Staff will be DELETED PERMANENTLY.
					</div>
					<p class="bigger-110 bolder center grey">
						<i class="ace-icon fa fa-hand-o-right blue bigger-120"></i>
						Are you sure you want to continue?
					</p>
				</div>
				<div class="modal-footer">
					<button type="submit" name="delete" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Delete</button>
					<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> Cancel</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal-dialog -->
	</form>
</div><!-- /.modal -->

Open in new window


The Delete Query is as follows:
// sql to delete a staff
if(isset($_POST['delete'])){
	$delete_id = $_POST['user_id'];
		$sql = "DELETE FROM Users WHERE UserId='$delete_id' ";
			if ($conn->query($sql) === TRUE) {
	$success_msg = '<div class="alert alert-success">
		<span class="badge badge-success">Success </span> The Staff was <div class="label label-warning">deleted</div> successfully.
		</div>';
	} else {
	$error_msg = '<div class="alert alert-danger">
		<span class="badge badge-danger">Error: </span> '.$conn->error.' </div>';
	}
}

Open in new window


When I click on Delete Icon, nothing happens. The Modal doesn't open at all.
What I want now is to use Ajax to delete record from database. Display Success Message and refresh the DataTable.
0
Good day, I have two dropdown lists, both being populated from my database. I have a controller that filters these lists, the controller is supposed to get the selected value from my dropdown. How do i pass both selections at the same time to the controller and return a view based on the filtered results of the controller? Thanks.

ViewModel

 public class LocationPurposeVM
    {
        public IEnumerable<Location> Locations { get; set; }
        public IEnumerable<Purpose> Purposes { get; set; }
        public IEnumerable<Hall> Halls { get; set; }
    }

Open in new window

CONTROLLER FOR POPULATING DROPDOWN LIST AND FILTERING BASED ON SELECTION
public ActionResult Index()
        {
            LocationPurposeVM vm = new LocationPurposeVM();
            vm.Locations = locationService.GetAll();
            vm.Purposes = purposeService.GetAll();
            vm.Halls = hallService.GetAll();
            return View(vm);
        }
        // GET: Location
        [HttpPost]
        public PartialViewResult ViewHalls(string location, string purpose)
        {
            LocationPurposeVM vm = new LocationPurposeVM();
            vm.Locations = locationService.GetAll();
            vm.Purposes = purposeService.GetAll();
            vm.Halls = hallService.GetAll();
            ViewBag.Location = (from r in vm.Halls
                                select r.Location).Distinct();
            ViewBag.Purpose = (from r in vm.Halls
                               select 

Open in new window

0
How can I refresh dataTable after insert with modal?

My table is as follows:
<table id="dynamicTable" class="table table-striped table-bordered table-hover">
	<thead>
		<tr>
			<th class="center">
				<label class="pos-rel"><span class="lbl">#</span></label>
			</th>
			<th>Staff Name</th>
			<th>User ID</th>
			<th class="hidden-480">Password</th>
			<th class="hidden-480">Role</th>
			<th class="hidden-480">Class Assigned</th>
			<th>Actions</th>
		</tr>
	</thead>
	<tbody>

		<?php
		if($total_rows > 0)
		{
			$cnt = 1;
			foreach($result as $row)
			{
				$id = $row['UserId'];
				$staff_name = $row['Initials'];
				$staff_loginid = $row['Username'];
				$staff_password = $row['Password'];
				$staff_role = $row['Role'];
				$class_assigned = $row['ClassAssigned'];

				if($staff_role == 'Admin'){
					$role = "<div class='badge badge-info'>Admin</div>";
				}else if($staff_role == 'Form Master'){
					$role = "<div class='badge badge-warning'>Form Master</div>";
				}else {
					$role = "<div class='badge badge-success'>Subject Teacher</div>";
				}             
				?>
				<tr>
					<td><?php echo $cnt;?></td>
					<td><?php echo $row['Initials'];?></td>
					<td><?php echo $row['Username'];?></td>
					<td class="hidden-480"><?php echo $row['Password'];?></td>
					<td class="hidden-480"><?php echo $role;?></td>
					<td class="hidden-480"><?php echo $row['ClassAssigned'];?></td>
					<td><div class="hidden-sm hidden-xs action-buttons">
						<a 

Open in new window

0
Hello Experts,

I need help on modal form validation.

The following code inserts properly (only when all inputs are filled correctly).

I'm having trouble validating subject_taught and class_taught inputs.

More so, I want the form to clear all inputs (reset) after insert without error. The datatable should refresh afterwards.

The code:
<?php
include('../includes/connection.php');


if ( ! empty($_POST) ) {
	
    if ( empty( $_POST["initial"] ) || empty( $_POST["username"] ) || empty( $_POST["password"] ) || empty( $_POST["role"] ) || empty( $_POST["subject_taught"] ) || empty( $_POST["class_taught"] ) ) {

    	$response = '<div class="alert alert-danger">
		<span class="badge badge-danger">Empty Field(s) Detected!</span> All fields are required.</div>';

        die($response);
    }

    // Validation passed so let's deal with the DB stuff

	$initial = $_POST["initial"];
	$username = $_POST["username"];
	$password = $_POST["password"];
	$role = $_POST["role"];
	$class_assigned = $_POST["class_assigned"];
	

	$master_query = '';
	
	$stmt = $conn->prepare("SELECT Username FROM Users WHERE Username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $staffList = $stmt->get_result();

    if (mysqli_num_rows($staffList) > 0 ) {

    	$response = '<div class="alert alert-danger">
		The Username: <span class="badge badge-pink">'.$username.'</span> already exists. Try another one!</div>';

	die($response);
  

Open in new window

0
I am making my Ajax Response. For this I take 3 variables in a while loop and save values of 3 database columns in them. As there are multiple records
in DB so I have concact the value like $value .= 'value from db'. After the loop I have put these three variables in an array and sent them by using json_encode.

Here is  the sample code
 
while($projects_row = mysqli_fetch_assoc($projects_result))
		{         
			$projects_name .= '<li id="project-id-5a01bffbcfbeb40a008b458a" data-id="5a01bffbcfbeb40a008b458a">
			<span class="li-txt" style="color:#ff0000;width: calc(100% - 90px);"><a id="myAnc" href="#">'.$projects_row['project_title'].'</a></span>
			<span class="thumb-container"><span class="thumb thumb-3" style=""></span> 
			<span class="thumb thumb-6" style=""></span> </span></li>';		

			$projects_detail .= $projects_row['project_detail'];			
			$projects_image .= $projects_row['project_image'];			
        }  

echo json_encode(array("message1" =>$projects_name, "message2" =>$projects_detail, "message3" =>$projects_image ));
		

Open in new window


In my Ajax Success function I am retrieving the values as:
  $.ajax({
                url:"myresponse.php",
                type: "POST",
                data:  {"country_id":country_id},
                dataType: "json",								
					success: function(data)
					{				
						console.log(data);
						//alert(data.message1);
						//alert(data.message2);
						jQuery("#project-list").html(data.message1);
						jQuery(".pr-cont-info").html(data.message2);												
					},
				
              });  

Open in new window


The issue is data.message1 and data.message2 contains data of all rows. I need to seperate the data of each row so that I can use any row data anywhere.
For example, in my case data.message1 contains data of 3 rows like 'USA Project 1 USA PROJECT 2 USA PROJECT'. I have print that data in a DIV and due <li> tags
one record is printed in one line. Now i want that if user click on USA Project1, then it only shows the details of Project1.  Currently it shows the details of all 3 rows.

So how to fix this issue?
0
Cloud Class® Course: CompTIA Healthcare IT Tech
LVL 12
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

All thanks to Chris Stanyon who has been helping in making sure I'm successful in my project.

Now, I have a bootstrap modal that inserts into mysql using explode. I like to use same type of modal form to update the data fetched from database.

When I click on the Edit button on the datatable, I want the Modal to open the record of the selected user for necessary update.

Please Note: I use Ajax to post to the database.

The sample of what I want is attached and the script for my insert is as follows:

Modal for Insert:
<!-- new staff modal-->
<div class="modal fade" role="dialog" id="addStaffModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Add New Staff</h4>
      </div>

      <form class="form-horizontal" method="post" id="newStaff-Form" action="data.php">
      <div class="modal-body">
      	
      	<div id="response" class="center"></div>
      	
        <div class="form-group">
    		<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="initials">Initials<span style=color:red;> *</span>
    		</label>
    		<div class="col-xs-12 col-sm-9">
    			<div class="clearfix">
    				<input type="text" name="initials" 

Open in new window

0
Here is my Ajax response:

 $projects_name .='<li id="project-id-5a01bffbcfbeb40a008b458a" data-id="5a01bffbcfbeb40a008b458a">
			<span class="li-txt" style="color:#ff0000;width: calc(100% - 90px);">'.$projects_row['project_title'].'</span>
			<span class="thumb-container"><span class="thumb thumb-3" style=""></span> 
			<span class="thumb thumb-6" style=""></span> </span> </li>';

Open in new window


Now I want that when user click on the Project Title (see $projects_row['project_title'] variable) then I want to change the style="display" property of two divs mentioned below:


1)I need to change style="display:none" to style="display:block"
<div id="project-content" class="map-sidebar project-sb" style="display: none;">



2) And in the below code, I want to change it to dispaly:none
<button class="sidebar-tab map-theme-bg-color" style="background-color: rgb(98, 166, 47); display: block;"></button>

Need jQuery code help

Ps: If I am not using Ajax then I am able to change value but with ajax Response I cannot get value.
0
Hello all,

I'm a hobbyist, starting to dip my toe into Bootstrap 4, along with JQuery and Ajax.

I've got a PHP script, which works fine for tabs in Bootstrap 3 - and I'm now trying to convert it into Bootstrap 4 Collapse/Accordion - but cannot get it working - my ajax content currently appears outside all the accordion tabs, at the very bottom of the screen. I've spent some time researching this, but cannot see examples on what I'm trying to achieve.
 
For my Bootstrap 4 Accordion, when it initially appears, I want the first panel open and populated with my dynamic ajax content - with loading gif -  with each panels content being dynamically refreshed with ajax with each panel press.

<script>
$(document).ready(function() {


    $("#247button").click(function() {
 
        $("#ajax-content").empty().append("<div id='loading'><img src='/images/loading.gif' height='60' width='60' alt='Loading' /></div>");
        $("#nav li a").removeClass('current');
        $(this).addClass('current');
 
        $.ajax({ url: this.href, success: function(html) {
            $("#ajax-content").empty().append(html);
            }
    });
    return false;
    });
 
    $("#ajax-content").empty().append("<div id='loading'><img src='/images/loading.gif' height='60' width='60' alt='Loading' /></div>");
    $.ajax({ url: '/247getday2staffTIMES.php', success: function(html) {
            $("#ajax-content").empty().append(html);
    }
    });
});
</script>  


<div id="accordion">
 

Open in new window

0
Hello Experts,

How can I make my modal stay open even after clicking on submit button?

Apart from the above, I want the success_msg and error_msg to display on the modal as in attached. If there's error, I want all the inputs to still retain their values but if there's no error, data should be inserted, table refreshed and success_msg displayed while all inputs are cleared. In any case, modal remains open until I manually close it.

My modal is as follows:
<!-- new staff modal-->
<div class="modal fade" role="dialog" id="UpdateStaff">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Add New Staff</h4>
      </div>

      <form class="form-horizontal" method="post" id="newStaff-Form" action="">

      <div class="modal-body">
      
      	<div class="center"><?php echo $success_msg; ?></div>
		<div class="center"><?php echo $error_msg; ?></div>

        <div class="form-group">
    		<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="initials">Initials<span style=color:red;> *</span>
    		</label>
    		<div class="col-xs-12 col-sm-9">
    			<div class="clearfix">
    				<input type="text" name="initials" class="col-xs-12 col-sm-9" id="initials" placeholder="e.g. AbdulRasheed G. O." autofocus 

Open in new window

0
I have developed a list filter page which updates using ajax. Everything works well until I have discovered that search engines do not see this content!

Is there anything I can do to make this content visible to search engines using ajax, before I start a redevelopment?
0
Hi there.
I'm adapting a tutorial which uses ajax and php to pull information from my database, when  the user scrolls to the bottom of the page.

I noted however, that when I was reaching the bottom of the page, information wasn't always getting pulled from my database. I amended my code slightly to include my div tags within the php echo  (as per the original code) and the code now works (to an extent)  - it's pulling information as specified from the database.

So my working php code which displays the information on the page, and reloads is the following :

while($teacher = mysqli_fetch_array($data))
		{
			//here we are displaying the information from the database
			echo '
			<div class="container">
			<div class="col-sm-6 col-md-4 buffer">
			<div class="card" style="width: 100%;">
			
				<div class="card-header">
				<h1>'.$teacher['id'].'</h1>
				<img src="../public/img/flags/'.$teacher['nationality'].'flag.gif">
				<h2>'.$teacher['firstname'].'</h2>
				</div>
				
				<div class="card-body">
				<h1>'.$teacher['id'].'</h1>
				<h2>'.$teacher['firstname'].'</h2>
				</div>
			
			</div>
			</div>
			</div>
			';
		}

Open in new window


However, I want to display more information within the while.. The following code represents the information I want to display within the while loop and how it should appear. This code displays everything correctly on it's own but the pulling of the data does not seem to work with it.  

<div class="row">
            

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.