I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress. Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
-
1Use web developer tools to view the network request. There you can view the response and the console to view errors. Chrome extensionYolo– Yolo2017年03月17日 16:31:25 +00:00Commented Mar 17, 2017 at 16:31
-
// get the raw POST data $rawData = file_get_contents("php://input"); // this returns null if not valid json echo json_decode($rawData);user7601056– user76010562017年03月17日 17:11:37 +00:00Commented Mar 17, 2017 at 17:11
-
stackoverflow.com/questions/8893574/php-php-input-vs-postuser7601056– user76010562017年03月17日 17:12:27 +00:00Commented Mar 17, 2017 at 17:12
2 Answers 2
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
4 Comments
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
Comments
Explore related questions
See similar questions with these tags.