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

Trying to send checkbox state to PHP page using Ajax. I am able to send he value of the element but I also need to send the state of the button that will determine if the data is added or deleted from the database. Here is what I have.
<script>

 $(document).on('click', '.favorite-resource-checkbox', function(){  
            var resourceValues = $( this ).val();
		    var user = "<?php echo $user_id; ?>";
	 		var id = $(this).attr('id');
           
           $.ajax({  
                url:"file.php",  
                method:"POST",  
                data:{value: resourceValues , user: user},  
                dataType:"text",  
                success:function(data)  
                {  
                     alert(data);  
                    
                }  
           })  
      });		
	
</script>	

Open in new window


Thanks
1
Microsoft Azure 2017
LVL 12
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Ok my problem,

I used ajax with case statements on php end.

function saveAct(){
    
    
    
    
    var testAct = $('#act-data :input').serialize();
    
  
   
    $.ajax({
           type: "POST",
           url: 'controllers/contacts.ajax.php',
           data: { subaction : "saveActDetails" , actForm : testAct},
           dataType: "json" 
        }).success(function (response) {
             
                 console.log(response)
  
      
        }).error(function (response) {
               console.log(" save-act error");
        });
}

Open in new window


so i use the post type,  i use the subaction to trigger the correct case, then im using the actFrom to send form data, now i want to be able to use this data to insert into a table. but im first seeing what i am posting, the return looks a match to the form however i dont think i can use it and add this to a table.


case 'saveActDetails' :

		$response = array(
			'Result' => 'save-act success',
			'data' => $_POST['actForm']
		);


		break;

Open in new window


any solutions ?
1
Whi can iam confirm a java script in any other mobile device and any other emaaddress and run it confidentialy please suggest me that what is the process to run the files that can,t be support the device.thease are the files mean java files or non supported files system can,t be display like zip files,axp,jpg,txt,docx,xisx,pdf,or more forms files.or a video format files that can be have to downloaded queue but system does not support to play and run thank you again
0
Twp questions on this page: https://www.gopherstateevents.com/results/cc_rslts/cc_rslts.asp

1) Why is there so much space above and below the horizontal list beginning with "Awards" and how can I minimize that?
2) If I used a data table for the Individual Results, would that increase, decrease, or have no impact on load time?

Thank you!
0
I want to disable a form submit if a div has a message contained within it.

I have a form that checks an external source for some validation. If the validation checks are not met, then a warning message is displayed in a div (dispemail).

I'd like to disable my submit button if a message is displayed in this div.

My form is:
<form action='formprocessor.php' method='post' id='member-add'>
<table cellpadding='5px' cellspacing='5' >
<tr><td>Email</td></tr>
<tr><td><input type='text' name='email' id='email' value=''/><div id='dispemail'></div></td></tr>
<tr><td><input type='submit' value='Submit' style='margin-top:20px; margin-bottom:40px' id='submit'/></td></tr>
</table>
</form>

Open in new window


The Javsacript to call the ajax validation script:
<script type="text/javascript">
$(document).ready(function(){
$("#email").blur(function() {
var email = $('#email').val();
if(email==="")
{
$("#dispemail").html("");
}
else
{
$.ajax({
type: "POST",
url: "check-email.php",
data: "email="+ email,
success: function(html){
$("#dispemail").html(html);
}
});
return false;
}
});
});
</script>

Open in new window


The validation code:
<?php

if(isset($_POST['email'])){
$email=(($_POST['email']));

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.xxxxx.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => "{}",
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}


$responsetext=json_decode($response, true);

if ($responsetext['result']=='undeliverable'){
$message = $responsetext['email']." is not a valid email - ".$responsetext['reason'];
echo "<p class='error'>$message</p>";

}
else {
$message = $responsetext['email']." is a valid email";
echo "<p>$message</p>";
}



}

?>

Open in new window

0
I'm trying to work with the Oxford Dictionary api to check whether words discovered in my app do actually feature in the dictionary.
Usually I make api calls using jquery and ajax, however this one doesn't receive client-side calls so I'm having to write it server-side in PHP and fire it using ajax from a javascript function.

I'm close, but I can't quite see how to include the authentication parameters in the url call, and my PHP is a bit sketchy at the best of times, so I'm hoping an expert here can help me to get the syntax right. At the moment, the response from the PHP file is simply: "Authentication parameters missing."  - So I'm sure its just my own ignorance about php and cURL holding it back. Can you help by showing me what changes to make in the PHP file below?

Any advice would be warmly received. Thanks...

This is how it looks so far:

For the JS:
function isDictionaryWord(pl){
    
    var isWord = false;
    
    pl = pl.toLowerCase();
    pl = pl.split(' ').join('_');
    
    $.ajax({
            url: "call_oxford_apia.php", 
            method: "post",
            data: { "word":pl},
                success: function(resp){
                    console.log("Oxford Check Shows: " + JSON.stringify(resp))
                    isWord = true;
                },
                 error: function() {
                     isWord = false;
                } 
    });
    
    return isWord;
}

Open in new window


And for the PHP: (filename: 'call_oxford_apia.php')


Open in new window

0
Hi Experts!

I have a question regarding to the file upload code. It is a simple html upload code:

<form class="smart-form" enctype="multiplart/form-data">
........
<fieldset>
        <section>
            <label class="label">File input</label>
            <div class="input input-file">
                  <span class="button"><input type="file" id="file" name="file" onchange="this.parentNode.nextSibling.value = this.value">Browse</span><input type="text" placeholder="Please upload the file in either .txt or .csv or .xls or .xlsx format" readonly="">
            </div>
      </section>
......
</form>

For my javasxript side I have this code: (I posted the information as $_FILES['Info'] to the PHP)

$('#file').change(function() {
      var file = this.files[0];
      var _formData = new FormData();
      _formData.append('Info', file);

      $.ajax({
            type: "POST",
            url: "App/uploader.php",
            dataType: "text",
            contentType: false,
            processData: false,
            data: file
      }).done(function(data){                   
            //console.log(data);
            var rData = JSON.parse(data);
            switch(rData)
            {
                  case 1:
                        $('#fileMsg ').text("SUCCESS!");
                        setTimeout(function(){location.reload(true);}, 1500);
                        break;
                  case 0:
                        $('#fileMsg ').text("FAILURE!");
                        setTimeout(function(){location.reload(true);}, 2500);
                        break;
            }
      });      
});

My issue is this:

When I use the ajax post and get a result as return I need to use setTimeout(function(){location.reload(true).... in order to upload another file. If I don't reload …
0
I have a ajax function which returns some json....

{
	"data": {
		"type": "slide",
		"id": "13",
		"attributes": {
			"slideID": 13,
			"slideGroupID": 1,
			"slideNumber": 2,
			"slideLocation": "Slide1.JPG",
			"slideLive": 1,
			"slideCurrent": 0,
			"slideHasVote": 0
		}
	}
}

Open in new window


How do I access the data using jquery. I need the slideLocation.
I thought this: console.log(data.attributes.slideLocation); but it doesn't work.
0
I have a job that I would like to get bids on...if that still happens on this site.  Here is what I need:

I need this page (https://www.gopherstateevents.com/results/fitness_events/results.asp?event_type=5&event_id=825&race_id=1427) to "scroll" vertically in marquee fashion for large screen display at races.  All I really need is the data table...or the data in the data table...to be visible.  Please let me know if you would be able to help me and what it would cost me.  I have tried to get this going in the "normal" process of doing it myself with EE help but, due to my weakness in JQuery, I just haven't gotten there.

Let me know if you have questions or if you can help me.
0
bootbox.confirm("Are you sure you wish to change this field?", function(result)
                    { 

                         

                    });
             
             
                        $.ajax({
                            type: "POST",
                            url: 'set-field-value.php',
                            data: formData,
                            processData: false,
                            contentType: false,
                            dataType: "json" 
                        }).success(function(response){
                            console.log(response);
                   

                        }).error(function (response) {

Open in new window



So above is start of a function i have which will update fields but i am doing some valuation. the bootbox brings up a dialog with message and two buttons which sets a result either true or false. im wondering how do i within that dialog function proceed to ajax is true and stop function and not reach ajax if false.
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.

I am using input type color as i want to save selected color to DB.
I can see color which I did choose in console (check js), but something  gets wrong with ajax as I can not get echo "nnnnnnnn", but just "mmmmmmmmmmm" (check php).
So I might not debug forward in case of other errors.


php
<?php
echo "mmmmmmmmm"; 
if(isset($_POST["uColorIsSet"])){
 echo "nnnnnnnnnnnn";    
include_once("/wp-content/themes/n4/php_includes/db_conx.php");
$uColor2 = mysqli_real_escape_string($db_conx,$_POST['uColor2']);
$sql = "UPDATE users SET yourColor='$uColor2' WHERE username='$u'";
$query = mysqli_query($db_conx, $sql);
}
?>

Open in new window

and js
function updateAll2(event) {
var uColorIsSet=0;
 var uColor2 = event.target.value;
 console.log("selected color"+uColor2);
$.ajax({
  method:"POST",
  url: '/wp-content/themes/n4/nF4/user.php',
  data:  {
    "uColorIsSet":1,
    "uColor2":uColor2
    },
    datatype: "text",
    success: function(strdate){
   
      console.log("aaaaaaaaaaaaaa");
     
     },
     error: function(error, txtStatus) {
      console.log(txtStatus+" error on load of canvas on user page");
      console.log('error');
    }
 });
}

Open in new window


Can you see from data that I  provided what is the problem?


Just for  Info: I am doing the initial setting of color as next.
      
$sql = "INSERT INTO users (yourColor)    VALUES ('$c')";

Open in new window

0
Hi experts!

I was working on the bootstrap modal. I was able to insert a datatable into the modal and everything displays properly via ajax sync. The datatable also has a input field for quantity (I inserted <input> as text) and I wished to do another ajax sync and took the input from user and updated the database (mysql). For some reason I had a js script to do that but I couldn't get it to work. I found a way to get around was that when I worked on the 1st ajax sync (insert data into datatable in the modal) I needed to add a <script src="xxxx/xxx.js"/> into the ajax section. I could then make my 2nd ajax sync work. was this a good way to update the database or there is a better way?  (Is there a way for me not to add that <script src="xxx/xx.js"/> into the ajax code but rather include in my original js script?) Let me know Thanks!
0
I am storing image names in an array from DB and then encode it with json encode function to receive it in my ajax success method:

Here is the code"

$sql_gallery = "SELECT * FROM map_projects_gallery ";		
$gallery_result = mysqli_query($conn, $sql_gallery);
while( $gallery_row = mysqli_fetch_assoc($gallery_result) )
{					
$gallery_image_name[] = $gallery_row["img_name"];			
}		

echo json_encode(array("map_gallery" =>$gallery_image_name ));		

Open in new window



Note: In ajax success function it returns all the image names. Now I want to display all images in a div and then later display them in a slider.


And here is my Code of jQuery Ajax
jQuery.ajax({
	url:"project.php",
	type: "POST",	
	data:  {"country_id":country_id,"lang_name":langname_val,"node_id":node_id,"fullurl":'<?php echo base_path();?>'},
	dataType: "json",								
	success: function(data)
	{
		alert(data.map_gallery);
		jQuery('#project-list').html(data.message1);  
	        jQuery('#paginations').html(data.message_2); 
		  
		
		  ///jQuery('.pr-cont-gallery').html('<img src=files/'+project_details.project_image+' width=200px>');	  
		  
		  jQuery('.pr-cont-gallery').append('<img src="' + data[0].map_gallery + '" />');

		  
		  data.forEach(function (data) {
				jQuery('.pr-cont-gallery').append('<img src="aaaaa.jpg" />');
		   });
	},
  }); 

Open in new window


Problem:  I am unable to display all images separately in a div. Need help to fix this issue
0
Here is the ajax call

function showCustomProps(){
    
    $('#subaction').val("getCustomProperties");
    var data = $('#subaction') ;
  
  
    $.ajax({
        type: "POST",
        url: 'controllers/contacts.ajax.php',
        data: data,
    }).success(function (response) {
      
        
        
        console.log(response);
        
    }).error(function (data) {
        console.log("erro customProps");
    });
    
} //showCustomProps

Open in new window


this is triggered on load.

to run this code -

$stmt = new Database();

				$query = "SELECT cp.id, cp.name, cp.field_type 
							FROM custom_properties cp
							WHERE cp.client_id = :clientID AND cp.viewable='1' AND cp.type = '1'
							ORDER BY cp.id DESC";
				$stmt->query( $query );
				$stmt->bind( ':clientID', $clientId);
		     	$stmt->execute();
				$demo1 = $stmt->fetchAll();

				foreach($demo1 as $customResult){
					$cusData['propertyId'] = $customResult['id'];
					$cusData['propertyName'] = $customResult['name'];
					$cusData['propertyType'] = $customResult['field_type'];
				

			

				}//customresult

						$response = array(
							'subresult' => 'customProps success',
							'data' => $cusData
						
							
						);

		break;

Open in new window



Now the issue is that it is returning null.  but if i change fetchAll to all it returns a row from the database, i need this foreach to fetch all records not just the first one. if i return demo1 instead of customResult i can see there is two records, Please note i can only see this data if i use all() and when i use fetchAll it returns null.
0
Array =

"<select style ='width:100%;' class='formInput' name='property'2527'' id='property'2527''><option value=''>- select -</option>"
1
:
"<option value='test1' >test1</option>"
2
:
"<option value='test2' >test2</option>"
3
:
"<option value='test3' >test3</option>"
4
:
"</select>"

Open in new window


so i then append to my html

$("#custom-properties").append(properties.custom);

Open in new window



but the output structure is incorrect ?

html structure
any hints
0
Hi experts,

I'm using the Telerik UI for ASP.NET AJAX RadWindow.
https://demos.telerik.com/aspnet-ajax/window/examples/overview/defaultcs.aspx

I'm using ASP.NET and VB.

I saw this example here for passing a parameter from the Main page to the RadWindow:

Using RadWindow as a Dialog
https://docs.telerik.com/devtools/aspnet-ajax/controls/window/how-to/using-radwindow-as-a-dialog

I recreated this example and it works fine.

This is the working code:

RadWindow1_MainPage.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="RadWindow1_MainPage.aspx.vb" Inherits="RadWindow1_MainPage" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">

        // https://docs.telerik.com/devtools/aspnet-ajax/controls/window/how-to/using-radwindow-as-a-dialog

        // The OnClientShow event handler sets the argument to the dialog being opened
        function clientShow(sender, eventArgs) {
            // When the showRadWindow1 button is clicked the value from the textbox is pass to RadWindow1 as an argument
            var txtInput = document.getElementById("txtInput");
            sender.argument = txtInput.value;
        }
        // The OnClientClose event handler receives the result of the dialog and responds
        function clientClose(sender, args) {
        

Open in new window

0
On my localhost I don't seem to have the problem but on a live server at times when performing an ajax request that has some php querying the database, the ajax query will hang and the spinner/loader that blocks the UI will just get stuck in some infinite loop. This is obviously not good for the customer and not good for business. What is the best way to prevent this/troubleshoot this?
0
I have developed a website using php 7, jQuery and ajax. I have had a few people mention that the website does not work on Internet explorer. There has been no mention of what version but if they said Internet explorer then it sounds like prior to Edge. Apparently just a blank screen appears instead of the actual website. I am running a mac so don't have internet explorer to check myself. What would the best solution be? To either redirect them to a page that requests that they use a more modern browser or.... ?
0
JQ onclick not triggering or any event on any inputs within this container.


So i have a container with inputs now im trying to test a click event on these inputs but it isnt working and no errors and i used click hundreds of times and never had this issue,


so really simple -

$(document).ready(function() {
    $("#contact-personal-fname").click(function () {
      alert("Hello!");

    });
  });

Open in new window


which refers to this one -

<div id = 'firstname' class=' col-md-4'>
                      <label class=' control-label' for='textinput'>First Name</label>                 
                      <input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='".$v_item['FIRST_NAME']."' > 
                    </div>

Open in new window


now this isnt hard coded in, it actually been passed from ajax and appended like so .

   var arrayJson = JSON.stringify(response);
        var properties = JSON.parse(arrayJson);
 $("#default-personal-properties").append(properties.personal);

Open in new window


how it looks in its array . -

personal
:
Array(16)
0
:
"↵								<div id = 'firstname' class=' col-md-4'>↵								<label class=' control-label' for='textinput'>First Name</label>                 ↵								<input id='contact-personal-fname' name = 'FIRST_NAME'  type='text' placeholder='First name'  class='form-control input-md no-border' value='Tim' > ↵								</div>↵						"
1
:
"↵↵						"

Open in new window

0
Become a CompTIA Certified Healthcare IT Tech
LVL 12
Become a CompTIA Certified 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.

Hello Experts!
Please how can I make this login script more secure? Help me use prepare statement and if possible use Ajax to validate at client side. Thank you so much.
<?php

require '../includes/connection.php';

session_start();
$timeout = 1440; // Set timeout period in seconds

if (isset($_SESSION['start_time'])) {
    $elapsed_time = time() - $_SESSION['start_time'];
    if ($elapsed_time > $timeout) {
        header("Location: ../logout.php");
    }
}
$_SESSION['start_time'] = time();

$date_time = date("Y-m-d H:i:s");

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

//Login Query
if(isset($_POST['login_btn'])){

    $username = clean($_POST["username"]);
    $password = clean($_POST["password"]);
    
    $sql = "SELECT users.UserId AS UserId, users.Initials AS Initials, users.Username AS Username, users.Password AS Password, users.Role AS Role, users.ClassAssigned AS ClassAssigned, userclass.SubjectTaught AS SubjectTaught, tbl_subjects.Subject_Name AS Subject_Name, userclass.ClassTaught AS ClassTaught from ((users join userclass on((users.UserId = userclass.UserId))) left join tbl_subjects on((userclass.SubjectTaught = tbl_subjects.Subject_Code))) WHERE Username='$username'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {

        // output data of each row
        while($row = $result->fetch_assoc()) {
            if($row['Password'] == $password 

Open in new window

0
Insert into pdo table not working and no error.

$stmt = new Database();
					//check to make sure there is a record to update 
				$query = "SELECT chk_name FROM a_test WHERE charityID = :clientID AND contactID = :contactId";
				$stmt->query( $query );
				$stmt->bind( ':clientID', $clientId);
				$stmt->bind( ':contactId', $contactId );
		     	$stmt->execute();
				$result = $stmt->all();

		if($result == null){
			foreach($_POST['chkStateCollection'] as $chkState) {
				$stmt = new Database();
					//Inserting check state.
				$query = "INSERT INTO a_test (charityID, contactID, chk_name) VALUES (:clientId, :contactId :chkName) ";
				$stmt->query( $query );
				$stmt->bind( ':clientId', $clientId );
				$stmt->bind( ':contactId', $contactId );
				$stmt->bind( ':chkName', $chkState );
		     	$stmt->execute();
				$result = $stmt->all();
			}
		} else {
				$testreply = "no rows detected";
		}

Open in new window


Ok so what this code is doing and suppose to do.  I am checking to see if a record exists first and this part works as expected if record exist goto else if not then create a record.

Now the record is created with two ID which is stored in a session they seem fine. now im not sure if the last one is the issue as i tried hard coding and same response but the field chk_name is populated by the forach which gets it details from ajax post array which looks like this -

(2) ["POSTITION", "FIRST_NAME"]

Open in new window


the problem is when it gets to the INSERT it doenst add and the ajax response is not successful with not errors. so im lost on what is the issue.
0
When using ajax to send data over i am getting this error.

["POSTITION"]
contact.php?cid=10296&id=:3334 0
jquery-2.2.4.min.js:4 Uncaught RangeError: Maximum call stack size exceeded
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)
    at Gb (jquery-2.2.4.min.js:4)

Open in new window


How i am sending -

$('#subaction').val("setChkState");
       var data = $('#subaction') ;

           $.ajax({
                type: "POST",
                url: 'controllers/contacts.ajax.php',
                dataType: 'json',
                data: {data:data},
            }).success(function (response) {
            

              console.log(response)

                
            }).error(function (data) {
                console.log("erro addCheckState");
            });

Open in new window


Reason for sending this way is im using subaction to trigger a case than i plan to also send muitple data with same ajax etc. like data is to call the case, then other wil be to do something within that case. but i get the follow error when i have only passed in one data.

any tips on where i am going wrong?
0
so im displaying a array result of a drop down.

it returns this data here - this is what it looks like in a alert -

<select style ='width:100%;' class='formInput' name='property'2527'' id='property'2527''><option value=''>- select -</option>,<option value='test1' >test1</option>,<option value='test2' >test2</option>,<option value='test3' >test3</option>,</select>

Open in new window


this is how it looks in the console.log -

"<select style ='width:100%;' class='formInput' name='property'2527'' id='property'2527''><option value=''>- select -</option>"
1
:
"<option value='test1' >test1</option>"
2
:
"<option value='test2' >test2</option>"
3
:
"<option value='test3' >test3</option>"
4
:
"</select>"

Open in new window


So far so good to me it looks in correct order.

but when i append the coniner i get the following display

<select style="width:100%;" class="formInput" name="property" 2527''="" id="property"><option value="">- select -</option></select>
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>

Open in new window


as you can see this is a different format from the array the options are outside the select.

here is how the array is set-up -

if($cusData['propertyType'] >=4 && $cusData['propertyType'] <=6) {
							$teststring = ["<select style ='width:100%;' class='formInput' name='property'".$cusData['propertyId']."'' id='property'".$cusData['propertyId']."''><option value=''>- select -</option>"];
							$testResult = "property found";

								$stmt = new Database();

								$query = "SELECT *
											FROM custom_property_values
											WHERE property_id = :propertyID
											ORDER BY id ASC";
								$stmt->query( $query );
								$stmt->bind( ':propertyID', $cusData['propertyId'] );
								$stmt->execute();
								$result = $stmt->all();

								foreach($result as $selectData){
									array_push($teststring , "<option value='".$selectData['value']."' ".($subrow['infomation'] == $selectData['value'] ? "selected='selected'" : "").">".$selectData['value']."</option>");

								}//selectData
								
								array_push($teststring, "</select>");

Open in new window


any hints to what i am doing wrong ?
0
I have been converting data to csv files simply by making the href target the controller responsible for it and when the user clicks on the link, the csv file downloads automatically.

However, in this particular case I actually need to send some data along where I didn't for the others. So, when just fetching some data I simply did the below and that points directly to the controller responsible for creating the file.

<a href="<?php echo URLROOT; ?>/Widgets/exportUsers" class="m-widget4__icon" download>
	<i class="la la-download"></i>
</a>

Open in new window



Here is the jQuery and Ajax for the date range picker. I have to split the dates so I have a start date and end date to pass through.

		$( '.salesclick' ).on('click', function(e) {
			e.preventDefault();
			var wholeDate = $( '#daterange' ).val();
			var index = wholeDate.indexOf(" ");  
			var start_date = wholeDate.substr(0, index); 
			var end_date = wholeDate.substr(index + 2); 
			$.ajax({
				url: url + '/Widgets/exportSales',
				type: 'POST',
				data: {start_date: start_date, end_date: end_date}
			})
			.done(function (data) {
				alert(data);
			})
		});

Open in new window


That goes to my controller:

      
	$start_date = $_POST['start_date'];
		$end_date = $_POST['end_date'];
		
		$results = $this->DashboardModel->listSales($start_date, $end_date);
		$filename = 'Sales_' . date('dmY') . '.csv'; 
			
			header("Content-Description: File Transfer");
			header("Content-Type: application/csv");
			header("Content-Disposition: attachment; filename=$filename");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

			
			$handle = fopen('php://output', 'w');
		
			$header = array("Order Date"); 
			fputcsv($handle, $header);		
				foreach ($results as $result):
					fputcsv($handle, $result);
				endforeach;

			fclose($handle);
	}

Open in new window


And here is the model:

		$this->db->query("SELECT `order_date` FROM `order_summary` WHERE `order_date` BETWEEN :start_date AND :end_date");
		$this->db->bind(":start_date", $start_date);
		$this->db->bind(":end:date", $end_date);
		$results = $this->db->arraySet();
		return $results;

Open in new window


I am getting an error when just trying to see the data:

Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Then there is another bit about
Dashboard-&gt;listSales('2018-08-06', '2018-08-06')
0
How can I make the datatable on https://www.gopherstateevents.com/results/fitness_events/results_scrollx.asp?event_id=794 show all rows and not show a search bar?

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