How to extract URL and store it to MySQL? - javascript

I have a textarea in which user enter url and link is extracted successfully and appended to a div. How can I store that extracted data into database as the extracted data is in a div not in any input?
<textarea id="get_url" placeholder="Enter Your URL here" class="get_url_input" spellcheck="false" ></textarea>
<input type="button" value="Share">
<div id="results">
</div>
Extracted data is shown in result div, do I need to store the response into any hidden input and check if it is empty while clicking on share button?

There are several ways to do this but I would recommend using:
Ajax and JQuery
In your JavaScript file add:
var data = $('#div id').text();
$.ajax ({
url: "www.websitename.com/addurl.php",
type: 'POST',
data: { urltoadd: data},
success: function (response){
If (response = 'successful'){
return true;
}else {
return false;
}
}
});
Now in your addurl.php file:
<?php
$urltoadd = $_POST ['urltoadd'];
... add Code to save $urltoadd in your database.
If (file was added successfully){
echo 'successful';
}else {
echo 'failed';
}
? >

On form submit you can bind a function and in that functiom
using jquery you can do $('#result').text()

Related

How to submit a form and get some text in return using Ajax

This is my Fiddle code:
$("form.signupform").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
$(form).children(".signupresult").html(data.signupresult);
$(form).children(".signupresult").css("opacity", "1");
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form class="signupform" method="post" action="admin/signupinsert.php">
<p class="signupresult"></p>
<input type="text" name="firstname" />
<input type="submit" value="Sign Up"/>
</form>
Signupinsert.php page code:
// Code to insert data into Database
$signupresult = "Some value here";
$response = new \stdClass();
$response->signupresult = $signupresult;
header('Content-Type: application/json');
print json_encode($response);
Expected Result:
When user clicks on submit form button, the code runs in background. And submits the form without reloading the page.
And the signupinsert.php page return some text, and its text display on a paragraph with class signupresult.
And the form can be submitted unlimited times, without reloading the page.
Problem:
The form only gets submitted once. If I try to submit it twice, "Nothing Happens" (No values inserted into database, no value returned in paragraph with class signupresult.
Where is the problem?
You have to tell your request that you expect JSON as return. Else data.signupresult doesn't make sense; data is seen as a string.
I always use $.ajax, never $.post; I find it easier to add options.
$.ajax({
url: $(this).attr("action"),
dataType: 'JSON',
type: 'post',
data: $(this).serialize(),
success: function(data) {
...
}
})

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

Extracting data from HTML form with inputs with JavaScript or AJAX and then passing it on to PHP

I have an issue I can't seem to solve, I have a form with a bunch of text-fields but I need to extract their information through AJAX or just through a simple JavaScript function. I need this data to be extracted, string by string into an array which should then be passed to PHP. If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. Anyway I've been searching google for good examples, and I really can't find anything good.
<form class="registration" method="POST">
<ul class="registration">
<li><label>Nombre de Usuario:</label></li>
<li><input type="text" name="username" title="Nombre de Usuario"/></li>
<li><label>Contraseña:</label></li>
<li><input type="text" name="password" title="Contraseña"/></li>
<li><label>Correo Electrónico:</label></li>
<li><input type="text" name="email" title="Correo Electrónico"/></li>
<li><label>Nombre:</label></li>
<li><input type="text" name="name" title="Nombre"/></li>
<li><label>Primer Apellido:</label></li>
<li><input type="text" name="first last name" title="Primer Apellido"/></li>
<li><label>Segundo Apellido:</label></li>
<li><input type="text" name="second last name" title="Segundo Apellido"/></li>
<li><input type="submit" name="create user" title="Crear Usuario" value="Crear Usuario"></input></li>
</ul>
</form>
This is my form, some of the values are in Spanish, the website I'm supposed to make has to be in that language. If I understood things right, I should call the function I want with an "OnClick" through my submit input button. This is the first time I've done web development, and understanding CSS and HTML was difficult for me. I was wondering if someone could help me out with an example or something. I'm basically using MVC to organize this, with HTML and JavaScript as the View, PHP as the control and Oracle SQL as the model. I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP.
I'm not looking for anyone to fix my thing or anything of the sort, all I need is an example and small explanation if possible.
You need to figure out $.ajax function. It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. Here is sample of code :
$('input[type=submit]').on('click',function(e)
{
e.preventDefault();
var my_username = $('input[name=username]').val();
.....
..... more here
$.ajax({
type : 'POST', //<--- GET or POST
url : 'url_of_insert_process.php',
data : {
username: my_username,
.....
..... more here
}
success : function(data){
// Here you can populate the view whatever you want
// like showing message success
}
});
});
That is the illustration sending the data. You also can use $("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. So many sources out there that you can put into your table.
Please try
$(document).ready(function(){
$('input[type="submit"]').click(function(e){
e.preventDefault();
$.ajax({
url: "YOUR_URL",
type: 'POST',
data:$("form#registration").serialize(),
success: function( response ) {
console.log(response);
}
});
});
});
//jsfile.js
//THIS METHOD RETURN THE name : value PAIR FROM
//A SPECIFIED FORM ID OR FORM IN THE CURRENT SPHERE
function formHandler(formID="") {
try {
if (formID === "") {
//PICK UP THE FORM IN THE CURRENT SPHERE
formElms document.querySelectorAll("input,select,textarea");
} else if(formID !== "") {
//PICK UP THE NAMED FORM
var formsElms = document.querySelectorAll("form");
formsElms.forEach(function(formElm) {
if (formElm.id === formID) {
formElms = document.querySelectorAll("#"+formID+" input, #"+formID+" select, #"+formID+" textarea");
}
});
}
if (formElms) {
var retObjs = new Array();
if (formElms) {
formElms.forEach(function(param) {
retObjs.push({name : param.name, value: param.value});
});
}
}
return retObjs;
} catch (e) {
console.log(e);
}
}
serverSideHandler(inda={}) {
try {
indata = inda;
complUrl = "url.php";
$.ajax({
method: "POST",
url: complUrl,
data: indata
})
.done(function(retData) {
serverResponseHandler(retData);//Function To Callback
});
} catch(ev) {
console.log(ev);
}
}
//url.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/json');
ini_set('memory_limit','1024M');
if (!empty($_POST)) {
//Extract your form Inputs as follow
$name = doSomeValidation($_POST['name']);
//Do DB connections
//Do your CRUD
//DO OTHER ACTIONS
}

How to use jQuery AJAX with PHP to submit a form into a mySQL database with using an <a> tag?

What I am trying to do is create a "save" button for my website which saves specific posts and comments, exactly like the "save" button on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save".
HTML
<div id="message1">
<div id="pmessage"><p><?php echo $myComment;?></p></div>
Save
Edit
Hide
</div>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $myComment; ?>">
</form>
jQuery
$('a.Save').click(function () {
if ($(this).text() == "Save") {
$("#1234").ajax({ url: 'ajaxexample.php', type: 'post', data: 'message' });
$("a.Save").text("Unsave");
} else {
$("a.Save").text("Save");
}
});
PHP5.3
$message = $_POST['message'];
$query = "INSERT INTO saved (comment) VALUES (?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $message);
$statement->execute();
$statement->store_result();
$submissionWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($submissionWasSuccessful)
{
header ("Location: index.php");
}
$myComment = "This is my message!";
As of now all I am trying to do is submit the message "This is my message!" into the database table "Saved". What is wrong with my code? Why can I not submit the data to the table and how can I fix it? Thanks in advance!
Submit form when someone clicks on a.Save
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
submit handler on form#1234
$("#1234").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
// data stores the response from ajaxexample.php
// Change the html of save by using $("a.Save").html("Unsave");
}
});
});
Serialize automatically makes a query string.
$(".save").bind("click",function(e){e.preventDefault();
$.ajax({
url : $("#1234").attr("action"),
type : "POST",
data : $("#1234").serialize(),
success : function(data){},
fail : function(data){},
});
});

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

Categories