Changes to text file with php and ajax-driven form - php

i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help

I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined

Related

Ajax is not sending input of type password

i have a problem with AJAX , not sending the input of type password and when i change type to TEXT
it sends the data normally , the code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="username">
<input type="password" id="password">
<input type="submit" id="subit" value="send">
<div id="par"></div>
<script>
var user = $("#username").val();
var pass = $('#password').val();
$(document).ready(function(){
$("#subit").click(function(){
$.ajax({
type:"post",
url: "home.php",
data:{subit:1, username: user, password: pass }
}).done(function(resdata){
$("#par").html(resdata);
});
});
});
</script>
</body>
</html>
and code for processing data
<?php
require_once 'queries.php';
if(isset($_POST['subit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$data = selectrow("users","username,password","'$username','$password'");
if(!empty($data)){
echo $data['username']." ".$data['password'];
} else {
echo "No Data Found";
}
}
?>
i am connecting to the database and checking the data if exist , the PHP code is not wrong as i tried it with form and it was working ,now i am using AJAX, and not working now saying that data is not found , the second echo.

Issue with Ajax Contact Form

I am trying to put together a simple contact form with ajax, where users are not redirected to the contact.php file once the submission is done..
There is no errors.. I am always redirected..
Any idea please? Any suggestion is highly appreciated. Thanks!
contact.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form action="contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your Name">
</div>
<div>
<input type="email" name="email" placeholder="Your Email">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
<div>
<input type="submit" value="Send">
</form>
</body>
</html>
contact.php
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
print_r($_POST);
}
?>
main.js
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success:function(response) {
console.log(response);
}
});
return false;
});
You need to prevent the default form behavior.
$('form.ajax').on('submit', function(evt) {
evt.preventDefault();
You need to ouput json format so header need to be setting and you need to return json value to ajax success so need json_encode($object_or_array_form_php);
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
header("Content-type:application/json");
$_POST['success'] = "You form is sending ...";
echo json_encode($_POST); //this is the "response" param form ajax
}
?>
Hacked! Here's a little bit different way ..
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-message").load("contact.php", {
name: name,
email: email,
message: message,
submit: submit
});
});
});
</script>

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Can't see the expected result in a jQuery lab

The html code:
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript"
src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(msg) {
alert(msg);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
</head>
<body>
<div id="info1">
Put the textbox input value into this block.
</div>
<br />
<form id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit"
id="submit" value="Submit Form" />
</form>
</body>
</html>
The php code:
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo json_encode($result);;
When I entered the text, it cannot display the same text above the input box. Maybe there have some wrong code, but I cannot find it, please help><
Reframed your code. Checkout,
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$("form[id='form1']").on('submit', function(ev){
ev.preventDefault();
var th = $(this);
var data = th.serialize();
var action = th.attr('action');
$.post(action, data).done(function(response){
$("#info1").html(response.msg);
});
});
});
</script>
</head>
<body>
<div id="info1">
<!--Put the textbox input value into this block.-->
</div>
<br />
<form action="ex2_5.php" id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit" id="submit" value="Submit Form" />
</form>
</body>
</html>
ex2_5.php
<?php
$result = array();
if (!empty($_POST['form1']))
$result['msg'] = "<h1>".$_POST['form1']."</h1> is added";
else
$result['msg'] = "<h1>Field is empty!!</h1>";
header('Content-type: application/json');
echo json_encode($result);
Bugs:
1) ;; double semicolon
2) $_POST['form1'] in your PHP file
3) Wrong index using in JS while returning
Debugging:
Open console (Right click -> Inspect element -> Console tab) and checkout for errors
Solution 1:
Specify content type for ajax response as application/json. Otherwise the response will be a string not as json.
// Specify content type header as application/json
header('Content-type: application/json');
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo #json_encode($result);
Solution 2:
If header is not application/json then parse string into object using JSON.parse function.
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(data) {
var data = JSON.parse(data);
$("#info1").html(data.msg);
}, "json");
});
});
</script>

AJAX JQUERY Php form not working

issues are still there...pls help
I am unable to load external file while using AJAX jquery. I want to use Jquery ajax to pop up form then validate, enter data in mysql. but starting from a simple ajax function. kindly let me know where i am going wrong
<link rel="stylesheet" type="text/css" media="all" href="test_style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="contact_form">
<form id="ajax-contact-form" name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<INPUT class="button" type="submit" name="submit" value="Send Message">
</fieldset>
</form>
</div>
</body>
</html>
and contact.php file is
<?php
echo "Hello";
?>
You need to return false; to prevent the form from submitting and refreshing the page and check if your $("#div1") is missing.
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
return false;
});
});
Simple. Since you are posting your form through ajax, you must prevent the default form submit by returning a false inside the submit method. Below is the correct version:
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url:"contact.php",
data: str,
success:function(result) {
$("#div1").html(result);
}
});
return false;
});
});
</script>
You can use a more simple form of post request as follows:
$.post("url",{var1: value1, var2: value2},function(data,status){
if(status=='success')
alert(data);
});
the second argument you can pass as many using this post request. The first argument url, if ofcourse relative to the document in which this js is loaded or you can give the exact url on the server.
According to your php file, data=='Hello'.
Similar is the procedure for any GET request also.
Make sure you are missing the div1
please use
<div id="div1"><div>

Categories