Ajax search post error - php

I need help with two things.
First: if I hit empty submit button. It should show me a error.
Second: If there is 0 results, it will give an error.
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
--
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
$error = 'error';
echo json_encode( $error );
} else {
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
}

OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="search" class="keywords">
<input type="submit" name="submit" class="search">
<div id="search"></div>
<script>
$(document).ready(function(){
$(".search").click(function(){
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data){
$("div#search").empty()
$("div#search").append(data);
},
"json"
);
});
});
</script>
</body>
</html>
And for the PHP search.php page:
<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
echo json_encode( "error" );
}
else {
// run mysql commands
// if resultset == empty
// echo json_encode( "error" );
echo json_encode( "actual data" );
}
?>
To parse json data in javascript do this:
$.post(
"search.php",
{ keywords: $(".keywords").val() },
function(data) {
$("div#search").empty();
obj = JSON.parse(data);
$("div#search").append(obj.id + " " + obj.title);
},
"json"
);

try using $(this) instead of this

Related

show JSON data(from php file) in table using ajax

I hava a php code as shown below serverdata.php
<?php
require_once('database.php');
header("Content-type: application/json");
$sql = "SELECT * FROM user";
$result = mysql_query($sql);
$uid = array();
$uname = array();
while($row = mysql_fetch_assoc($result))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
?>
which produce the following output in JSON format:
[{"id":"1","username":"Sagun","password":"61b51ae250c7e7505191e4d5e6240c04"},{"id":"2","username":"roshan","password":"d6dfb33a2052663df81c35e5496b3b1b"},{"id":"17","username":"rajiv","password":"9a9af43c15771eaf3b2db8bb28a2829d"}]
All i want is to get the data from above php file that is in json format and display it in table in another page using AJAX. Please guide me through it.
ID USERNAME PASSOWRD
1 sagun 61b51...
2 roshan d6dfb..
17 rajiv 9a9af..
This is the ajax function to get your json data from php output, try to modify as you need.
<script type="text/javascript">
$(function() {
$.ajax({
type : 'POST',
url : 'YOUR_PHP_URL',
data : {},
dataType : 'json',
error : function (a, b, c)
{
},
success : function(data)
{
console.log( data );
}
});
});
</script>
Don't forget to include the jQuery library.
https://developers.google.com/speed/libraries/#jquery
This code for build table in jquery
<script type="text/javascript">
function jsonData()
{
$.ajax({
type:'post',
url:"serverdata.php",
datatype:'json',
success:function(data)
{
var jdata=$.parseJSON(data);
///console.log(jdata);
$(function(){
$.each(jdata,function(i,item){
var tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.email),
//$('<td>').text(item.password),
$('<td>').text(item.mob_num),
);
$("#tableId tbody").append(tr);
//console.log(tr.wrap('<p>').html());
})
})
}
})
}
database.php
<?php
try{
$db = new PDO('mysql:host=localhost;dbname=testing', "root" , "");
}catch(PDOException $e){
print "error in connection" . $e->getMessage();
}
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON data</title>
</head>
<body>
<table id="demoTable">
<thead>
<tr>
<td ><label>Id</label></td>
<td ><label>Username</label></td>
<td ><label>Password</label></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="detail.js" type="text/javascript"></script>
</body>
</html>
details.js
$(document).ready(function() {
$.ajax({
url:'serverdata.php',
type:'POST',
success:function(data){
var result = $.parseJSON(data);
$.each(result, function(key, value){
$.each(value, function(k, v){
if(k === "id"){
$("#demoTable >tbody:last").append(
$('<tr>').append(
$('<td>').append(v)
.append(
$('</td>').append(
$('</tr>')
)
)
)
);
}
if(k === "username"){
$("#demoTable >tbody >tr:last").append(
$('<td>').append(v)
.append(
$('</td>')
)
);
}
if(k === "password"){
$("#demoTable >tbody >tr:last").append(
$('<td>').append(v)
.append(
$('</td>')
)
);
}
});
});
}
})
});
serverdata.php
<?php
require_once 'database.php';
$data = array();
$stmt = $db->query('SELECT * FROM user');
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($row as $key => $value) {
$data[$key] = $value;
$result = json_encode($data);
}
echo $result;

PHP - variable from GET is changing

I have a svg.php file with some shapes.
<rect onclick="window.location='search.php?filter=1'" width="50" height="50">
<rect onclick="window.location='search.php?filter=2'" width="50" height="50">
Search.php
div class="container">
<textarea class="search" id="search_id"></textarea>
<div id="result"></div>
<?php include("svg.php"); ?>
</div>
//This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var search_id = $(this).val();
var dataString = 'search='+ search_id;
if (search_id=='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).hide(); }
});
};
if(search_id!='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show(); }
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#search_id').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#search_id').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Then a search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
echo $search; //echos "2".
if ($search=="1") {
echo $search; //enters if, and it's not supposed to, and echos "1"
Select * from table;
}
Search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : "1";
echo $search //echos "2";
if ($search=="1") {
$q = $_POST['search'];
$q_length = strlen($q);
$sql = <<<SQL
SELECT * FROM table
LIMIT 6
SQL;
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');
}
while($row = $result->fetch_array()) { ?>
<div class="show_search">
<?php echo $row['name'] ?> </a>
</div>
<?php } } ?>
I'm on search.php?filter=2 and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1".
I'm not defining the $search variable anywhere else. Thank you for your help.
Your code is a bit too complicated.
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
if($search == 1) {
echo $search;
}
Thats enough, you don't need the check if $_POST is available. That make not so much sense because you don't send a form and you don't have post data in that case when you it with window.location.
If there is no other code between following two lines:
echo $search; //echos "2".
AND
if ($_POST AND $search=="1") { ... }
Then, its not possible to go inside if condition. its only possible if your if condition is like if($_POST AND $search=1). Check that, whether you have single = or double == in comparing $search variable.
If there is some php code in between, then show us, whatever it is, so that we can help you.

Auto Capitalize on submit AJAX

How do I Auto Capitalize all the value of my dynamic text box. I want on submit for security purposes. I used strtooper in PHP but it has an array problem. And I used auto capitalization using CSS but if the value is already submitted to database it is not working, it's still the same as the value I inputted. Anyone can help me.
main form:
<script type='text/javascript'>
/* attach a submit handler to the form */
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
var mytxt1 = [];
var mytxt2 = [];
$(".car_brand").each(function () {
mytxt1.push($(this).val());
});
$(".car_model").each(function () {
mytxt2.push($(this).val());
});
e.preventDefault();
var perfTimes = $(this).serialize();
$.post("maintenance_function.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.location.href = data.redirect;
}
}, "json");
});
});
<script>
var nitem =0;
var ntotal = 0;
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'Car Manufacturer: <input type="text" class="car_brand" id="' + nitem + '" required> ' +
'Car Model: <input type="text" class="car_model" id="' + nitem + '" required>' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem).each(function(){
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
</script>
Function form:
<?php
include('connect.php');
$mydata = $_POST["results"];
//echo $mydata;
parse_str($mydata);
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$errors = [];
if(!isset($_POST["txt1"])){
$errors[] = array(
'error_code' => 1,
'message' => 'Please add a text box.'
);
}
if(empty($errors)) {
for($i=0;$i<=count($_POST["txt1"])-1;$i++)
{
//if (trim($_POST["txt1"][$i]) != "" && trim($_POST["txt2"][$i]) != "" && trim($_POST["txt3"][$i]) != ""){
mysql_query("INSERT INTO car_maintenance VALUES ('', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."')");
//}
}
$response = array(
'message' => 'Successfully Added',
'redirect' => "car_maintenance.php"//add here
);
echo json_encode($response);
}
else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
?>
use this on the string you want to capitalize in the php file:
$newstring = ucwords(strtolower($string1));
this will create “title case,” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase, hopw this is what you meant.
if you want all letters capital, use this:
$newstring = strtoupper($string1);
In css
input {text-transform:uppercase;}
In javascript
document.getElementsByTagName('input').value = document.getElementsByTagName('input').value.toUpperCase()

Using Jquery autocomplete with images

I am using the code bellow of foxycomplete to get some results from my db with images.
With local files works great but i cant do it with mysql.
Here is my code that i am using..
<form id="autocompleteForm" name="autocompleteForm" action="" method="post">
<input type="text" name="s" id="s" value="Search" style="border:none;" />
</form>
The Javascript Code:
(function($) {
$(document).ready(function() {
$( '#s' ).each( function(){
$(this).attr( 'title', $(this).val() )
.focus( function(){
if ( $(this).val() == $(this).attr('title') ) {
$(this).val( '' );
}
} ).blur( function(){
if ( $(this).val() == '' || $(this).val() == ' ' ) {
$(this).val( $(this).attr('title') );
}
} );
} );
$('input#s').result(function(event, data, formatted) {
$('#result').html( !data ? "No match!" : "Selected: " + formatted);
}).blur(function(){
});
$(function() {
function format(mail) {
return "<a href='"+mail.permalink+"'><img src='" + mail.image + "' /><span class='title'>" + mail.title +"</span></a>";
}
function link(mail) {
return mail.permalink
}
function title(mail) {
return mail.title
}
$("#s").autocomplete(completeResults, {
width: $("#s").outerWidth()-2,
max: 5,
scroll: false,
dataType: "json",
source: "video_search.php",
matchContains: "word",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.title,
result: $("#s").val()
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#s").val(title(item));
//location.href = link(item);
});
});
});
})(jQuery);
And the php code to retrieve my data:
<?php
require "connectiondb.php";
if(isset($_REQUEST['s']))
{
$queryString = mysql_real_escape_string($_REQUEST['s']);
echo'var completeResults = [{';
$ss = mysql_query ("SELECT title, image FROM users WHERE title LIKE '$queryString%' LIMIT 7");
while($result = mysql_fetch_assoc($ss)) {
echo '
"permalink": "index.html",
"image": "'.$result['image'].'",
"title": "'.$result['title'].'"
},';
}
echo '}];';
}else{
}
?>
Thank you Guys!!!
Whats inside the $result['image']? If it contains the image file itself(binary data) and not just the path, then you need to create one more file (image.php?s=id) which would retreive just that binary data with adequate header.. ie
<?php
header('Content-Type: image/jpeg');
// sql stuff
echo $result['image'];
?>
In your main file you'll then call just
"image": "'.image.php?id='.$result['id'].'",
also, dont torture yourself and use json_encode() :)

Empty post error

I need to make my script detect, if post is empty so that it will post error.
Right now, when my post is empty, it posts all the results.
my code
$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
$query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
$arr = array();
$query->execute();
while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
$arr[] = array( "id" => $row["id"], "title" => $row["title"]);
}
echo json_encode( $arr );
?>
and my script
$(document).ready(function(){
$(".search").click(function(){
$.post("search.php", { keywords: $(".keywords").val() }, function(data){
$("div#search").empty()
$.each(data, function(){
$("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
});
}, "json");
});
});
Add this:
if(empty( $keywords ) ) {
// Show some error
}
else{
// your search code here ...
}
but it's preferred to do the check in the JS too before posting

Categories