Home > Blockchain >  Why Ajax is not able to send array data?
Why Ajax is not able to send array data?

Time:12-08

Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64

this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.

All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data


 var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];


  $(function () {
    var frm = $("#saveform");
    frm.submit(function (ev) {
      $.ajax({
        type: frm.attr("method"),
        url: frm.attr("action"),
        data: {
          data: imagesBase64,
          PubId: $("#Publications").val(),
          sdate: $("#datepicker").val(), 
          pnumber: $("#pnumber").val()
        },
        cache: false,
        error: function (err, data) {
          console.log("There was an error. Try again please!"   data, err);
        },
        success: function (data) {
          alert("New message received");
        },
      });
      ev.preventDefault();
    });
  });

In PHP page -

print_r($_POST['data']);

it gives an error undefined data, though when I tried with postman everything is working fine.

CodePudding user response:

also I am not able to see error in console because it redirected to URL where I am posting the data

That's the problem.

You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.

This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.

Possible reasons that might apply are:

  • var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS
  • You don't have jQuery loaded so the call to $ fails
  • You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).

Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:

The cog menu in Firefox's developer tools

CodePudding user response:

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.

  • Related