How to fetch data from database with json_encode of ajax - javascript

I use ajax to fetch data from DB. And I chose alert(valData) in success function to test the data, but unlucky nothing return from
ajax. Then I tested
select contact from IDC WHERE id='5';
It works fine in mysql cmd line.
Here is my js code:
var stNum = 5;
$.ajax({
dataType:'json',
type:"POST",
url:"get_ajax_csc.php",
data:{stNum:stNum},
success:function(data)
{
var valData = data;
alert(valData);
$('#stContact').val(data.stCnt);
$('#stPhone').val(data.stPho);
}
});
Here is my html code:
<div class="divFir">
<label>Contact:</label><input type="text" id="stContact" ><br />
<label>Phone:</label><input type="text" id="stPhone" ><br />
</div>
Here is get_ajax_csc.php code:
<?php
if(isset($_POST['stNum']))
{
include("DB.php");
$q=$_POST["stNum"];
$sql="select contact,phone from IDC WHERE id='".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
$tmpArr = array(
'stCnt'=>$arr['contace'],
'stPho'=>$arr['phone']
);
echo json_encode($tmpArr);
}
if(isset($_POST['htmlCnt']))
{
include("DB.php");
$htcnt=stripslashes(".$_POST['htmlCnt'].");
........
}
?>
Here is DB.php code:
<?php
session_start();
$pwd=$_SESSION['password'];
$user=$_SESSION['user'];
try
{
$conn = new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch (PDOException $e)
{
echo "account or pwd wrong <meta http-equiv='refresh' content='1;url=index.html'>";
exit;
}
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
?>
It seems nothing wrong in my code, but I cann't fetch data from database
I have found that stripslashes() made ajax return nothing. When I shielded this method (//stripslashes()), it worked fine. Why stripslashes can influence my ajax return data?

I found that:
$htcnt=stripslashes(".$_POST['htmlCnt'].");
change to:
$htcnt=stripslashes($_POST['htmlCnt']);

Related

Sending Ajax Request to PHP not working

I am trying to make an ajax request to my PHP file.
The ajax request occurs when my "Country" select option menu changes. The result is suppose to be a new select option menu titled "State Province" and the options would be based off the choice made in the "Country" select option menu.
This is what I want it to look like:
The problem I'm having is when the ajax is making a request to the PHP, the PHP seems to be returning an empty array:
Does anyone know what might be wrong?
Thank you!
HTML for the select option:
<select name="Country" class="form-control input-sm" id="Country">
</select>
Ajax code with the onchange function:
$("#Country").on("change",function(){
var val = $('#Country').val();
performAJAX(val,'Country','StateProvince');
});
function performAJAX(choice,prevSelect,newSelect){
$.ajax({
type: "post",
url: "select-creation.php",
data: {choice: choice, prevSelect: prevSelect,newSelect: newSelect},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log("meow meow");
}
});
}
PHP code:
<?php session_start();
try{
$choice = $_POST['choice'];
$prevAttri = $_POST['prevSelect'];
$nxtAttri = $_POST['newSelect'];
$data = array();
$sql = 'SELECT '.$nxtAttri.' FROM agents WHERE '.$prevAttri.' = :userChoice';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/Database.class.php';
$db = new Database();
$conn = $db->getConnection();
$query = $conn->prepare($sql);
$query->bindValue(':userChoice',$choice,PDO::PARAM_STR);
if($query->execute()){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}//stmt
return json_encode($data);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
Your code return json_encode($data); seems to be nothing or invalid because your code doesn't use a function.
Just use echo json_encode($data);
In the ajax side, you don't need to use $.parseJSON(data); because you already specify the dataType to json it will immediately convert the data response by PHP to an object type.

Ajax form data reaching .done(function (data)) but no data posted to db

I am having some issues with information posting to my database. I have other information posting to my database via ajax call in my javascript and it posts no problem, however, I don't know what is wrong with this part of my code. It refuses to post to the database. I wanted to post it and see if anyone spots something that I don't that would prohibit it from making it to the database. The funny thing is, the ajax call is making it inside my .done function(data) for my ajax call, but nothing is going into my database.
Below I have posted all code that I believe is relevant
$('#form-reg').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function(data){
console.log(data),
},
error: function(err){ console.log(err)
};
})
.done(function (data) {
console.log("lo");
document.getElementById('form-reg').reset(function(){
alert("signed up completed");
});
})
.fail(function (error) {
alert("POST failed");
});
return false;
});
/*mysqli_connect.php -- note this is just an old file name. not important*/
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
/*register.php*/
<?php
require 'mysqli_connect.php';
if((isset($_POST['name']) && !empty($_POST['name']))||
(isset($_POST['email']) && !empty($_POST['email']))){
$sth = $dbh->prepare('INSERT INTO test_table (comment) VALUES(?,?);');
$name = $_POST['name'];
$email = $_POST['email'];
$sth->execute(Array($name, $email));
}
else{
echo 'error no comment entered';
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<div id = "register-container">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
</div>
. If I miss something feel free to request that piece of code.
It seems the problem is in:
INSERT INTO test_table (comment) VALUES(?,?);
Why is there one col "(comment)" while in VALUES there are two (?,?) placeholders? What columns are in the table "test_table"? I think the query might be something like:
INSERT INTO test_table (name, email) VALUES(?,?);
I think your problem lies in your PHP.
$sth = $dbh->prepare('INSERT INTO test_table (comment) VALUES(?,?);');
$name = $_POST['name'];
$email = $_POST['email'];
Your SQL doesn't know what the question marks (?) are unless you give them a value. Look at the example below:
$name = $_POST['name'];
$email = $_POST['email'];
$sth = $dbh->prepare('INSERT INTO test_table VALUES(?,?);');
$sth->bind_param('ss', $name, $email); // you must bind the values you wish to insert
$sth->execute();
For more information about bind_param take a look at the PHP Documentation:
http://php.net/manual/en/mysqli-stmt.bind-param.php

Wordpress plugin ajax returns 0

I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

How to load data from sql through ajax using php variable?

My HTML/PHP code:
<br/><br/><div id="dialog-modal"></div><br/><br/>
<?php foreach (range(0, 29) as $rs) { ?>
<a data-toggle="modal" href="#" data-href="rsc1<?php echo $rs;?>" class="link">pvz - rsc1<?php echo $rs;?></a><br/>
<?php } ?>
My JavaScript code:
$('.link').on('click',function(e){
var linkValue = $(this).attr('data-href');
$.ajax({
cache: false,
type: 'GET',
//url: 'details.php',
//data: 'i=' + linkValue,
success: function(data) {
$('.ui-dialog-title').html(linkValue)
$('#dialog-modal').html(linkValue).dialog();
}
});
e.preventDefault();
});
The details.php code:
$i = $_GET['i'];
echo $i;
This script opens only new dialog with my sent data from url data-href. All I want to do is to take some data from sql db into that dialog window by variable $i…
I think you want to know how to get data from sql database and show it in your ajax response.
If so then try something like this:
details.php code:
$i = $_GET['i'];//getting your data
$link = mysqli_connect("localhost", "my_user", "my_password", "db name");//set your correct database connection string
//check if connection errors
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//make a query with valid table name
$result = mysqli_query($link, "SELECT * from your_table ");
if($result->num_rows){ //check if any data found
while ($row = mysql_fetch_assoc($query)) {
echo $row['id'];// echo this data
}
}
else{
echo "no data found!";//echo no data found
}
mysqli_close($link); // close mysql connection
In this php page what ever i have echoed it will send as ajax response in your success call back's data. that will display in your modal. I just tried to give you a basic idea. I think it will help you.
Some good resource links: http://www.phptutorialforbeginners.com/2013/01/jquery-ajax-tutorial-and-example-of.html
http://www.cleverweb.nl/php/jquery-ajax-call-tutorial/

Categories