Reputation: 79
I have written this code in choose-item.php
function myFunction() {
var values =[];
$('#sortable2').each(function(){// id of ul
var li = $(this).find('li')//get each li in ul
var res = li.text().split("::");
var myJsonString = JSON.stringify(res);
$.post("choose-items.php", {"result": myJsonString});
console.log(myJsonString)//get text of each li*/
})
}
in the same page I have added this php script
if(!empty($_POST['result']))
{
$res = $_POST['result'];
echo "alert('$res')";
}
But I am not getting the result in my php variable.
any body can help? Thanks
Upvotes: 1
Views: 63
Reputation: 6673
jQuery could to be like this:
[...]
$.post("choose-items.php", {"result": myJsonString})
.done(function (data)
{ alert(data); }); // Your alert can be inside the function
[...]
PHP could to be like this:
if(isset($_POST['result']) && !empty($_POST['result'])):
$res = $_POST['result'];
echo $res; // This is the data you're passing back
endif;
However, your response will not be accurate since you're not sending it to a generic handler page followed then by your response you wanted to send ($res
).
The response the request will receive is anything that the handler puts out onto the screen, so in your case, your response will be your normal page.
TL;DR & IMO: You should create a new PHP file for handling this so your code is laid out and so your response doesn't get mixed up with page content.
Upvotes: 1
Reputation: 1173
If you are using wrong variable names in $_POST to reference which actually do not exists then you will not be able to get the value of desired variable :
//$_POST['result[]'] do not exists but $_POST['result'] is what you passed in $.post
if(!empty($_POST['result[]']))
{
$res = $_POST['result'];
echo "alert('$res')";
}
You should correct the if condition to :
if(!empty($_POST['result']))
{
$res = $_POST['result'];
echo "alert('$res')";
}
Also as you are using the same page to return your ajax response so you should move your process logic for ajax at top of the page with a conditional check so that it only executes when ajax is fired and not on page load. Code should be like this
// Conditional statements to allow ease of HTML
if(!empty($_POST['result'])):
$res = $_POST['result'];
echo "alert('$res')";
exit;
else:
// your normal page content
endif;
You should do a print_r at top of you script to know what is actually getting posted, or you can inspect the console ajax request for same
echo "<pre>"
print_r($_POST);
echo "</pre>"
Upvotes: 1