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);
?>
Related
I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});
my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong?
PHP:
//after connect to database (succesfull)
if($_GET['search_data'])
{
$search = ltrim($_GET['search']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: "text=" + text,
async: false,
success: function(text) {
if(text)
{
$('#display').append(JSON.stringify(text))
}
else
{
$('#display').append('No results!');
}
}
});
});
});</script>
<title>Live search</title>
</head>
<body>
<br />
search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" />
<br />
<div id="display"></div>
</html>
and results:
[{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars
"},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}]
My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?
You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this :
if($_GET['search_data'])
{
$search = ltrim($_POST['text']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
if(!empty($search)
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
And it's a good practice to use object in your ajax data
$(document).ready(function () {
$("#search").keyup(function () {
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: {
text: text
},
async: false,
success: function (text) {
if (text)
{
$('#display').append(JSON.stringify(text))
} else
{
$('#display').append('No results!');
}
}
});
});
});
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.
how to return URL built in php as json object to ajax to open it in the new tab?
so far all my attempts to do so were unsuccessful. Please help
here is my JS file
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
cache: false,
success: function (html) {
myWindow = window.open(encodeURIComponent(true),
"_blank");
myWindow.focus();
if (html == "true") {
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
and here is my PHP file
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/includes/sitewide-variables.php");
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// Check if all required fields are filled in
if (empty($_POST['name']) && empty($_POST['id'])) {
echo "Error: You must fill in all required fields.";
// If not, exit!
exit();
}
// If valid, store values in variables
$id = stripslashes($_POST['id']);
$name = stripslashes($_POST['name']);
if($name){
$query = 'SELECT * FROM files_paid WHERE parentpageID = :promoproductID';
$res = $db->prepare($query);
$res->execute(array(':promoproductID' => $id));
foreach ($res as $info);
if($info['promoCode'] == $_POST['name']){
$redirect_link = 'http://'.$info['promobuylinkID'].'.myid.pay.clickbank.net';
$todayis = date("l, F j, Y, g:i a") ;
$to = "My Email Address";
$subject = "Promotional Purchase";
$message = "$todayis [EST] \n
Promo Code: $name \n
";
// Send email
$sent = mail($to, $subject, $message);
if($sent) {
echo json_encode($redirect_link);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
}
}
?>
I am only getting true in the new window.
Thanks in advance
I have have found the problem.
First, I was missing dataType: "json", in ajax.
and after that I only had to return html to get to the point where I needed to get.
So the JS file now looks like this
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
dataType: "json",
cache: false,
success: function (html) {
if (html) {
window.open(decodeURIComponent(html),"_blank").focus();
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function () {
alert("Your Coupon Code is not valid");
}
});
return false;
});
});
All works just fine.
I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});