How print AJAX data? - javascript

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.

Related

JS code working in chrome and IE, not in safari and firefox

I have the below js code that is working in chrome and IE but not safari and firefox. In both cases, the beforeSend: function works, but the success function does not work. Is this a problem with the CSS or am I missing something in the javascript?
---JS----
$("#updateBidButton").click(function () {
var bid_amount = document.getElementById("auction_bid_input").value;
var item_id = "<?php echo $this->item['id']?>";
var current_bid = "<?php echo $this->item['current_bid']?>";
var url_view = "<?php echo $this->item['url_view']?>";
$.ajax({
type: 'post',
url: "?module=items&controller=index&action=submitBid",
dataType: "text",
data: 'bid_amount=' + bid_amount + '&item_id=' + item_id + '&current_bid=' + current_bid + '&url_view=' + url_view,
beforeSend: function () {
$('.auction_box').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
$.get(window.location.href, function (data) {
$('.auction_box').animate({
'backgroundColor': '#A3D1A3'
}, 400);
});
} else {
alert(result);
$('.auction_box').animate({
'backgroundColor': '#FFBFBF'
}, 400);
}
}
});
});
Here is the html:
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="auction_bid_box">
<label for="auction_bid_input">
<!-- Starting bid EXISTS -->
<?php if ($this->item['bid_count'] >= '1') { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to update the current bid.
<!-- Starting bid is MISSING-->
<?php } else { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to enter a starting bid.
<?php } ?>
</label>
<span class="auction_bid_container">
<input id="auction_bid_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bid_amount" value="Enter Bid"/>
<input id="updateBidButton" type="submit"
value="<?php echo $this->translate('Update'); ?>"
class="button grey-button num-items-button"/>
</span>
</div>
</div>
</form>

ajax is not reading json php response correctly

I have done a lot of reading research on trying to figure out why ajax is reading a json response as undefined, and of course I have tried a lot of those solutions too, but unfortunately they don't work for me. If you guys can help, it would be GREAT!!!!
I have tried adding dataType: 'json', using data.status and data['status'], they still come as undefined. I can see see php responding the correct status in json format (an example of the response is at the bottom of the page)
php side:
//doing sql query
if ($conn->query($sql) === TRUE) {
$response_array["status"] = "success";
} elseif ($conn->errno == 1062) {
$response_array["status"] = "dup";
} else {
$response_array["status"] = "error";
}
header('Content-Type: application/json');
echo json_encode($response_array);
jquery side:
$(document).ready( function(){
$('#name_form').submit( function(event) {
if ( !formValidation()) {
event.preventDefault();
} else {
var datastr = $('#addclass_form').serialize();
$.ajax({
type: 'POST',
url: someurl,
data: datastr,
success: function(data) {
alert(data.status);
console.log(data);
},
error: function() {
alert('php error');
}
});
}
});
});
html side:
<form id='name_form'>
<div>
<b>Class Name</b>
<input type='text' name='classname' id='classname' placeholder='Enter Class Name'>
</div>
<div class='ui-grid-c'>
<div class='ui-block-a main'><b>Component</b></div>
<div class='ui-block-b point'><b>Max Point</b></div>
<div class='ui-block-c per'><b>Percentage</b></div>
</div>
<div id='components'>
<div class='ui-grid-c'>
<div class='ui-block-a main'><input type='text' name='component0' id='component0' placeholder='Component'></div>
<div class='ui-block-b point'><input type='number' name='point0' id='point0' placeholder='Max Point'></div>
<div class='ui-block-c per'><input type='number' name='percentage0' id='percentage0' placeholder='Percentage'></div>
<div class='ui-block-d rm'><button type='button' class='ui-btn ui-icon-delete ui-shadow ui-corner-all ui-btn-icon-notext' disabled></button></div>
</div>
</div>
<br>
<input type='hidden' name='compSize' id='compSize'>
<input type='submit' class='ui-btn ui-btn-b ui-shadow ui-corner-all' value='Create Class'>
</form>
output of console.log(data):
<!doctype html>
<html>
<head>
</head>
<body>
{"status":"success"}
</body>
</html>

I can't get my ajax request to work

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;
}
?>

Ajax form submit using mongodb

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>

Submitting post between ajax and php

I'm a newbie in the world of php and I was trying to learn it with a simple page.
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> Logout</div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>

Categories