I've a really simple case , but made me confused , here is script =>
<!DOCTYPE html>
<html>
<head>
<title>HI</title>
<link rel="stylesheet" href="./scripts/css/default.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form name="ok" method="post" action="index.php">
<select name="sel" id="sel"><option value="a">1</option><option value="b">2</option><option value="c">3</option></select>
</form>
FIRST PAGE
<div id="as"></div>
<script type="text/javascript">
document.getElementById("sel").onchange = function(){
var doc = false;
if (window.XMLHttpRequest){
doc = new XMLHttpRequest();
}
if(doc){
doc.open("POST","./index.php",true);
doc.onreadystatechange = function(){
if (doc.status==200 && doc.readyState==4){
document.getElementById("as").innerHTML = doc.responseText;
}
};
doc.send("sel=" + document.getElementById("sel").value);
}
};
</script>
<?php
if (isset($_POST['sel'])){
echo $_POST['sel'];
}
?>
</body>
</html>
from this script I expect that onselect change returns me value of the select element , but it returns whole page again , why ? any ideas ? please help , thanks :))
PS. this is self index.php page
Create a separate php file to handle to your ajax requests that way ajax request will only show you the the texts echoed out by the php file.
This is my example code:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
if (isset($_POST['sel'])){
echo "yeah";
}
}else{die('You are not allowed to access this page!');}
Related
emphasized texti need help creating an onclick() function for an tag, that when it is activated it writes to 3 different rows in an MSSQL DB.
Im trying to figure it out, but my knowledge is not that great, i know i might have to use AJAX for this work.
Using MSSQL 2017, PHP 7.1
MY end result is to create a Click counter, the name of the section clicked and the date/time it was clicked.
IF anyone can help me, i appreciated very much.
Thank you.
Thanks for the guidance!!!
Edit
test.php
$counterServer = "TEST\TEST";
$counterconnection = array( "Database"=>"TestingCounters","UID"=>"User","PWD"=>"1234","CharacterSet"=>"UTF-8");
$finalcon = sqlsrv_connect( $counterServer, $counterconnection);
if( !$finalcon ) {
die( print_r( sqlsrv_errors(), true));
}
$sequel = "INSERT INTO dbo.CounterTest(Visit,Date_Value,Section)
VALUES('1',getdate(),'Kitchen')";
and my dumb logic , but i later realized i dont need to use a button but an anchor.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button action="test.php" method="post">click</button>
</body>
</html>
Final Working Test HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
function ctest(){
$(document).ready(function () {
$.post('test.php', // url
{ Section: 'something.' });
});
}
</script>
</head>
<body>
<h1> jQuery post() method demo
</h1>
click me
<p>
</p>
</body>
</html>
Use Jquery library for Ajax request then add the onclick event on the button to make the ajax request.
https://www.tutorialsteacher.com/jquery/jquery-post-method
You can see the example of ajax on this link. The url should be where your php script is to send the 3 different rows in an MSSQL DB.
Lately I've been experimenting with AJAX and jQuery. But somehow $.post method doesn't seem to work. Anybody got solutions?
Here's my code.
<html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="jquery-3.3.1.js"></script>
<script type="text/javascript">
function send(){
$.post('t.php', {stuff:1}, function(data){
if(data == 'success'){
alert('works');
}
});
}
</script>
</head>
<body>
<div id="btn" onclick="send()">CLICK</div>
</body>
</html>
and my t.php:
<?php echo "success";?>
It works actually but you don't know that how to get response from php file properly
Change ajax code like below:
$.post('t.php', {stuff:1}, function(data){
if(data[0] == 's'){//changed here. data is an array not string
alert('works');
}
});
And in php
<?php echo "s";?>
I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');
hi every body i was testing a code for checking name availability with ajax and i dont now why its doesnt work
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<title>index</title>
</head>
this is the body and the jquery function
check
<div id="answer" >
<script type="text/javascript">
//script
$(document).ready(function() {
$("#checkme").click(function(){
$("#answer").ajaxStart(function() {
$(this).text("loading .. .").show("slow");
});
var Userme = $("#username").val();
$.ajax({
type:GET,
url:"file.php",
data:"username=" + Userme,
success: function(msg){ $("#answer").text(msg).fadeIn("slow");}
});
});
});
</script>
</div></form>
</body>
</html>
and this is php code
<?php
$names = array (A,B,C,D);
$username = $_GET['username'];
if(in_array ($username , $names)){
echo "ok";
}else{
echo "doesnt exist ";
}
?>
plz help
im new with jquery and ajax and i cant guess the mistake i hope you can help me
It's unclear what exactly the problem is as I can see multiple errors.
In your javascript code:
type:GET should be type: "get"
data:"username=" + Userme should be data: {username: Userme}
In your PHP code:
$names = array (A,B,C,D); should be $names = array ("A", "B", "C", "D");
I have looked at other questions and cannot find the answer to why this isn't working. I am following a tutorial online. Here is my code:
HTML file:
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<h4>Enter an Item</h4>
<input type="text" id="item" /><br />
<input type="button" id="button" value="Submit" /><br />
<div id="content"></div>
<script type="text/javascript" scr="ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
</body>
</html>
JS file:
$('#button').click(function() {
var item = $('#item').val();
$('#content').text('Loading...');
$.post('ajax.php', { item: item }, function(data) {
$('#content').text(data);
});
});
PHP file:
<?php
include 'db.php';
if (isset($_POST['item'])) {
$item = $_POST['item'];
$sql = mysql_query("INSERT INTO items(item)VALUES('$item')");
if ($sql === true) {
echo "Inserted into database";
} elseif ($sql ==== false) {
echo "Error inserting into database";
}
}
?>
I don't see what I'm doing wrong. The tutorial has the same code. Thanks for your help.
moonwave99 is right (I'm not sure why the downvotes).. and also the scr="ajax" should be src="ajax" in your html and should be put in head or even before. Other reason may be the position of ajax.php to the site, maybe declaring whole URL will help :
$.post('http://wholeurl/ajax.php', {
item: item
}, function(data) {
$('#content').text(data);
});
Hope this helps, if not please specify error.
Well i dont know if i can help you:
You have some mistakes on your code
The elseif condition is not ====(4) just ===(3)
The ajax.js file should be after the jquery library
The src attribute is not scr.
And of course the URL of the jquery library should start with http:// because is an external resource.
The mysql_query() function should have the conection variable, Example:
mysql_query("[query here]", $connect);
Beside any other error you may get, you should import jQuery before your script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ajax.js"></script>