I have implemented the following autoload code. It fetches result from database but it keeps looping the same result over and over.
php code
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$keywords = $_GET['keywords'];
$sql = "SELECT * FROM blog_posts WHERE postCat LIKE '".$keywords."' ORDER BY postID ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['postTitle'] . '</h3>';
}
}
?>
Try this
<?php
$keywords = 'events';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var keywords = '<?php echo $keywords; ?>'; // Changed
var busy = false;
var limit = 15;
var offset = 0;
function displayRecords(lim, off) {
// Changed/New
var data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html,textStatus,jqHXR) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No records found.</button>').show()
} else {
$("#loader_message").css('display','none');
$("#loader_message").html(html);
}
window.busy = false;
},
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
$('#result').on('scroll', function() { if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { busy = true; offset = limit + offset; setTimeout(function() { displayRecords(limit, offset); }, 500); } })
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
this is loading same contents over and over because on each ajax call you are sending same 'data' which is
var data = {
'limit': limit,
'offset': offset,
'keywords': keywords,
};
Change the function to use new limit and offset
function displayRecords(lim, off) {
data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
...
...
Related
I have a code for showing list from database and a loadmore button. After all records list is displayed and click on loadmore button show empty places.
How to hide loadmore button once all records displayed?
index.php file:
<?php $chinp=$_GET['schinp'];?>
<div id="schts"></div>
<button id="btnsch">load more</button>
<script>
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 1;
var offsrch = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp}
})
.done(function(msg) {
$("#schts").append(msg);
});
offsrch = offsrch + srchco;
});
$("button").trigger("click");
});
</script>
search.php :
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
Thanks.
Here is code to hide load more button as per your code.
Replace this code in your first file.
<script type="text/javascript">
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 2;
var offsrch = 0;
var page_num = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp, page_num : page_num}
})
.done(function(msg) {
if(msg == 'noMoreData'){
$("#btnsch").hide();
} else {
$("#schts").append(msg);
}
});
page_num = page_num + 1;
offsrch = offsrch + srchco;
});
$("#btnsch").trigger("click");
});
</script>
Now add this code in your search file.
<?php
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$page_num=$_POST['page_num'];
$total_records = 0;
$totalschql="SELECT id FROM t_users WHERE name LIKE 'krishna' ORDER BY name ASC";
if ($result=mysqli_query($conn,$totalschql))
{
$total_records=mysqli_num_rows($result);
}
$last_records_count = ($page_num) * $srchcoun;
if($last_records_count >= $total_records) {
echo 'noMoreData';exit();
} else {
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";;
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];
?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
<?php
}
?>
Try this and let me know if you have any issue.
Simply use $('#myButtonId').hide(); in ajax part after you load the entire data from database.
function get_rain_data_list(is_load_more=0){
if(is_load_more!=0){//if is_load_more is not 0 then get offset data from btnlod attr
offset = $('#btn_load_more_rain').attr("data-offset");
}else{ //set offset =0 when is_load_more is 0
offset = 0;
}
var id = $('#id').val();
var countShow = 0;
if(fromDate!=''){
countShow = 1;
}
$.ajax({
url: base_url+"rain_data_list_ajax",
type: "POST",
data:{offset:offset,propertyId:propertyId,fromDate:fromDate,toData:toData},
dataType: "JSON",
beforeSend: function() {
show_loader();
},
success: function(data){
hide_loader();
// console.log(data);
$('.proprty_load_more_btn').remove();//remove load more button
if(offset==0){ //clear div when offset 0
$("#append_rain_list").html('');
}
if(data.no_record==0){//show data in div when no previous record
$("#append_rain_list").html(data.html_rain);
$("#add_count").html('');
if(countShow){
//$("#add_count").html(data.count+data.record);
}
}else{
//append data when already record show in view
$("#append_rain_list").append(data.html_rain);
$("#append_load_btn").append(data.btn_html);
$("#add_count").html('');
if(countShow){
$("#add_count").html(data.count+data.record);
}
}
},
});
}
<div id="append_rain_list"></div>
<div id="add_count"></div>
<?php
function rain_data_list_ajax(){
$limit = 6;
$is_next = 0;
//get and set offset
$offset = $this->input->post('offset');
$data['property_id'] = decoding($this->input->post('propertyId'));
$fDate = sanitize_input_text($this->input->post('fromDate'));
$tDate = sanitize_input_text($this->input->post('toData'));
$new_offset = $limit+$offset; //pr($data);
//set where
$where = array('property_id'=>$data['property_id']);
//set select field to get
$data['limit'] = $limit;
$data['offset'] = $offset;
//get count of records
$dataView['total_count'] = $this->Property_model->get_rain_count($data);
//get records
$dataView['rain_list'] = $this->Property_model->get_rain_list($data);
///lq();
//check for load more btn
//pr($dataView);
if($dataView['total_count']>$new_offset){
$is_next =1;
}
$btn_html = '';
if($is_next){
//if is next =1 set load more button in btn_html
$id = "btn_load_more_rain";
$btn_html = '<div class="col-sm-12 text-center pt-20 proprty_load_more_btn"><button class="login-btn load load_more_btn" id = "'.$id.'" data-offset ="'.$new_offset.'" data-isNext ="'.$is_next.'" >'.lang('load_more').'</button></div>';
}
//load view with data
$html_rain = $this->load->view('test1',$dataView,true);
$response = array('status'=>1,'html_rain'=>$html_rain,'btn_html'=>$btn_html,'count'=>$dataView['total_count'],'record'=>lang('recod_found'));
//flag for no record
$no_record=1;
if(empty($dataView['rain_list'])){
$no_record = 0;
}
$response['no_record'] = $no_record;
echo json_encode($response);die;
}
?>
Trying to paginate ajax data using Select2 (v 4.0.6.rc1) so that the user can find more results if not present in the first limit ,using the following but not retrieving data.I 'll appreciate if someone helps me out,there is not much of examples about pagination.
i was trying to paginate data using the help of this question Select2 v4 how to paginate results using AJAX its not seems to be working,getting the array but not correct format.
JS:
$('#compose_username').select2({
dropdownParent: $("#modal-compose") ,
placeholder: "Search Username...",
minimumInputLength: 1,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
return {
term: params.term,
page: params.page || 1
//a: params.term, // search term
//psf: params.page
};
},
processResults: function(data) {
console.log(data);
var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
return { results: result };
}
}
});
PHP
try{
$page= $_GET['page'];
// $resultCount = 10;
// $offset = ($page - 1) * $resultCount;
$pageLength = 20;
$pageStart = ($page - 1) * $pageLength;
$pageEnd = $pageStart + $pageLength;
$stmt = $db_con->query("SELECT id,first_name FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}");
$count = $db_con->query("SELECT count(first_name) FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}")->fetchColumn();;
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$json[] = ['id'=>$row['id'], 'username'=>$row['first_name']];
}
$endCount = $pageStart + $pageLength;
$morePages = $endCount > $count;
$results = array(
"results" => $json,
"pagination" => array(
"more" => $morePages
)
);
echo json_encode($results);
}
catch(PDOException $e){
echo $e->getMessage();
}
Found not much examples about select2 paginate, had to figure it out on my own and here is the full working of how to paginate data(infinite scroll) using Select2: Hope this helps someone else.
JS:
$('#compose_username').select2({
dropdownParent: $("#modal-compose") ,
placeholder: "Search Username...",
minimumInputLength: 1,
allowClear: true,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
return {
term: params.term,
page: params.page || 1,
};
},
processResults: function(data, params) {
//console.log(data);
// NO NEED TO PARSE DATA `processResults` automatically parse it
//var c = JSON.parse(data);
console.log(data);
var page = params.page || 1;
return {
results: $.map(data, function (item) { return {id: item.col, text: item.col}}),
pagination: {
// THE `10` SHOULD BE SAME AS `$resultCount FROM PHP, it is the number of records to fetch from table`
more: (page * 10) <= data[0].total_count
}
};
},
}
});
PHP(USING PDO):
try{
$page= $_GET['page'];
$resultCount = 10;
$end = ($page - 1) * $resultCount;
$start = $end + $resultCount;
$stmt = $db_con->query("SELECT col,col FROM table WHERE col LIKE '".$_GET['term']."%' LIMIT {$end},{$start}");
$stmt->execute();
$count = $stmt->rowCount();
$data = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = ['id'=>$row['id'], 'col'=>$row['col'],'total_count'=>$count];
// IF SEARCH TERM IS NOT FOUND DATA WILL BE EMPTY SO
if (empty($data)){
$empty[] = ['id'=>'', 'col'=>'', 'total_count'=>''];
echo json_encode($empty);
}
else
echo json_encode($data);
}
catch(PDOException $e){
echo $e->getMessage();
}
could someone help me out?
I have these 2 files:
keywords.php
records.php
The keywords.php is like a search page where user submits a query like keywords.php?keywords=robert
Now what I want, is to send the value robert to records.php and display all records matching the name robert from the blog_posts table to the keywords.php page
my keywords.php
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var <?php echo $keyword; ?>;
var busy = false;
var limit = 15
var offset = 0;
function displayRecords(lim, off) {
$.ajax({
type: "GET",
async: false,
url: "records.php",
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
and this is my records.php
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$keywords = $_GET['keywords'];
$sql = "SELECT * FROM blog_posts WHERE keyword LIKE '".$keywords."' ORDER BY postid ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['keyword'] . '</h3>';
}
}
?>
thanks alot for your help
There are several changes needed in keywords.php. Take a look at the changes below.
<?php
$keywords = $_GET['keywords'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var keywords = '<?php echo $keywords; ?>'; // Changed
var busy = false;
var limit = 15
var offset = 0;
// Changed/New
var data = {
'limit': limit,
'offset': offset,
'keywords': keywords,
};
function displayRecords(lim, off) {
$.ajax({
type: "GET",
async: false,
url: "records.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html,textStatus,jqHXR) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").css('display','none');
$("#loader_message").html(html);
}
window.busy = false;
},
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
I'm trying to incorporate the jquery sortable functionality into my website and saving the positions in the database is giving me all sorts of headaches... I've been fighting this for 3 days now, and I cannot seem to get this work properly.
As it stands, it is saving positions to the database, but not in the order or positions, that you'd expect. Meaning, if I move the item in position 0 to position 1, it saves the positions in a different order in the db. check out a live version here.
Here is my code...
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js file:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php file:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode( ($arr['sort']) );
Can anyone please point to where I am going wrong on this?
Thank you in advance.
Serge
In case someone lands on here, here is what worked in my case...
NOTE: I did not create prepared statements in the index.php select function. But you probably should.
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<div id='sort_<?php echo $items['id'] ?>' class='items'>
<span>☰</span> <?php echo $items['description'] ?>
</div>
<?php
}
}
?>
</div>
jquery sortable file:
var ul_sortable = $('#container');
ul_sortable.sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = ul_sortable.sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
ul_sortable.disableSelection();
update php file:
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
require_once('conn.php');
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$db->close();
}
Change your JS code like this:
{...}
tolerance: 'pointer',
cursor: 'move',
// new LINE
items: '.items', // <---- this is the new line
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
var post={},count=0;
$(this).children('.items').each(function(){
post[++count]=$(this).attr('id');
});
// new LINES end
$.ajax({
{...}
With this $.each loop you overwrite your var post -> serialize and define your own sort order. Now look at your $_POST["positions"] with PHP print_r($_POST["positions"]); and you have your positions in your own order.
result:
This ajax can't give me a result. I'm struggling with this issue. I don't know why and I couldn't find where is the mistake. I was tried another ajax and it works, but i don't know with this one. How's this? somebody help me, thanks.
ztest1.php:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style></style>
<script>
function checkemail() {
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if (u != "") {
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
data: ({
email: u,
cekemailsignup: 'yes'
}),
success: function(result) {
status.innerHTML = result['result'] + "," + result['cekemailsignup'] + "," + result['email'];
}
});
} else {
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
</head>
<body>
<div id='emailudahada'></div>
<input type='text' id='email' onblur='checkemail()'></input>
</body>
</html>
ztest2.php:
<?php
include('ckcon.php');
$cekemailsignup=isset($_REQUEST['cekemailsignup'])?$_REQUEST['cekemailsignup']:null;
if($cekemailsignup=='yes'){
$email=isset($_REQUEST['email'])?$_REQUEST['email']:null;
$q=mysql_query("SELECT COUNT(email) AS ce FROM t_un WHERE email='$email' LIMIT 1");
$f=mysql_fetch_object($q);
$ce=$f->ce;
if($email==null){
$result="<img src='/img/xred.png'></img> <font color='red'>Cant be null value</font>";
}
if(strlen($email) < 4){
$result="<img src='/img/xred.png'></img> <font color='red'>4 digit at minimum</font>";
}
if(is_numeric($email[0])){
$result="<img src='/img/xred.png'></img> <font color='red'>1st character must be letter</font>";
}
if($ce<>0){
//$result="<img src='/img/xred.png'></img> <font color='red'><strong>".$email."</strong> is taken</font>";
$result="kampret lu";
}
echo "
cekemailsignup=$cekemailsignup<br>
email=$email<br>
ce=$ce<br>
result=$result<br>
";
$ar = array(
'result' => $result,
'cekemailsignup' => $cekemailsignup,
'email' => $email
);
echo json_encode($ar);
}
?>
Here is changed js function
<script>
function checkemail() {
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if (u != "") {
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
dataType: "json", //need to tell that response will as json
data: ({
email: u,
cekemailsignup: 'yes'
}),
success: function(result) {
status.innerHTML = result.result + "," + result.cekemailsignup. + "," + result.email;
}
});
} else {
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
result is string, to use it like object you need to parse it to JSON.
var obj = JSON.parse(result);
You can also set dataType: 'json', in the $.ajax configuration options to set it by default and then you don't need to parse the response, it can be directly used.
As jQuery is included on page, use it for DOM manipulation.
Complete Code:
$('#email').on('blur', function() {
var $status = $('#emailudahada');
email = $.trim($(this).val());
if (email) {
$(this).css('backgroundColor', 'yellow');
$status.html('<img src=\'/img/loading.GIF\'></img>');
$.ajax({
url: '/ztest2.php',
type: 'POST',
dataType: 'json',
data: ({
email: email,
cekemailsignup: 'yes'
}),
success: function(result) {
$status.html(result.result + ',' + result.cekemailsignup. + ',' + result.email);
}
});
} else {
$(this).css('backgroundColor', 'white');
}
});
HTML File
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
</style>
<script>
function checkemail(){
var status = document.getElementById("emailudahada");
var u = document.getElementById("email").value;
if(u != ""){
document.getElementById("email").style.backgroundColor = "yellow";
status.innerHTML = "<img src='/img/loading.GIF'></img>";
$.ajax({
url: '/ztest2.php',
type: "POST",
data: ({
email: u,
cekemailsignup: 'yes'
}),
success :
function(result2){
var result = JSON.parse(result2);
status.innerHTML=result['result']+","+result['cekemailsignup']+","+result['email'];
}
});
}else{
document.getElementById("email").style.backgroundColor = "white";
}
}
</script>
</head>
<body>
<div id='emailudahada'></div>
<input type='text' id='email' onblur='checkemail()'></input>
</body>
PHP file (ztest2.php)
<?php
$ar = array(
'result' => "123",
'cekemailsignup' => "true",
'email' => "ririnputrian#gmail.com"
);
echo json_encode($ar);
?>