I'm trying to get the data value on success from the php. However when I alert(data) in the success, it returns the page html.
HTML:
<input type="text" class="form-control" name="project_name" id="projectName" required>
Jquery AJAX:
$('#projectName').on('blur', function(){
var projectName = $(this).val();
$.ajax({
url: 'page.php',
type: 'POST',
dataType: 'text',
data: {
'projectChecked': 1,
'project_name': projectName,
},
success: function(data){
if (data == 'taken') {
$('#projectName').addClass('border-red');
}
}
});
});
PHP:
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
Alert Message:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="shortcut icon" href="/favicon.png"/>
<title>Page Title</title>
<meta name="description" content="Meta Description">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlTw8HfCJo=" crossorigin="anonymous"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-157194354-1"></script>
You should use exit in php code to get return data use following code
if(isset($_POST['projectChecked'])){
echo 'taken';
exit;
}
can you check the html code when you do alert(data); and post here?
alternatively, you might want to check the developer tools of browser and validate network tab to monitor parameters and response of ajax request.
It is possible that you are getting http 400/500 response and you are actually seeing default error page (which is of course not a JSON response) in the data variable (this depends on the way server is configured)
Related
been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});
I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>
This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.
I am struggling with getting this code to work. My intention is to be able to save the contents of a div to an html file, so that I can recall it later...
It works partially, in that if I change $data=$_POST['id'] to $data=$_POST['memory'] in readInput.php it will indeed save any text I enter into the input named 'memory' to an html file, and will correctly save the file with whatever name I give it. Where it fails is if I try to grab the data of DIV 'readDiv' and its contents $data=$_POST['id']; it will save a blank html page, with whatever name I gave it... Here is the code:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>readInput</title>
<meta name="description" content="HTML5 web page">
<meta name="keywords" content="HTML5">
<meta name="author" content="You">
<meta charset="UTF-8">
<link href="jquery-ui.htm" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-latest.htm"></script>
<script name="saveMemory" type="text/javascript">
$(document).ready(function() {
$('#saveMemory').click(function() {
//e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content}
//dataType: "html" // test
});
});
});
</script>
</head>
<body onload="document.readWrite.writeInput.focus();"><!--form name.input name.focus!-->
<div id="formContainer" style="display:block">
<form name="readWrite" action="readInput.php" method="POST">
<input name="memory" placeholder="...enter text here..." type="text">
<input name="readMemory" id="readMemory" class="readMemory" placeholder="...read..." type="text">
<input id="writeInput" name="writeInput" class="writeInput" placeholder="...write..." type="text">
<input class="saveMemory" id="saveMemory" name="saveMemory" value="...saveMemory..." type="submit">
</form></div>
<div name="readDiv" id="readDiv" class="readDiv">
<div id="writeDiv" class="writeDiv" title="writeDiv">test text
<div id="topDropbox" class="topDropbox" title="topDropbox">
<img src="car.jpg">
</div></div></div>
</body></html>
readInput.php:
<?php
$writeInput = $_POST['writeInput'];
$data = $_POST['id'];
$fileName = ("memories/$writeInput.html");
$fileHandle = fopen($fileName, 'w+') or die("Cannot open file");
fwrite($fileHandle, $data);
fclose($fileHandle);
echo($fileName);
echo($data);
?>
It probably looks like a horrible hack job to you pros because I have tried so many bits of code, and I am sure I am just missing something silly, but I am at a loss...thank you anyone for any help!
This update should do the trick:
$(document).ready(function() {
$('#saveMemory').click(function(e) {
e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content, writeInput : $('#writeInput').val()}
//dataType: "html" // test
}).done(
function( data ){
$('#result).html( data);
}
);
});
});
Changes:
Added e to the click function. It provides the function with a reference to the event object.
Uncommented e.preventDefault() so the form won't execute breaking the ajax call.
Added writeInput to the post data.
Added a callback (.done). When the request is finished this function will execute writing the responseData into writeDiv
Add the following div directly in the body tag.
<div id="result" style="background-color: #f4f4f4;width:100%;height:300px;overflow: auto"></div>
I am trying receive the JSON data using PhoneGap application. I am using server xampp php server. On this server I have server code api.php for receiving data from database. My laptop's IP address is 192.168.1.4 so the URL of this local server is http ://192.168.1.4/Experiements/webservices/api.php".
I am able to receive the data using
alert(JSON.stringify(response));
but I want to add this _email_id_ information to
<div id="email">Email_id< /div >
which is defined in index.html.
From my Android phone I want to just log in and and receive the email_id of that user. Please see the image of my database and and data receive on my phone using
alert(JSON.stringify(response)).
My server code is api.php
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("demo");
if(isset($_GET['type']))
{
if($_GET['type']=="login"){
$username=$_GET['UserName'];
$Password=$_GET['Password'];
$query="Select * from registration where UserName='$username' and Password='$Password'";
$result=mysql_query($query);
$totalRows=mysql_num_rows($result);
if($totalRows>0){
$recipes=array();
while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){
$recipes[]=array('User'=>$recipe);
}
$output=json_encode(($recipes));
echo $output;
}
}
}
else{
echo "Invalid format";
}
My PhoneGap application code is in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title> Database Application</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, width=device-width">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densitydpi=medium-dpi, user-scalable=0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$("#btnLogin").click(function(){
var userId = document.getElementById('id').value;
var userPassword = document.getElementById('password').value;
$.ajax({
url:"http://192.168.0.106/Experiements/webservices/api.php",
type:"GET",
dataType:"json",
data:{type:"login", UserName:userId,Password:userPassword},
ContentType:"application/json",
success: function(response){
alert(JSON.stringify(response));
console.log(JSON.stringify(response));
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
},
error: function(err){
alert(JSON.stringify(err));
}
})
});
});
</script>
<script type="text/javascript">
document.addEventListener("deviceready",OnDeviceReady,false);
function OnDeviceReady(){
//alert("cordova is loaded");
}
</script>
</head>
<body>
User ID : <input type="text" id="id" name="user" />
User Password : <input type="text" id="password" name="password" />
<input type="button" id="btnLogin" name="btnLogin" value="Login"/>
<div id="email">Email_id</div>
</body>
</html>
DataBase: demo, user: root, password: 1234, table: registration
Screen shot of my phone:
So if I understood you correctly, what you want to do is to get the email_id from the response and put the content into the div called email.
What you need to do is to first get the user's email from the JSON object which is in your case Array with just one item. This first item of array again is Object which contains field called email which is exactly what we want. After that we need to locate the div from the DOM with jQuery element selector and insert the user's email in it. Example is found below.
var userEmail = response[0].User.email; // Find the email from the JSON
var emailDiv = $("div#email"); // Find the div for email with jQuery selector
emailDiv.text(userEmail); // Put user's email as text to that div
POST PHP to itself using AJAX does not return the expected value?
Parameters has been successfully send to POST, based on Firebugs Console
but it does not dispaly the result to the same page.
How to fix this?
labor.php
<?php
if(isset($_POST['from']) && isset($_POST['from']))
{
echo 'from: '.$_POST['from'].
' to: '.$_POST['to'];
//do something here
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Labor Reports</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker_from" ).datepicker();
$( "#datepicker_to" ).datepicker();
$( "button" )
.button()
.click(function() {
$.ajax({
url: 'labor.php',
type: 'POST',
data: { from: $('#datepicker_from').val().trim(), to: $('#datepicker_to').val().trim() },
success: function(){
}
});
});
});
You aren't doing anything with the returned data.
success: function(data){
alert(data);
}
data represents the response sent back from the server. In your case, it will be the echoed output of your from and to $_POST values. Coincidentally, you will also get the rest of the page sent back to you as well, you'll probably want to return false; after the echoes, so that it stops the printing of the page.
I have the following php script which works flawlessly in normal circumstances (i.e. visiting the page directly):
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="css/contact_search.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).click(function() {
$("#display").hide();
});
var cache = {};
$("#searchbox").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox.length < 3 ) {
$("#display").hide();
} else {
$.ajax({
type: "POST",
url: "contact_search/search.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
return false;
});
});
jQuery(function($) {
$("#searchbox").Watermark("Search for Group");
});
</script>
</head>
<body bgcolor="#e0e0e0">
<div class="body">
<div class="liquid-round" style="width:100%;">
<div class="top"><span><h2>Contacts List</h2></span></div>
<div class="center-content">
<img src="images/search.gif" style="float:right;" />
<input type="text" id="searchbox" maxlength="20" value="<?php echo $_SESSION['hello'];?>" />
<div id="display"></div><div style="clear:both;"></div>
</div>
<div class="bottom"><span></span></div>
</div>
<div class="liquid-round" style="width:97%;">
<div class="top"><span><h2>My Messages</h2></span></div>
<div class="center-content" style="min-height:200px;">
</div>
<div class="bottom"><span></span></div>
</div>
</div>
</body>
</html>
HOWEVER - when I add the following piece to the top of the page, the javascript/jquery functions simply stop working altogether.
<?php
session_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
?>
These pages require login so I need to ensure they are https protected but this error messes all that up. Any ideas what could be causing the issue?
It's probably the browser not displaying insecure (http) content on https pages, there's a simple fix though, use a scheme relative URL, like this:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
This way you'll get http://ajax.googleapis.com/.... on the http:// version of your page and https://ajax.googleapis.com/.... on the https:// version.
Since session_start produces HTTP-Headers I recommend to do the port check before session_start.
But, these lines should not affect your JS in any circumstances, because the redirect to HTTPS is independend from the fact if your site is working via HTTPS. So, if you are not sure, remove the lines and access your page with HTTPS. Bring JS to work there. And afterwards implement the redirect.