I'm unable to make a call to an ajax function, shown below (index.php):
<script type="text/javascript">
$('.show_more').on('click',function (e){
$.ajax({
type:'POST',
url:'gallery_controller.php',
success:function(html){
$('.content').append(html);
}
});
});
my button click is here (index.php):
<form action="" method="post">
<button type="submit" class="show_more" name="next">Next</button>
</form>
this is my php script (gallery_controller.php):
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password, "dbgallery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT imagefile FROM tbl_images ORDER BY id DESC LIMIT 10 OFFSET 0");
while($row = $result->fetch_assoc()) {
echo '<h1>'.$row["imagefile"].'</h1><hr />';
}
?>
it seems to simply do nothing, i've tried a few things and nothing appears to work.. im wondering if ajax even works at all on my server.. i am a complete noob.
Do you need a form for that button?
If you wrapped the button into a form for W3C validity issues it's ok, you can simply change your button type attribute from type="submit" to type="button".
Please check the following complete code. I think "e.preventDefault();" is missing in your code.
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="" method="post">
<button type="submit" class="show_more" name="next">Next</button>
</form>
<div class="content">
</div>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script>
$('.show_more').on('click',function (e){
e.preventDefault();
$.ajax({
type:'POST',
url:'gallery_controller.php',
success:function(html){
$('.content').append(html);
}
});
});
</script>
</body>
</html>
Related
can anyone tell me how to retrieve data from database and display it in text box in html by using php ajax and jquery? it will just only display if the button is click. Thanks for helping!
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>registion</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
$('#btn').click(function () {
$.post(
'checkUserName.php',{
username:$('#username').val()
},function(data,textStatus){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<h1>registion</h1>
<form action="" method="post">
userNameļ¼<input type="text" name="username" id="username">
<input type="button" value="Verify userName" id="btn">
<br>
<span id="result"></span>
</form>
</body>
</html>
checkUserName.php
<?php
$uname = $_POST['username'];
$conn = mysqli_connect('localhost','root','root','db_user');
$query = "SELECT * from tb_user where name = '$uname' ";
$result = mysqli_query($conn,$query);
$nums = mysqli_num_rows($result);
//echo $query;
//echo $nums;
if($nums > 0){
echo "Username already exist";
}else{
echo "Username OK";
}
mysqli_close($conn);
Next time please post together what have you done so far. From there only the community will be able to help you.
HTML Code :
<input type="text" id="input-box">
<button type="button" id="btn_get">Click</button>
Ajax Code :
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box').val(data);
}
});
});
PHP Code :
//get data from db here
$data = 'foo';
echo $data;
i want to insert data to server using ajax in my chrome extension so my users can sign up to use my extension.
i am desperately finding solution not not find the example
when i code ajax on popup.html i got this error
"Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-lXzxt12nj+7ATE1j5ucGnYo1VkLZpNS/cGA9SL9nCv0='), or a nonce ('nonce-...') is required to enable inline execution."
popup.html Code
<!DOCTYPE html>
<html>
<head>
<style>
body {
width:300px;
font-size:12px;
}
</style>
</head>
<body>
<form action="" method="POST">
<input type="text" id="name" name="uname">
<input type="text" id="pass" name="upass">
<input type="submit" id="submit" name="submit" id="btn">
</form>
</body>
</html>
<script type="text/javascript" src="check.js"></script>
<script type="text/javascript">
$("#btn").click(function(){
var btn =$('#btn').val();
var name= $('#name').val();
var pas = $('#pass').val();
$.ajax({
data :{btn: btn, name : name, pas: pas},
method="POST",
url:"http://localhost/status/index.php",
success : function(data){
lb.val(data);
}
});
});
}
</script>
index.php code which is on server
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['byn'])){
$localIP = getHostByName(getHostName());
$name = $_POST['name'];
$pass = $_POST['pass'];
$insert = mysqli_query($conn,"INSERT INTO usercheck VALUES('','$name','$pass','1111,'$localIP')");
}
?>
I am curious to know if it's possible that I can have a div reload like a window does. The reason for this is I have a forum but I don't want a full page reload after four is completed. So I was wondering if just the elements that are in that div or forum section could do a background reload or just load by them self when the submit button is pressed.
This is in a file called forum where the information gets typed in. I want it to not reload the page but stay on that forum and still send the data to the database.
<html>
<body>
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
<div id = "load_results"></div>
</body>
</html>
This is sending the information to the database but I want it to be done discreetly.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Yes, there is a way. It is called AJAX - but, not to worry, it's pretty simple.
Your code will look something like this:
HTML:
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
js/jQuery:
$(function(){
$('form').submit(function(evt){
//next line stops form submission from sending you to `demo.php`
evt.preventDefault(); //evt stands for "event" - can be anything. I use e.preventDefault()
var fn = $('[name=firstname]').val();
$.ajax({
type: 'post',
url: 'demo.php', //send data ONLY to demo.php -- page stays as it is
data: 'first='+fn,
success: function(d){
if (d.length) alert(d);
}
}); //END ajax
}); //END document.ready
demo.php
<?php
$fn = $_POST['fn'];
//Do your database insert here
//If you wish, you can return some data to the AJAX's success function:
echo 'You submitted: ' .$fn;
Here are some posts with simple AJAX examples:
AJAX request callback using jQuery
I am making a question/status posting system using JQuery and Ajax however an error is being displayed "Notice: Undefined index: status in C:\xampp\htdocs\deadline\data.php on line 5" which is my line of code "$var = $_POST['status']; "
My system works as you have to log in to post a question(using sessions) BUT the issue is with my JQuery/AJAX script as the data that I have on homepage.php is not being sent to data.php (from my understanding which is why my index 'status' is undefined).
MY CODE
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
}
else {
header("location:login.php");
}
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = 'status='+status;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form action="" onsubmit="return false">
<textarea id="status"></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="status">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname">JOnathan</div>
<div id="statustext"> this is the question</div>
<div id="statusoption"><button id="likestatus">LIKE</button></div>
<div id="statusoption"><button id="commentstatus">COMMENT</button></div>
<div id="statusoption"><button id="sharestatus">SHARE</button></div>
<div id="statusoption"><button id="statustime">TIME</button></div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
<?php
$var = $_POST['status'];
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
echo " success";
}
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) {
echo "inserted successfuly";
}
else {
echo "failed: " . $conn->error;
}
echo " the text: " .$var. " has been added to database.";
?>
HOW IT SHOULD WORK
I want to use JQuery/AJAX on my homepage.php to send data to data.php and that data gets returned back to homepage.php. On success to be displayed in my div #statustext.
Meaning when i write a question in textarea input field the data gets stored in database and retrieved and displayed in my div on the browser.
Please help me thanks..
you should change your script like below. Ajax sends data to url in a serialize manner either you have to use form serialize which will send all the fileds info to your php url other wise if you have to send only one field value then you can do this change
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = {'status='+status};
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
First of all use .val() not .value() when you getting value of your message. Second mistake - is using two id = "sattus". Id of elements must be unique or use class = "" for ident your class of elements.
Don't give same id to more then 1 html element !
In your code :
<textarea id="status"></textarea>
and
<div id="status">
both contains same id ! Please correct it first.Also In your code as Spencer mentioned in his answer that add name attribute with value "status". No doubt as you are using jQuery selector it should pick up correct one,though you can just alert it before sending the request using AJAX.
also set data variable as var data = {status : status};
POST uses name and not id so change this:
<textarea id="status"></textarea>
To this:
<textarea name="status"></textarea>
For the data make sure it's the data for your form, and add method="post" to it so it can send POST data. For example if you gave your form an id of yourForm:
HTML
<form action="" method="post" id="yourForm" onsubmit="return false">
JS
$.ajax({
...
data: $("#yourForm").serialize(),
...
});
I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.