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!

4
  • 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. Commented Sep 11, 2017 at 7:47
  • Yea i read that aswell but can i declare Jquery inside a javascript file? Commented Sep 11, 2017 at 7:50
  • oh this is a chrome plugin, perhaps you should read stackoverflow.com/questions/21317476/…, 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 Commented Sep 11, 2017 at 7: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. Commented Sep 11, 2017 at 8:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is <script> not meant for an HTML page? Seeing as i am not running any HTML files because this is a chrome plugin. Or can i just declare <script> inside a javascript file?
For more information on including jQuery in chrome extensions refer to this post stackoverflow.com/questions/21317476/…
I tried doing the same but it still gives me the same error back.
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?
i think you need to specify the full url to your php script url: "servername/pathtophp/messageProcessing.php",

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.