2

I want to pass a nested javascript array that is dynamically generated to a php file to later insert it into the database.

The array is dynamically generated inside a Javascript file. Now i want to pass that array to a php file that will insert that data dynamically into a database.

I have found multiple examples of this question on stackoverflow but none suit my situation (they are all working from inside an HTML file).

The array I am trying to pass:

1.  0:
  1.    cleintDate:"31/08/17"
  2.    cleintExpirydate:"29/11/17"
  3.    cleintState:"Department"
  4.    clientCode:"clientcode"
  5.    clientName:"Name"
  6.    messages:Array(2)
1.  0:
   1.   messageClient:"Name"
   2.   messageDate:"2017-08-31T00:00:00"
   3.   messageSubject:"subject "
   4.   messageText:"messageText "
   5.   messageTime:"13:22"
   6.   messageType:"link"
   7.   __proto__:Object
   2.   1:
   1.   messageClient:"Name"
   2.   messageDate:"2017-08-31T00:00:00"
   3.   messageSubject:"subject "
   4.   messageText:"messageText "
   5.   messageTime:"13:22"
   6.   messageType:"link"
   7.   __proto__:Object
   3.   length:2

**Note:**The above example contains 2 messages inside the array but there are examples of 54 messages inside the array. (Text of array slightly edited to hide personal information).

How I generate this array:

matches[0].forEach(function(match, index) {
var cleintcode = /<div\s*class="t_seg_codCliente">(.*?)<\/div>/.exec(match)[1];
var cleintname = /<div\s*class="t_seg_nomCliente">(.*?)<\/div>/.exec(match)[1];
var taxId = /<div\s*class="t_seg_nifCliente">(.*?)<\/div>/.exec(match)[1];
var date = /<div\s*class="t_seg_fechaPresCliente">(.*?)<\/div>/.exec(match)[1];
var state = /<div\s*class="t_seg_estadoCliente">(.*?)<\/div>/.exec(match)[1];
var expirydate = /<div\s*class="t_seg_fechaCadCliente">(.*?)<\/div>/.exec(match)[1];
var communications = /<div\s*class="t_seg_comCliente"><a .*;">(.*?)<\/a>/.exec(match)[1];
var comclient = /<div\s*class="t_seg_comCliente"><a href="javaScript:popupComs\('(.*?)'/.exec(match)[1];
var messages = "link" + comclient;

var html1 = httpGet(messages);

const cleanupDocString = html1.replace(/(?:<!--|-->)/gm, '');

parser = new DOMParser();

htmlDoc = parser.parseFromString(cleanupDocString, "text/html");

var communicationsvalue = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;

if (communicationsvalue.indexOf('No existen comunicaciones asociadas a este cliente.') !== -1) {
  console.log("This chat does not contain any communiction!");
} else {

  var adiv = document.createElement("div"),
    msgs = [],
    trs;

  adiv.innerHTML = cleanupDocString;
  trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
  trs.forEach(function(tr) {
    var d = [];
    tr.querySelectorAll("td")
      .forEach(function(td) {
        var img = td.querySelector("img"),
          src = img && img.attributes.getNamedItem("src").value;
        d.push(src || td.textContent);
      });
    msgs.push(d);
  });

  var mappedArray = msgs.map((msg) => {
    return {
      messageDate: msg[0],
      messageTime: msg[1],
      messageType: msg[2],
      messageClient: msg[3],
      messageSubject: msg[4],
      messageText: msg[5]
    }
  });

  var messageData = [{
    clientCode: cleintcode,
    clientName: cleintname,
    taxID: taxId,
    cleintDate: date,
    cleintState: state,
    cleintExpirydate: expirydate,
    messages: mappedArray
  }];

  console.log(messageData);
}
});

The code I am trying to use to pass the array:

$.ajax({
      type: "POST",
      url: "../php/messageProcessing.php",
      data: {
        "id": 1,
        "myJSArray": JSON.stringify(messageData)
      },
      success: function(data) {
        alert(data);
      }
    });

The error it gives me:

Uncaught ReferenceError: $ is not defined
at ProcessAJAXRequest (getPagesSource.js:126)
at getPagesSource.js:139
at Array.forEach (<anonymous>)
at DOMtoString (getPagesSource.js:62)
at getPagesSource.js:150

Summary:

How do i pass a Javascript array with Ajax (or any other solution) from a external Javascript file.

And how do I dynamically get each piece of data from messages to insert into the Database.

Thanks for any piece of help!

  • `Uncaught ReferenceError: $ is not defined` means that jQuery is not loaded. Be sure you're loading it before that script. Also, you don't need to "stringify" the array. Just send the array via POST and parse the request in php. – Frondor Sep 11 '17 at 07:47
  • Yea i read that aswell but can i declare Jquery inside a javascript file? –  Sep 11 '17 at 07:50
  • oh this is a chrome plugin, perhaps you should read https://stackoverflow.com/questions/21317476/how-to-use-jquery-in-chrome-extension, and consider what @Frondor said about: Also, you don't need to "stringify" the array. Just send the array via POST and parse the request in php – David Sep 11 '17 at 07:59
  • @David I looked at that post but i cant seem to be able to make it work. Doesn't matter where i put it. –  Sep 11 '17 at 08:25

1 Answers1

1

The problem seems to be that you have used JQuery without including the JQuery library on the page. The JQuery library exposes a global variable $ and must be loaded into the global context before being used by other javascript files.

$.ajax({
  type: "POST",
  url: "../php/messageProcessing.php",
  data: {
    "id": 1,
    "myJSArray": JSON.stringify(messageData)
  },
  success: function(data) {
    alert(data);
  }
});

You can fix this by including jQuery somewhere in the page from the cdn (lastest version):

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

Alternatively, if you were not intending to use a JavaScript library, you will have to look into how to use XmlHttpRequest to do what you are looking for. This is built into the javascript language itself.

how do I dynamically get each piece of data from messages to insert into the Database?

You will receive a POST request in the PHP script with the myJSArray in the body. You will be able to access it via $_POST['myJSArray'], you will then need to parse it as JSON and then treat is as any other kind of PHP object.

Eladian
  • 958
  • 10
  • 29
  • Is –  Sep 11 '17 at 07:51
  • For more information on including jQuery in chrome extensions refer to this post https://stackoverflow.com/questions/21317476/how-to-use-jquery-in-chrome-extension – Eladian Sep 11 '17 at 07:58
  • I tried doing the same but it still gives me the same error back. –  Sep 11 '17 at 08:17
  • I am now trying to get the XMLHttpRequest to work but it doesnt seem to find my php file when i use ../php/messageProcessing.php? Is this because the php file isnt in the actual webbrowsers folder? –  Sep 11 '17 at 08:52
  • i think you need to specify the full url to your php script url: "http://www.servername/pathtophp/messageProcessing.php", – David Sep 11 '17 at 09:31