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>
Related
So I'm making a form that puts info into my local mysql db. But I stuck when I try to POST it. I getting "405 method not found" when try to debbug. I'm sing xampp for my virtual DB, maybe it's because of that?
The code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Kasmetinių atostogų prašymas</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="title">
<h1>Kasmetinių atostogų prašymas</h1>
</div>
<div class="form">
<form id="requestForm" method="POST" target="_blank">
<input type="date" name="request_date" id="input_field" placeholder="Prašymo data" required></br></br>
<input type="text" name="first_name" placeholder="Vardas" id="input_field" required></br></br>
<input type="text" name="last_name" placeholder="Pavardė" id="input_field" ></br></br>
<input type="number" name="personal_code" placeholder="Asmens kodas" id="input_field" min="11" max="11" ></br></br>
<input type="text" name="p_address" placeholder="Jūsų adresas" id="input_field" ></br></br>
<input type="date" name="requestDateFrom" id="input_field" placeholder="Atostogos nuo" ></br></br>
<input type="date" name="requestDateTo" id="input_field" placeholder="Atostogos iki" ></br></br>
<input type="number" name="daysNumber" placeholder="Atostogų dienų skaičius" id="input_field" ></br></br>
</br>
<Input type="button" name="submit_button" id="buttonLast" value="Patvirtinti">
</form>
</div>
<script>
$(document).ready(function(){
$("#buttonLast").click(function(){
$.ajax({
url:"http://127.0.0.1:5500/insert.php",
type: "POST",
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
});
</script>
</body>
</html>
And this is php code to connect db and post info into specific columns.
For the purpose of test I trying to post just from the 3 cols.
PHP:
<?php
$con = mysqli_connect("localhost","root","","test");
if(!$con)
{
echo 'Connection problems';
}
else
{
echo 'Ok';
}
if(isset($_POST['submit'])){
$date = $_POST['requestDate'];
$name=$_POST['firstName'];
$lname = $_POST['lastName'];
$query = "insert into info (date,name,lname) values ('$date','$name','$lname')";
if($con->query($query) === true )
{
echo 'Duomenys išsaugoti!';
}
else{
echo 'Duomenų nepavyko išsaugoti!';
}
}
header("refresh:2; url=index.html");
?>
Change
type: "POST"
to
method:"POST"
Other error you might encounter:
You are using requestDate in php but request_date in html. Similar for other params.
Update:
Add cors header to Ajax call
url:"http://127.0.0.1:5500/insert.php",
method: "POST",
headers: {
'Access-Control-Allow-Origin': '*'
},
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
$(document).on("submit", "#requestForm", function (event) {$.ajax({
url:"https://127.0.0.1:5500/insert.php",
type: "POST",
data:$(this).serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
Try this Jquery Code.
My response text has html tags which causes ERROR to fire instead of SUCCESS. What am I doing wrong?
Here's my html code:
<head>
<title>HTML Window</title>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function post() {
var email = document.getElementById("email");
var password = document.getElementById("password");
var data = {
email: email.value,
password: password.value
};
$.ajax({
type: "GET",
url: "http://localhost/ParentChild/index.php",
dataType: "json",
data: data,
success: function (response) {
console.log("SUCCESS");
console.log(response);
},
error: function (response, textStatus, errorThrown) {
console.log("ERROR");
console.log("Status: " + textStatus);
console.log(response.responseText);
}
});
}
</script>
</head>
<body>
<form method="GET" action="javascript:post();">
<div>
Parent Window
<br><label for="email">Email: <input type="text" id="email" name="email"></label>
<br><label for="password">Password: <input type="text" id="password" name="password"></label>
<br><input type="submit" value="Post">
</div>
</form>
</body>
Here's my php:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$response = array(
"a" => "test");
echo (json_encode($response);
?>
</body>
</html>
And here is the console message:
ERROR
(index):28 Status: parsererror
(index):29 errorThrown: SyntaxError: Unexpected token < in JSON at position 0
(index):30 <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{"a":"test"} </body>
If I remove dataType: "json", I SUCCESS fires but the html tags are still part of the response text.
What am I doing wrong?
Your PHP script that return data to the ajax call should be treated pretty much like a subroutine and not a web page. If you have HTML in that script, it will also be sent back to the browser as part of the total response.
So amend the script to this i.e. remove all the HTML you had in it
<?php
$response = array("a" => "test");
echo (json_encode($response);
?>
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;
}
?>
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>
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.