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

Hi, I have a PHP script which calls another PHP script via a jQuery ajax call.  I can see that the call is successful and that there is a proper response from the network activity.  However I am having trouble processing that response in the calling PHP/JavaScript code.

Here's my attempt:

demo.html

From the network activity I see the response is:

["data1","data2"] and this is what I am expecting (actual data not shown)

But I cannot 'see' nor process these data in the success data in the calling code shown above.  The alerts do not fire.

Any guidance will be most appreciated and thank you in anticipation.
0
Bootstrap 4: Exploring New Features
LVL 13
Bootstrap 4: Exploring New Features

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

We are getting a CORS error when trying to run and API request from one of our subdomains to another. I saw an htaccess fix...

<ifmodule mod_headers.c="">
   SetEnvIf Origin "^(.*\.MyDomain\.com)$" ORIGIN_SUB_DOMAIN=$1
   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
   Header set Access-Control-Allow-Methods: "*"
   Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</ifmodule>

I added that to the htaccess file of where the API request was going *to*, but we still get the error. Does it need to go in the htaccess of the site the request is coming *from*? Or both? In other words, does the htaccess stuff need to live where the request originates or where the request is processed? Or both?
0
Hello,

I got a data object like below. This is a part of RestAPI method return. But when i call REST API using Jquery AJAX , I am getting Name, Address correct but the List of ProductName is coming is empty.

Is there any reason whey List is empty. I checked the method it is having the values but at the side of Jquery Ajax response i am getting it as empty.

public class TotalRectificationOverTime
    {
       
        public string Name;
       
        public int Address;

        public List<string> ProductName;

    }
0
Error with resources when using ajaxtabcontainer.  I have other ajaxcontrols on the page (calendar) that have not had a problem, but after adding the tab container to the page I get an error as follows.

Error Rendering Control - Table2 An unhandled exception has occurred.
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "AjaxControlToolkit.Properties.Resources.NET4.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed.

Open in new window

Below is the code:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager> 
<asp:Table ID="Table2" runat="server" Height="70%" Width="100%">
                <asp:TableRow>
                <asp:TableCell ID="TableCell22" RowSpan="6" Width="20%" VerticalAlign="Top" HorizontalAlign="Center" 
                BorderStyle="Inset" BorderWidth="2" BorderColor="Gray" runat="server" Height="100%" CssClass="CellPadding">
<asp:Panel ID="Panel2" runat="server">
                    <ajaxToolkit:TabContainer ID="TabContainer1" runat="server" BackColor="Black" BorderStyle="None" 
                        Font-Names="Arial" Font-Size="10" ForeColor="#FFFFCC" AutoPostBack="True" TabStripPlacement="Bottom">
                        
                        <ajaxToolkit:TabPanel runat="server" ForeColor="#FFFFCC" Font-Size="10" 
          

Open in new window

0
Hi,

I have set up a very simple update panel page as I was getting a full postback each time on a new site I have set up in VWD, it refuses to update just the update panel, but if I copy over the page to the older site it works fine.

They have identical web configs and I'm not using a master page so no interference there.

Same on the live server, one work, one doesn't - any ideas?

Cheers
Karl
0
Greetings:

I am quite confused as to what I can do and what I cannot do within the UploadComplete event of the AjaxFileUpload control.

There are 2 ASPX Label controls which are assigned values within the UploadComplete event, however, the assigned values do not appear on the page after the event completes. The uploaded file is saved to the designated directory, however.

I'm including the ASPX, the VB code behind and the web.config files as follows:

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title></title>
</head>
<body>
	<form id="form1" runat="server">
		<div>

			<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

			<asp:Label ID="Label1" runat="server"></asp:Label>

			<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" AllowedFileTypes="jpeg,jpg,gif" />

			<asp:Label ID="Label2" runat="server"></asp:Label>

		</div>
	</form>
</body>
</html>

Open in new window

VB Code Behind
Imports AjaxControlToolkit

Partial Class _Default
	Inherits System.Web.UI.Page

	Private Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete

		Label1.Text = "Here we are 1."

		AjaxFileUpload1.SaveAs("C:\inetpub\ClientWebs\AjaxFileUploadSync\Images\" & e.FileName)

		Label2.Text = "Here we are 2."

	End Sub

End Class

Open in new window

web.config
<?xml version="1.0" encoding="utf-8"?>

<configuration>

	<system.web>
		<compilation debug="true" targetFramework="4.0" />
	<pages>
      <controls>
        <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
      </controls>
    </pages></system.web>

	<system.webServer>

		<handlers>

			<add name="AjaxFileUploadHandler" verb="*" path="AjaxFileUploadHandler.axd" type="AjaxControlToolkit.AjaxFileUploadHandler, AjaxControlToolkit" />

		</handlers>

	</system.webServer>
</configuration>

Open in new window

Any assistance you might provide would be most helpful.


Much thanks,
David Bach
0
Hello !

I ask your help to be able to have the following format in an input : a1B2-c3D4-R2EJ-s1fe
This is not a credit card format, but a gift voucher.
The user can copy / paste the code or simply write it.
I tried to dig a little but I'm not well advanced.

Can you help me please ?
thank you in advance
0
I'm doing an ajax call to a ColdFusion function to return a query. It should return a single record with three columns for an event's title, description, and date. I want to place each of those three pieces in their corresponding divs. Everything is working fine but I can't figure out how to access the results, and the options I've Googled up have failed me. How do I get the JSON equivalent of CF's queryName.columnName? Thanks!

The jQuery I'm using is as follows:
	$('.calendar-event').click(function(){
		 var id = this.id;
		 var splitid = id.split('_');
		 var eventID = splitid[1];
				console.log(eventID);
		 // AJAX request
		 $.ajax({
			type: "POST",
			url: "/cfc/calendar.cfc?method=getEventAjax",
		  dataType: "json",
			data: {
			 returnFormat: "json",
			 eventID: eventID
		 },
			success: function(response){ 
				console.log(response);
				// Add response in Modal body
				$('#eventTitle').html(what goes here for the title?);
				$('#eventDescription').html(what goes here for the description?);
				$('#eventDate').html(what goes here for the date, and what about formatting?);
				// Display Modal
				$('#eventModal').modal('show'); 
			},
			error: function (response) {
				console.log(response);
        $("#modal-body").html("This event could not be loaded.");
				$("#eventModal").modal("show"); 
      }
		});
	 });

Open in new window


The function is simple:
<cffunction name="getEventAjax" access="remote" returntype="query" hint="returns info for single event">
		<cfargument name="eventID" type="numeric" required="yes">
		<cfquery name="qGetEvent" datasource="#APPLICATION.ds#">
			SELECT eventTitle, eventDescription, eventDate FROM calendar
			WHERE ID = <cfqueryparam value="#ARGUMENTS.eventID#" cfsqltype="CF_SQL_INTEGER">
		</cfquery>
		<cfreturn qGetEvent>
	</cffunction>

Open in new window


In the console log I'm getting
{COLUMNS(3), DATA: Array(1)},
COLUMNS: (3) ["EVENTTITLE", "EVENTDESCRIPTION", "EVENTDATE"]
DATA: Array(1)
0: Array(3)
0: "Radio Interview with Lucy Ann Lance of 1290AM"
1: "<p>Interview will take place at 8:20am EST</p>"
2: "July, 29 2019 00:00:00"
0
After attempting to edit a mysql record in node.js, I am receiving null results when I review the mysql query report and the affected rows are returning zero.  There is no change to the record. However, the backend says that the results are not null, the sql query is not null and that the req.body for all the values are not null.

Here is the mysql general query log:

190717 16:42:40	    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
190717 16:42:42	    3 Query	SELECT * FROM stores
190717 16:43:13	    3 Query	UPDATE stores SET `station` = NULL, `address` = NULL, `monthly c-store sales` = NULL,`operator` = NULL, `top sku` = NULL WHERE `id` = NULL

Open in new window


These are the results returned on the frontend:

affectedRows: 0
changedRows: 0
fieldCount: 0
insertId: 0
message: ""
protocol41: true
serverStatus: 2
warningCount: 0

Open in new window


However, the backend says that the values are not null after putting in the following code:

if (results !== null) {
        console.log('results is not null');
        }else{
        console.log('results is null');
        };


      if (sql !== null) {
      console.log('sql is not null');
      }else{
      console.log('sql is null');
      };

      if (req.body.Station !== null) {
        console.log('req.body is not null');
        }else{
        console.log('req.body is null');
        };

Open in new window


Here are the results.....
{ station: 'Hopefully',
  address: 'this',
  monthlycstoresales: '200',
  operator: 'will',
  topsku: 'work',
  id: '7' }

results is not null

sql is not null

req.body is not null

Open in new window



Here is the backend code:

Open in new window

0
Dear Experts, I'm trying to learn How to Make Load More Results From Database using jQuery,Ajax,PHP and MySQL

I found this simple code on the web which is suppose be working but I have the below error.

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in ....

I tried a few things but it didn't work. What do you suggest I should do?

On the top of my two pages I have database connection, and my code is :
<?php 
.......
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
?>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $("#load").click(function () {
                    loadmore();
                });
            });

            function loadmore()
            {
                var val = document.getElementById("result_no").value;
                $.ajax({
                    type: 'post',
                    url: 'getrecord.php',
                    data: {
                        getresult: val
                    },
                    success: function (response) {
                        var content = document.getElementById("result_para");
                        content.innerHTML = content.innerHTML + response;
                        document.getElementById("result_no").value = Number(val) + 2;
                    }
                });
     

Open in new window

0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

I have written my first Spring MVC controller. While I have no problems with GET requests, I am still having some issues with POST methods.

This is the code in my controller:
@RequestMapping(value = "/editorsWriters", method = RequestMethod.POST)
    public <HttpServletRequest> ResponseEntity<List<FreelancerContactWriterListView>> getEditorsWriters(
                                                                    @RequestParam int[] languageIds, 
                                                                    @RequestParam int[] summaryGroupIds, 
                                                                    @RequestParam String[] writerStates,
                                                                    HttpServletRequest request, HttpServletResponse response) {

        WriterState[] writerState = Arrays.copyOf(writerStates, writerStates.length, WriterState[].class);
        

        List<FreelancerContactWriterListView> writers = writerService.getActiveWriters(languageIds, summaryGroupIds, writerState)
                                                                    .stream()
                                                                    .map(writer -> this.convertTo(writer))
                                                                    .collect(Collectors.toList());

        
           return new ResponseEntity<List<FreelancerContactWriterListView>>(writers, HttpStatus.OK);
    }

Open in new window


and this is the JavaScript code:

 $("#search").on("click", function(e) {
            var languages=$("#languages").val();
            var summaryGroups = $("#summaryGroups").val();
            var writerStates = $("#writerState").val();
            
            var myObject = new Object();
            myObject.languageIds = languages;
            myObject.summaryGroupIds = summaryGroups;
            myObject.writerStates = writerStates;

            var myData = JSON.stringify(myObject);

            console.log(myData);

            $.ajax({
                method: 'POST',
                dataType: 'json',
                data: myData,
                url:'/api/pps/contactFreelancers/editorsWriters',
                contentType: "application/json"
            })
            
        });

Open in new window


This is the JSON sent:

{"languageIds":["1"],"summaryGroupIds":["11"],"writerStates":["PROBATION","REGULAR"]}

Open in new window


The problem is that I get a POST 404 (Not Found) error in the JavaScript console
POST https://dev1.getabstract.com/api/pps/contactFreelancers/editorsWriters 404 (Not Found)

and the following message in the terminal of my IDE:

2019-07-14 22:49:06,923 DEBUG [BaseControllerExceptionHandler] Page not found for the URL https://dev1.getabstract.com/api/pps/contactFreelancers/editorsWriters with query null: Required int[] parameter 'languageIds' is not present

Open in new window



So it is reaching or sending the POST to the correct URL, but what am I doing wrong?

Is the way I have created the data wrong?
languages, summaryGroups and writersStates are all arrays and I am putting them together into one JSON.

Thanks for your help

Massimo
0
I have a search field which provides data from a database for the user. It works well but the autocomplete coding doesn't.  The station names are suppose to automatically show. Please see the code below...

<h3>Search Box</h3>
    <label>Type Station Name</label>
    <input id = "stationBox" type="text">
    <ul id="autoList"></ul>
    <button id ="stationOne" >Submit</button>
    <div id="searchResult"></div>

Open in new window


//Inserting information in a search bar--
<script>
  $(document).ready(() => {
    $('#stationOne').click(() => {
      var requestUrl = 'stationNames/' + $('#stationBox').val();
      console.log('making ajax request to', requestUrl)
      $.ajax({
          url:requestUrl,
          type:'GET',
          datatype:'json',
          success: (data) => {
          console.log('You received some', data);
            
          var search_data = '';
            $.each(data, function (key, value) {
              //console.log(value.ID);
              search_data += '<li>ID: ' + value.ID + '</li>' +
                '<li>Station: ' + value.Station + '</li>' +
                '<li>Address: ' + value.Address + '</li>' +
                '<li>Sales: ' + value.Monthly_CStore_Sales + '</li>' +
                '<li>Operator: ' + value.Operator + '</li>' +
                '<li>Top SKU: ' + value.Top_SKU + '</li>' +
                '</<li>' + '<br/>';
            });

            $('#searchResult').html(search_data);
          }
      })
    });
  });
         

Open in new window

1
Good Morning Dear Expert,

I'm actually using Cfswitch expression to play several module on the same page with a page's "refreshment" when i submit the form.. i would like to use Coldfusion and Ajax for a different experience.. Is it possible on a input or submit Click, to call an Ajax function on the same page and in this function, change the variable of the CFcase expression to play a different mudule ?

Any response will be helpful..
0
I am using jQuery   I have a a dropdown box and the the code is in a dialog box that opens from an onclick event(). I have a .change() event that fires twice.  I know this problem is caused by the dialog box because when I remove  the dialog box it works fine

Then at a later point the user selects one of these values

and I detect the change with this

			
$('#Code').change(function () {
				      var value = $(this).val();
				      var text = $(this).find(":selected").text();
				      alert(' Text = ' + text  + '  value = '  +value  );
                                      .... do more stuff
			        });

Open in new window

0
I have a form that includes a file upload that I'm submitting with Ajax. When the submit button is pressed, I want to change the text of the button to "Please wait" and disable it. Whether the form is successfully submitted or not, change the text back to "submit" and re-enable it once the function completes. This is not working. I've Googled up several suggested methods and haven't managed to get any of them to work, but I may be placing them incorrectly. Can you see where I'm going wrong? Thanks!

the jQuery in the .js file:

$(document).ready(function() {
	
	// submitting the video form
  $("#video-form").submit(function(e){	 
		 
		e.preventDefault();
		 		 
    var formData = new FormData($(this)[0]);
		 
		$.ajax({
			type: "POST",
			url: "ajax-video-submit.cfm",
			
			beforeSend: function (){
      	$("#submitVideo").val("Please wait...").attr("disabled", "disabled");
      },
			
			data: formData,
      async: false,
      cache: false,
      contentType: false,
      enctype: 'multipart/form-data',
      processData: false,
      
			success: function (response) {
      	$('#video-alert').html(response);
      },
			
			complete: function () {
       
      	$("#submitVideo").val("Submit").removeAttr("disabled");
      }
			

		});
	});
});

Open in new window


the button code:
<input type="submit" name="submitVideo" id="submitVideo" value="Submit" class="btn btn-primary btn-xl mt-2">

Open in new window

0
Hello everybody,

I need JS to fetch all the data in the DB for one or more auto-generated stuff. First I create a global variable and make a forEach loop to get my data from the DB for each instance:
var datosRae = new Array();

arrayRaes.forEach(getRaesOriginalData);

Open in new window

Inside the function I call in the loop, I use AJAX to fetch the data arrays:
function getRaesOriginalData(value, uid, yacimiento) {
	
	var dataString = 'uid=' + uid + '&yacimiento=' + yacimiento + '&raeId=' + value;
	
	$.ajax ({
		url: 'get-rae-datos-originales.php',
		type: 'POST',
		data: dataString,
		dataType: 'json',
		success: function (d) {
			console.log(d);
			datosRae[value] = d;
		}
	});
	
}

Open in new window

The result is as expected (if 3 items are called, it brings me 3 arrays with all the data), except when I need to use that data. As you can see in the last line inside the success function of the AJAX call, I insert the arrays into the global array while giving each entry the ID for that DB entry. When I try to print in the console, let's say the ID number 15 with:
console.log(datosRae[15]);

Open in new window

it gives me "undefined". If I remove the ID and try to print the whole global array, it prints the following:
Global array resultHow can I call each array from within the global array using it's ID? What am I missing?

Thanks in advance!
0
Hello everyone,

I have a PHP page that generates content dynamically upon creation. It adds TABS with the same FORM in each one, but referencing different IDs from a table in the DB. I need to make listeners for each input, radio button, checkbox, textarea and button in each form and have AJAX update the DB immediately when any of these values change.

Since the tabs and forms are created automatically, they are all the same except for the ID of each element, that get the DB id that is connected to each form. I chose to use the format "this_is_the_button_something-XX" where XX is the ID from the DB that that form is currently attached to.

I've trying/testing the following code to detect the changes individually for each element:
const checkbox_rae_forma_de_contacto_telefono = document.getElementById('rae_forma_de_contacto_telefono-14')

checkbox_rae_forma_de_contacto_telefono.addEventListener('change', (event) => {
	
	if (event.target.checked) {
		
		console.log($('#rae_forma_de_contacto_telefono-14').val());
		
	} else {
		
		console.log('Nada');
		
	}
	
});

const checkbox_rae_forma_de_contacto_radio = document.getElementById('rae_forma_de_contacto_radio-14')

checkbox_rae_forma_de_contacto_radio.addEventListener('change', (event) => {
	
	if (event.target.checked) {
		
		console.log($('#rae_forma_de_contacto_radio-14').val());
		
	} else {
		
		console.log('Nada');
		
	}
	
});

const checkbox_rae_forma_de_contacto_personalmente = 

Open in new window

0
I'm displaying a table that returns users I want to click on the user and edit them in a bootstrap modal. I'm able to do this using ajax but the modal that opens won't load some of the classes I'm using in the form. If I open the modal from that page without using the ajax the form loads and works as it should but I can't load that user id in my where statement. I up to try anything. One example is using the floating labels bootstrap has.
0
I would like to get the latitude and longitudes of an address from the OpenstreetMap Server. I use the following code:
The URI https://nominatim.openstreetmap.org/search/Keizersgracht%202,%20Amsterdam?format=json

gives me the following JSON output:

[
    {
        "place_id": 29597926,
        "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
        "osm_type": "node",
        "osm_id": 2729940028,
        "boundingbox": [
            "52.3654887",
            "52.3655887",
            "4.8878076",
            "4.8879076"
        ],
        "lat": "52.3655387",
        "lon": "4.8878576",
        "display_name": "489B-2, Keizersgracht, Grachtengordel, Amsterdam, Noord-Holland, Nederland, 1017DM, Nederland",
        "class": "place",
        "type": "house",
        "importance": 0.32100000000000006
    },
    {
        "place_id": 29345477,
        "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
        "osm_type": "node",
        "osm_id": 2722023917,
        "boundingbox": [
            "52.3669115",
            "52.3670115",
            "4.8842236",
            "4.8843236"
        ],
        "lat": "52.3669615",
        "lon": "4.8842736",
        "display_name": "460-2, Keizersgracht, Grachtengordel, Amsterdam, Noord-Holland, Nederland, 1016GE, Nederland",
        "class": "place",
        "type": "house",
        "importance": 0.32100000000000006
    },
    {
        "place_id": 

Open in new window

1
Exploring SharePoint 2016
LVL 13
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

I am developing an app using Apache Cordova and I have the following code which fails to execute. The idea of the code is:

1) loop through the array with all orders (JSON)
2) retrieve the customer's name
3) generate a table or <tr>

The problem is point 2 - the code just stops and I have to restart the server.
The array with orders is not that big - around 150 JSON objects which I retrieve when the application loads;
the array with customers is even smaller: just two clients are in the array.

Is this an issue with JavaScript concurrency? I would appreciate it if someone can give me an idea of how to tackle this, as I have spent hours trying to figure out how to make this work.

Surely, it must be possible to retrieve the orders - then lookup the customer's name - and then put the data into another array.

Thanks

Massimo

      /**
       * @description retrieves all orders for megamax and genereates table rows for the HTML table
       */
      this.getAllMegamaxOrders = function () {
        "use strict";
        var mm_orderID = 0;
        var mm_customer_id = "0";
        var mm_orderDate = "";
        var mm_customerName = "";
        var mm_lat = "";
        var mm_lng = "";
        var mm_price = "";
      
        
        //loop through all orders from array allOrders
        for (i = 0; i < app.allOrders.length; i++) {

          //populate local variables
          mm_orderID = app.allOrders[i].id;
          mm_customer_id = 

Open in new window

1
How do I post using jquery ajax?

I am having the issue that I get a wrong username and password error message from the server.
When I try using Postman, I don't have any problems connecting to a server and getting a value back.

I have to make use of .ajax because I have to make a synchronous call.

Am I missing something as part of the ajax POST message?

         * @description Places a new (empty) order for a customer. 
         *              If successful, the system will display a message
         *              informing the user that a number order has been
         *              placed (with the order ID)
         * @param {number} clientID the client's ID
         */
        this.placeNewOrder = function (clientID) {
      
          data = {
            OUCU: oucu,
            password: password,
            client_id: clientID,
            latitude: 41,
            longitude: 0
          };

          $.ajax(
            {
              method : 'POST',
              async : false,
              url : "http://137.108.92.9/openstack/api/orders",
              dataType : 'json',
               success: function (data) {
                        var obj = data;
                        if (obj.status == "success") {
                          //put new order ID into variable
                          newOrderID = (obj.data[0].id);
                          //get client's name and display it on the next page with the new order number
             

Open in new window

0
I'm developing a Cordova app and one of the function is, that it can display orders.
I would like to retrieve all the orders when the app starts and put them into a JavaScript array:


var allOrders = [];			
this.getAllOrders = function() {
				var url = "http://137.108.92.9/openstack/api/orders?OUCU=" + oucu + "&password=" + password;
				/* Get the data */

				$.get(url, function (data) {
					var obj = $.parseJSON(data); // 
					if (obj.status == "success") {
						// was able to get the data successfully 
						// loop through all orders
								$.each(obj.data, function(i, item) {
                  console.log(item);
									app.allOrders.push(item);
                });
          };
				})
      }

Open in new window


The JavaScript array is populated with JSON objects.

How do I read JSON objects out of the array? For example, I would like to find out in which position the Order ID 71415 is.

      //Searches for an order ID
      this.searchOrderID = function(OrderID) {
        ???
      }

Open in new window


I would appreciate it if someone could give me an idea how to read json objects out of a JavaScript array. Searching for an order ID is one thing and then I would like to retrieve the picture URL for example .. I think once I know how to loop through the variable and then read the element ID, it should make it easier for me to implement the other functions.

Thanks for your help

Massimo
JSfiddle: https://jsfiddle.net/mscola75/ksqyem7g/2/



The JavaScript array with data
0
I would like to write a function that returns all orders and puts the OrderIDs in a JavaScript array.

The JSON looks like this:

{
    "status": "success",
    "data": [
        {
            "id": "69507",
            "client_id": "1",
            "date": "2019-05-18 11:02:20",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69514",
            "client_id": "2",
            "date": "2019-05-18 11:15:20",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69513",
            "client_id": "1",
            "date": "2019-05-18 11:15:16",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69511",
            "client_id": "1",
            "date": "2019-05-18 11:13:23",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "69510",
            "client_id": "1",
            "date": "2019-05-18 11:12:01",
            "latitude": "0.00000000",
            "longitude": "0.00000000"
        },
        {
            "id": "71397",
            "client_id": "1",
            "date": "2019-05-20 22:33:36",
            "latitude": "41.00000000",
            "longitude": "0.00000000"
        }
    ]
}

Open in new window


As I'm using jQuery, I use the following method to loop through the array - and then get the "id":

var orderIDs = [];

function getAllOrderIDs() {
  var url = "http://137.108.92.9/openstack/api/orders?OUCU=" + oucu + "&password=" + password;
  /* Get the data */
  $.get(url, function (data) {
    var obj = $.parseJSON(data);
    if (obj.status == "success") {
      // was able to get the data successfully 
      // loop through all orders
      data = $.parseJSON(data);
        $.each(data, function(i, item) {
          //alert(item);
          orderIDs.push(data[item].id);
        });
    };
  })
}

Open in new window


I get the following error message:
index.js:49 Uncaught TypeError: Cannot read property 'id' of undefined

Line 49 is the line of code which I puts the orderID into the array.

Can someone please give me a clue what I'm doing wrong?

Thanks for your help

Massimo
0
Hi there,

I have an issue with my woocommerce mini cart.

The issue I have is that there are a few items that seem to be stuck in the cart no matter if you are logged in or not. If you try and remove them, a few seconds later they appear again.

I thought It might have been outdated plugins and template files, so I have backed up my site and updated everything along with all the template files, still the same issue.

My website is www.ingeniousgifts.co.uk and you can access the slide out mini cart from the top right of the screen.

I have attached a screen record so you can see what happens.

I would really appreciate if someone could help me find out why this is happening and how to fix it?
Home---Ingenious-Gifts.webm
0
  function getContacts(listId, cOnly) {

            if (typeof contactTable !== 'undefined')
                contactTable.destroy();
            contactTable = $('#contactstable').DataTable({
                "serverSide": true,
                "stateSave": true,
                "ordering": false,
                "searching": true,
                "oSearch": {"bSmart": false},
                "searchDelay": 1500,
                "ajax": {
                    "url": "get-contacts.php",
                    "type": "POST",
                    "data": {
                        listId: listId,
                        co: cOnly
                    }
                },
                "rowCallback": function (row, data) {
                },
                "initComplete": function (data) {
         
                },
                "columns": [
                    {"data": "contact"},
                    {"data": "email"},
                    {"data": "company"},
                    {"data": "date"},
                    {"data": "actions"}
                ],
                'columnDefs'        : [      
                { 
                    'searchable'    : false, 
                    'targets'       : [2,3,4] 
                }
            ],
                "order": [[0, 'desc']]
            });


     
        }

Open in new window



so this function creates my dataTable,

all works table it up, i only perform search functions on contact and email,

how ever it is failing to give me exact results , for example first record is  Tim Smith , i can clearly see Tim Smith, i type Tim Smith into the search input provided by data-tables, and he isnt shown in the result ?

https://datatables.net/
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.