Cannot retrieve json string from php using ajax - javascript

I can't retrieve json string data from my php script using ajax call.
Here is my ajax script :
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(data){
$("#app_panel").append(data.html);
$('.inv_date').hide();
}
});
and this is my php script:
<?php
//wall ===================================================
session_start();
include("../../dbinfo.inc.php");
$from = $_POST['from'];
$to = $_POST['to'];
$sel = $_POST['sel'];
// connect to the database
$client_id = $_SESSION['clientid'];
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
$results = array(
'html' => $html
);
$html = " ";
if($sel == "all"){
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
}else{
$query=" select * from tele_panel_call where (client='$client_id' AND date_time BETWEEN '$from' AND '$to') ORDER BY date_time DESC";
$result = $mysqli->query($query);
}
if ($result->num_rows > 0){
while ($row = $result->fetch_object())
{
$from = $row->from;
$to = $row->to;
$html .= '<div style="width:590px;height:15px;background: url(img/clientimg/wrap-white.png)repeat;padding: 5px 5px 5px 5px;margin-bottom:5px;">';
$query_from=" select * from tele_agent_dialer where (client='$client_id' AND (dialer='$from' OR dialer='$to'))";
$result_from = $mysqli->query($query_from);
$row_from = $result_from->fetch_assoc();
$dialer = $row_from['dialer'];
if($dialer == $from){
$image = 'outgoing';
$out = $out+1;
}
if($dialer == $to){
$image = 'incoming';
$in = $in+1;
}
if($dialer != $to & $dialer != $from){
$image = 'extension';
$ext = $ext+1;
}
$html .= '<img src="img/clientimg/'; $html .= $image; $html .= '.png" style="float:left;margin-right:10px;height:15px">';
$html .= '<div style="float:left;margin-right:5px;width:135px;height:30px;overflow:hidden;"><b>From: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $from, $matches ) )
{
$from = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $from;
$html .= '</div>
<div style="float:left;margin-right:5px;width:125px;height:30px;overflow:hidden;">
<b>To: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $to, $matches ) )
{
$to = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $to;
$html .= '</div>
<div style="float:left;width:160px;margin-right:5px;height:30px;overflow:hidden;">
<b>Date/Time: </b>'; $html .= $row->date_time;
$html .= '</div>
<div style="float:left;width:100px;margin-right:5px;height:30px;overflow:hidden;">
<b>Duration: </b>';
$duration = $row->duration;
preg_match("#(\d+):(\d+)#", $duration, $matches );
$min = $min + $matches[1];
$sec = $sec + $matches[2];
$html .= $duration;
$html .= '</div>';
$html .= '</div>';
}
}else{
echo "No results to display!";
}
$jsonString = json_encode($results);
echo $jsonString;
$mysqli->close();
?>
Can someone please tell me what I'm doing wrong here? My php script doesn't have any errors when I check the page itself.

Also it's good to add proper header for json data output (at the begining of the script for example).
header("Content-Type: application/json");
As for query results, you should debug it. Try to print the query and run it in Phpmyadmin (or other database administration tool)

Related

How to send php value to javascript with script tag?

php code is
<?php
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
// echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
// echo $endDate;
$model = $_POST['model'];
// echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
// echo $dates
for ($i=0; $i < count($dates); $i++){
echo "<form method = 'post'>";
echo "<tr>";
echo "<td><button type = 'submit' style = 'border-color : white; background-color : white; outline : 0; border : 0' name = 'datebutton' value = '$model,$dates[$i]'>$dates[$i]</td>";
echo "</form>";
$query = mysqli_query($conn, "SELECT * from elentec_count where Date = '$dates[$i]' and model = '$model'");
$row = mysqli_fetch_row($query);
echo "<td>$row[2]</td><td>$row[3]</td><td>$row[4]</td><td>$row[5]</td><td>$row[6]</td><td>$row[7]</td>";
}
$burrCordResult = updateChart($conn, $model, $dates);
$burrCordResult = ['mon', 'Tue'];
print_r($burrCordResult);
}
?>
<script>var BurrLoc = "<?= $burrCordResult ?>";</script>
javascript code is
console.log(BurrLoc)
The php code is in the middle of the html code. It makes the error
Uncaught ReferenceError: BurrLoc is not defined
I don't know why this matter comes out.
Just do an echo within your script with script tags enclosing it anywhere within your PHP code to send it.
echo "<script>var BurrLoc ='$Burrloc';</script>";

Executing a Php Mysql function from Onclick NO POST

I have a php Mysql interaction and i wish to trigger the Mysql Search through an ONCLICK event.
iv thought about using a JS function or JQ and parsing the ID of selected through JS function but then im unsure as how i would re-execute the php to re-search the database with the new JS Veriable...
The code below is accurate and is what im working with...
How would i re execute the php with the new ID.. Much appreciated..
<div class="contentheader">
<header> Welcome Please Choose a Catagory</strong></header>
</div>
<div id='smallpagination' class='smallpagination'>
<?php
//search according to chosen search critera NOT LIMITED//
include("conect.php");
$startit = 0;
$startfrom = rand(0, 20);
$displayto = $startfrom + 10;
$search = "";
$startedfrom = $startfrom;
$sql = "SELECT * FROM testdata
WHERE title LIKE '%%$search%%'
LIMIT $startfrom , $displayto";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$id = $row['id'];
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
if ($startit < 1) {
$gotid = $row['id'];
$startit = $startit + 1;
};
$vidd = $row['id'] - 0.01;
$pidd = $row['id'] - 0.02;
$type = $row['type'];
$showinglocate = $row['id'] - 0.03;
$showingphone = $row['id'] - 0.04;
$displaytype = "minlist";
//Thumbnails sized listings
if ($displaytype == "minlist") {
echo "
<div class='floaterminhomepage'>
<div class='innerfloaterminhomepage' >";
if (!empty($videos)) {
echo "
<video id='$v_id' style='position:absolute; top:0%; left:0%; width:100%; height:100%; background-size: cover; object-fit:fill;' preload='metadata' onclick='showdata({$v_id});'>
<source src='vid/{$row['videos']}.mp4' type='video/mp4'>
<source src='vid/{$row['videos']}.mp4' type='video/ogg'>
<source src='vid/{$row['videos']}.mp4' type='video/webm'>
</video >";
}
if (empty($videos)) {
echo "<img id='$vidd' src='pageimages/blank.png' style='position:absolute; top:0%; left:0%; width:100%; height:100%;'>";
}
echo "
</div>
</div>
";
}
};
?>
</div> <!---smallpagination--->
<script>
------ > SHOWDATA
RETRIEVE
ID
SCRIPT
HERE < -----
</script>
Then re-execute the folling php
----HOW WOULD I GO ABOUT THIS RE_EXECUTION.
<?php
$displayto = $startfrom;
$sql = "SELECT * FROM testdata
WHERE id={$gotid};
";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
$type = $row['type'];
};
echo "<div id='smallpagdata' class='smallpagdata'>
ID={$v_id}<br>
NAME={$Name}<br>
TITLE={$title}<br>
INFO={$info}<br>
PHONE={$phone}<br>
LOCATION={$locate}<br>
PRICE={$price}<br>
Listed={$date}<br>
</div>";
?>
Does "NO POST" mean "no GET" as well? Otherwise you could put your retrieval script in a different file and call that with jQuery.get or XMLHttpRequest.

Modify DOM and replace mail addresses

I would like to make use of Simple HTML DOM parser to search for mail-adresses in the content of a html-site and replace them.
The replacement contains a span element and a little bit JS (this should obfuscate the addresses.
At the moment this works as follows:
$pattern =
"/(?:[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/";
preg_match_all( $pattern, $content, $matches );
foreach ( $matches[ 0 ] as $email ) {
$content = $this->searchDOM(
$content,
$email,
$this->hide_email($email)
);
}
This is the searchDOM-method:
private function searchDOM( $content, $search, $replace, $excludedParents = [] )
{
$dom = HtmlDomParser::str_get_html(
$content,
true,
true,
DEFAULT_TARGET_CHARSET,
false,
DEFAULT_BR_TEXT,
DEFAULT_SPAN_TEXT
);
foreach ( $dom->find( 'text' ) as $element ) {
if ( !in_array( $element->parent()->tag, $excludedParents ) ) {
$element->innertext = preg_replace(
'/(?<!\w)' . preg_quote( $search, "/" ) . '(?!\w)/i',
$replace,
$element->innertext
);
}
}
return $dom->save();
}
and this is the hide_email-method:
function hide_email( $email )
{
$character_set = '+-.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle( $character_set );
$cipher_text = '';
$id = 'e' . rand( 1, 999999999 );
for ( $i = 0; $i < strlen( $email ); $i += 1 )
$cipher_text .= $key[ strpos( $character_set, $email[ $i ] ) ];
$script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
$script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script .= 'document.getElementById("' . $id . '").innerHTML=""+d+""';
$script = "eval(\"" . str_replace( [ "\\", '"' ], [ "\\\\", '\"' ], $script ) . "\")";
$script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
}
Well - this is not working as expected, because the rendered page shows only "[javascript protected email address]". If I have a look at the source, the a-tag is missing.

AJAX Call - Does not recognize wordpress functions / classes

i have Ajax call for getting response , in response file i have used wordpress loop usng WP_Query() class...
but when i perform ajax it returns Fatal error:
Fatal error: Class 'WP_Query' not found in C:\xampp\htdocs\business-finder\wp-content\themes\businessfinder\metabox\ajax-process.php on line 20
Here is AJAX call code:
var path = 'http://localhost/business-finder/wp-content/themes/businessfinder/metabox/ajax-process.php';
$.ajax({
type: "POST",
url: path,
data: { param:folio_data }
}).done(function( msg ) {
$( '#ajax_folio' ).html( msg );
//alert( "Data Saved: " + msg );
});
Here is response file Code:
<?php
print_r( $_POST['param'] );
if( !empty( $_POST['param'] ) ):
echo spyropress_get_attached_posts1( $_POST['param'], 'ait-grid-portfolio' );
echo '<br><br>';
endif;
function spyropress_get_attached_posts1( $post_id = '', $post_type = '' ){
//if( $post_id = '' || $post_type = '' ) return;
$counter = 0;
global $wp_query ;
$query = new WP_Query( array( 'post_type' => $post_type, 'post__in' => $post_id ) );
if( $query->have_posts() ):
$out .= '<table border = "1">';
while( $query->have_posts() ):
$query->the_post();
if( $counter == 6 ):
$out .= '<tr class = "post_list">';
else:
$counter++;
endif;
$out .= '<td>'.get_the_post_thumbnail(get_the_ID(), array(100,100)).'<br>'.get_the_title().'</td>';
if( $counter == 6 ):
$out .= '</tr>';
$counter = 0;
endif;
endwhile;
$out .= '</table>';
wp_reset_postdata();
else:
$out = 'No Posts Found....';
endif;
wp_reset_query();
return $out;
}
add_action( 'init', 'spyropress_get_attached_posts' );
?>
You have written wrong ajax code. you can not use ajax like this. See below code:
jQuery(document).ready(function($) {
var dataString = {
action: 'my_ajax',
param: folio_data
};
jQuery.ajax
({
type: "POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: dataString,
cache: false,
success: function(msg)
{
$( '#ajax_folio' ).html( msg );
//alert( "Data Saved: " + msg );
}
});
});
function ajaxDataSubmit(){
global $wpdb;
$post_id = $_POST['param'];
$post_type='ait-grid-portfolio';
$counter = 0;
global $wp_query ;
$query = new WP_Query( array( 'post_type' => $post_type, 'post__in' => $post_id ) );
if( $query->have_posts() ):
$out .= '<table border = "1">';
while( $query->have_posts() ):
$query->the_post();
if( $counter == 6 ):
$out .= '<tr class = "post_list">';
else:
$counter++;
endif;
$out .= '<td>'.get_the_post_thumbnail(get_the_ID(), array(100,100)).'<br>'.get_the_title().'</td>';
if( $counter == 6 ):
$out .= '</tr>';
$counter = 0;
endif;
endwhile;
$out .= '</table>';
wp_reset_postdata();
else:
$out = 'No Posts Found....';
endif;
wp_reset_query();
die($out);
}
add_action('wp_ajax_my_ajax', 'ajaxDataSubmit');//Logged in users
add_action('wp_ajax_nopriv_my_ajax', 'ajaxDataSubmit'); // Not logged in uNOTE: mer

button onclick= returns var without slashes

The following code returns the $userurl, that is:
<button class="Urllink" type="button" onclick="window.parent.location.href=" www.facebook.com";"><img src="http://www.facebook.com/favicon.ico" width="16" height="16">Facebook</button>
CODE:
function userUrl($user){
include ('bin/mysqllogin.php');
$userUrl = '';
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href="';
$userUrl .= $dbresult['Url'] . '";><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
As you all see $userUrl returns not the needed http://www.facebook.com. What am I doing wrong here?
Edit1: Found the solution. I needed to add /' around the var $dbresult['Url']. So the code changed to:
function userUrl($user){
include ('bin/mysqllogin.php');
$userUrl = '';
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href=\'';
$userUrl .= $dbresult['Url'] . '\';"><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
You need to prepend http:// to $userUrl. As such:
function userUrl($user) {
include ('bin/mysqllogin.php');
$userUrl = 'http://'; // <-- Prepended in here
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href="';
$userUrl .= $dbresult['Url'] . '";><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
Please lookup SQL-injections by the way. Or, best choice, use PDO.

Categories

Resources