Receive data from php using AJAX - php

I am working on a function, where if a user selects a value from a drop down list, then this calls an AJAX function, which then should get me a list of Names and their email addresses
$.ajax({
type:'POST',
url:'get_distusers.php',
data:'dist_id='+dist_id+'&study_id='+study_id,
success: function(data){
$('#dist_list2').html(data);
$('#dist_list').val(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error."+textStatus+" - " + XMLHttpRequest.status);
}
});
Then the other page has this to send back the list of names and emails
unset($contact);
if ($count_du>0) {
while($row_du = mysqli_fetch_array($result_du)) {
if(!empty($contacts))
$contacts.="<br>, ";
$contact['name']=$row_du[0];
$contact['email']=$row_du[1];
}
}
$contacts[]=$contact;
//$contacts=array($contact_email,$contact_name);
//echo $sql_patrand;
echo json_encode($contacts);
However, when I try to retrieve the contact list, I either get the word object or nothing.
Can someone tell me what I am doing wrong?

You have return echo json_encode($contacts); json format from the your php code, but your ajax not understand json format because you have not set dataType: 'json' param, Please check the below mention code, it will defiantly helpful, any query comment inside answer....
$.ajax({
type:'POST',
url:'get_distusers.php',
data:'dist_id='+dist_id+'&study_id='+study_id,
dataType: 'json', //NOTE:Your missing point - update first
success: function(data){
console.log(data); //Print your data, so it will help you to how manage
$('#dist_list2').html(data);
$('#dist_list').val(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error."+textStatus+" - " + XMLHttpRequest.status);
}
});

Related

How to post value from one php page to another using ajax

I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.
Here is my code:
$("#requirementtable tbody tr").on("click", function(){
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: desc,
success: function (data, textStatus, jqXHR)
{
alert(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("some error occured->" + jqXHR.responseJSON);
}
})
})
this is my php code:
<?php
$data = $_POST['data'];
echo $data;
?>
Check the desc variable has some value in it and you have to post data like,
data: {data:desc},
AJAX Code,
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: {data:desc},
success: function (data, textStatus, jqXHR) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
And in PHP use isset() to prevent undefined errors like,
<?php
$data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
echo $data;
?>
If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.
here is a simple example that contains your code and solution
//Data Object
var obj={
name:"uneeb",
city:"gujranwala",
state: "punjab"
};
//Data Object
//Ajax Request to Server
$.ajax({
type: 'post',
url: 'someFile.php',
data:object,
success: function (data) {
//do something here
}
});
//Ajax Request to Server
//PHP
echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab
//PHP
Replace the followings:
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
// remove ^^^^^^^^^^ since you're currently in tr click
desc = $(this).find("td:nth-child(4)").text().trim();
And replace to:
data: desc,
With:
data: {data:desc}, //to pass data as object as you don't have serialized data
And inside your php code, you can get data using $_POST['data'].
replace this data: desc, field in your ajax to data:{data: desc},, this is the cause you are not getting data in your php code

Send variable to PHP using AJAX

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

Issues with Jquery/PHP ajax form submission

I am using the following code to post form data to a php file..
jQuery("#form-submit").click(function(data){
var url = "save-data.php";
jQuery.ajax({
type: "POST",
data: jQuery('#my-form').serialize(),
url: url,
cache : "false",
success: function(data){
jQuery("#dl-message").html(data);
jQuery("#dl-message").css('background-color', '#0C3');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
},
error: function ( jqXHR, textStatus, errorThrown){
jQuery("#dl-message").html('There was an error saving your form: ' + errorThrown);
jQuery("#dl-message").css('background-color', '#F33');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
}
});
return false;
});
and then in my php file I am simply looking for $_POST['field-name'] to see if the contents of the form were posted. The ajax call returns successful, however no data from the form seems to be posted to the PHP file. When I call...
$name = $_POST['name'];
echo "Your name is: " . $name;
I get nothing.... Does anyone see anything wrong with my ajax call at all?
Thanks so much for your time...
So it seems the post was empty at the first place (btw you can include your last three posts inside the question by editing it). Are you sure your form's id is 'my-form'?

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

ajax - check if a username exists + return message if it does

im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.
I'm having some trouble and have a few questions.
I have my input field plus js:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').on('blur', checkdb);
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: 'desiredUsername='+desiredUsername,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
});
</script>
<input type="text" name="username" id="username">
and my check-db.php file:
$mysqli = mysqli_connect("localhost","connection info");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$desiredUsername = $_POST['desiredUsername'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' ");
$stmt->bind_param('s', $desiredUsername);
$stmt->execute();
firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?
then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?
thanks!
On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :
echo json_encode($datas); //can be array or whatever
Then on the Client side :
$.ajax({
method: 'POST',
dataType:'json',
data: {'username' : desiredUsername}, //then getting $_POST['username']
success: function(datas) {
console.log(datas); //Your previous data from the server side
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
try
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: {
desiredUsername: desiredUsername
},
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
You have an error when sending the data, you should send a JS Object as data, like this:
data: { desiredUsername: desiredUsername },

Categories