1

I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:

    var rowArr=[];
    var currow=$(this.closest('tr'));
    var col1=currow.find('td:eq(0)').text();
    rowArr.push(col1);
    var col2=currow.find('td:eq(1)').text();
    rowArr.push(col2);
    var col3=currow.find('td:eq(2)').text();
    rowArr.push(col3);
    var myJSONText = JSON.stringify( rowArr );

   $.ajax({ 
        type: "POST", 
        url: "jsonRecieve.php", 
        data: { emps : myJSONText}, 
        success: function() { 
        alert("Success"); 
    } 
 }); 

so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:

<?php
   $rowAr=$_POST['emps'];
   print_r($rowAr);
?>

is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?

1 Answer 1

1

Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-

ON JS

$.ajax({ 
        type: "POST", 
        url: "jsonRecieve.php", 
        data: { emps : myJSONText}, 
        success: function(data) {     
        alert(data);  // alert your data to see that returns from server
    }

ON PHP

<?php
   $rowAr=$_POST['emps'];
   $array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
   print_r($array);
   die('response from the server');
?>
Sign up to request clarification or add additional context in comments.

4 Comments

so I got it to print through your edits, thank you. But when it does that does it mean that the array is now saved under $_POST['emps']? because I want to fill in a forms input boxes with the arrays information in php and when I try to initialize an array in my php file with $_POST['emps'] it says that it is an undefined index
and also in the ajax function under url, do you have to send it to a separate php file or are you able to send it in the same file?
Yes you can get the form input values with serializeArray before passing them to your php file, have a look here gomakethings.com/getting-an-array-of-form-data-with-vanilla-js also the same file can do your job. No need to use another php file
no, I mean id like to use the javascript array that has been converted into php to be used as placeholders for the form. How will I do that?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.