I cannot make the following AJAX request work:
I want to make the text entered in the field to be displayed in the "p" tag
Server: Apache 2.2
PHP 5
My HTML:
<html>
<head>
<title>Test for reponder</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$function send() {
$('body').on('click', 'button', function(event) {
var namee = document.getElementById('name').value;
//var dataString='name ='+ name;
$.ajax({
type: 'POST',
url: 'responder.php',
data: namee,
success: function(html) {
$('#msg').html(html);
}
})
</script>
</head>
<body>
<input type="text" id="name">
<!--<input type="submit" id="button" value="Send" onclick="return send();">-->
<button type="button">Send</button>
<p id="msg"></p>
</body>
</html>
My PHP file:
<?php
$name=$_POST[ 'name'];
echo "response:" . $name;
?>
You can do something like this:
HTML
<input type="text" id="name">
<button type="button">Send</button>
<p id="msg"></p>
jQuery
<script>
$(document).ready(function(){
$(document).on('click', 'button', function(){
var name = $("#name").val();
var param = {name: name};
$.ajax({
type: 'POST',
url: 'responder.php',
cache: 'false',
data: param,
beforeSend: function(){
// before send
},
success: function(data){
// success
$('#msg').html(data);
},
error: function(){
// error
}
});
});
});
</script>
responder.php
<?php
if(isset($_POST['name'])){
$name=$_POST['name'];
echo "response:" . $name;
}
?>
Related
So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});
UPDATE
Objective post data (age and name) from www.domain1.com to www.domain2.com/try.php
Problem
am getting this on domain2.com/try.php
Undefined index: name
Undefined index: age
Index.html on domain1
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#clickMe").click(function () {
$.ajax({
type: 'post',
contentType: "application/json; charset=utf-8",
url: 'www.domain2.com/try.php',
dataType: "json",
data: {
name: "tom",
age: "30"
},
complete:
function (data) {
window.location = "www.domain2.com/try.php";
}
})
})
})
</script>
</head>
<body>
<input id="clickMe" type="button" value="clickme123"/>
</body>
</html>
try.php on domain2
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo 'name:'.$name;
echo 'age:'.$age;
On the first domain just use a form and post to the second domain:
<html>
<head>
</head>
<body>
<form action="http://two.example.com/foo.php" method="POST">
<input type="hidden" name="name" value="tom">
<input type="hidden" name="age" value="30">
<input type="submit" value="Go">
</form>
</body>
</html>
i am trying to use ajax submit form but for some reason it doesn't work for me, any suggestions how to fix it.
I'm getting the alert message when I submit but it takes me to another page, what am i doing wrong with ajax request ?
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// AJAX forms
$("#search_form").submit(function(e){
e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: { name: username },
cache: false,
success: function(data){
$('#results').html(data);
}
})
})
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
process.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Something wrong!";
exit;
}
$name = $_POST['name'];
$m = new MongoClient();
//echo "Connection to database successfully";
// select a database
$address = array(
'name'=>$name,
'city' => 'test',
'state' => 'test2',
'zipcode' => 'test3'
);
$db = $m->local;
//echo "Database mydb selected";
$collection = $db->user;
//echo "Collection selected succsessfully";
$collection->insert($address);
$user = $collection->findOne(array('name' => $name));
?>
<ul>
<li><?php echo $user['name']; ?>: <?php echo $user['city']; ?></li>
<script>
alert('test 1234');
</script>
</ul>
I had to change:
$("#search_form").submit(function(e){
to:
$(document).on('submit', '#search_form', function(){
Now it works fine.
<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
// AJAX forms
$(document).on('submit', '#search_form', function() {
//e.preventDefault();
//var data = $(this).serialize();
var method = $(this).attr("method");
var action = $(this).attr("action");
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: {
name: username
},
cache: false,
success: function(data) {
$('#results').html(data);
}
})
return false;
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php
Thanks to people from stackoverflow, they helped me to realize my functional with Ajax, but now I have another problem. Below is code:
if(isset($_POST['site'])){
if($_POST['site'] == NULL)
{
echo "Field cannot be empty";
return;
}
//here we check site validation on server side
if (!preg_match("~^(?:(?:https?|ftp|telnet)://(?:[a-z0-9_-]{1,32}".
"(?::[a-z0-9_-]{1,32})?#)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|".
"org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?".
"!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-z0-9.,_#%&".
"?+=\~/-]*)?(?:#[^ '\"&<>]*)?$~i", $_POST['site']))
{
echo "<br/>";
echo "<div id='err'>Oooops!!! Wrong site name</div>";
return;
}
$homepage = file_get_contents("http://".$_POST['site']);
preg_match('%<meta.*name="keywords".*content="(.*)"\s+/>%U', $homepage, $regs);
if(count($regs))
{
$myString = implode( '', $regs );
echo "<br/>";
echo "<div id='test'>Keywords:</div>";
print_r( "<div id='test2'>$myString</div>");
}
else
{
echo "<br/>";
echo "<div id='test'>There is no keywords</div>";
}
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#payment').submit(function(e){
e.preventDefault();
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
//data: $(this).serialize(),
data: x,
datatype: 'json',
success: function(data)
{
$('#metaTags').text(data)
},
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.status);}
});
});
});
</script>
</head>
<div>
<form id="payment" method="post" name="forma1">
<label for=name>ENTER www.bbc.com:</label>
<input id="name" type=text placeholder="Write here..." name="site">
<input type="submit" value="START" name="searchbutton" id="sb">
</form>
<div id="metaTags"></div>
</div>
</html>
Everything is ok, but the output you can see here:
http://tsite.500mb.net/test.php
for testing type for example: www.bbc.com and you'll see the output result
I need that the otput will only meta tags, without source code. How to do it?
I tried next idea:
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
data: x,
where data = x, and x - value from input textbox, but it doesn't help. Any ideas?
You can use the get_meta_tags() function, here is a quick and dirty sample you can take further.
php
<?
if (isset($_POST['site'])) {
if (empty($_POST['site'])) {
echo "<div>Field cannot be empty</div>";
} else {
//here we check site validation on server side
if (!preg_match("~^(?:(?:https?|ftp|telnet)://(?:[a-z0-9_-]{1,32}" .
"(?::[a-z0-9_-]{1,32})?#)?)?(?:(?:[a-z0-9-]{1,128}\.)+(?:com|net|" .
"org|mil|edu|arpa|gov|biz|info|aero|inc|name|[a-z]{2})|(?!0)(?:(?" .
"!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:/[a-z0-9.,_#%&" .
"?+=\~/-]*)?(?:#[^ '\"&<>]*)?$~i", $_POST['site'])) {
echo "<div id='err'>Oooops!!! Wrong site name</div>";
}
$metatags = get_meta_tags("http://" . $_POST['site']);
/* List all meta tags
echo "<pre>".print_r($metatags, true)."</pre>";
*/
if (count($metatags)) {
foreach ($metatags as $tag => $value) {
echo "<div class=\"result\"><strong>$tag:</strong> $value</div>";
}
} else {
echo "<div id='test'>There is no keywords</div>";
}
}
return;
}
?>
html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#payment').submit(function(e) {
e.preventDefault();
var x = $('input[name=site]').val();
$.ajax({
type: "POST",
url: 'test.php',
data: {site: x},
success: function(response) {
$('#metaTags').html(response)
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
});
});
</script>
<style>
.result {
margin-bottom: 15px;
}
</style>
</head>
<body>
<div>
<form id="payment" method="post" name="forma1">
<label for="name">ENTER www.bbc.com:</label>
<input id="name" type=text placeholder="Write here..." name="site">
<input type="submit" value="START" name="searchbutton" id="sb">
</form>
<div id="metaTags"></div>
</div>
</body>
</html>
Hope it helps.