parse title of other urls using jquery - javascript

i am looking for a way to get title of urls mentioned in the webpage.
I tried http://urldecoderonline.com/ but it does not provide a way to parse the page.
Just for ex: user enters a url say http://www.google.com in a text input box and on pressing a submit button i would like to alert him with a title of "http://www.google.com"
Any ideas??

you need to use ajax and a php ajax proxy script on your server
i didn't test this, but it should work
ajax_proxy.php
<?php
if(isset($_POST["url"]){
echo file_get_contents($_POST["url"]);
}
?>
js
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "post",
dataType: "text",
url: "ajax_proxy.php",
data: { url: $("#input").val() }
success: function(data){
alert($(data).find("title").html());
}
});
});
});

If the problem is to extract the host part from the URL string, then this is a typical regular expression problem.
If there's something before the first semicolon, that's the protocol. Everything from there up to the forward slash is the host.
Something along the line of:
<http>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function parseUrl(url) {
var regexStringProtocol = '^([A-Za-z]*)://';
var protocolResults=new RegExp(regexStringProtocol).exec(url);
if(protocolResults) {
var protocol = protocolResults[1];
url = url.substring(protocolResults[0].length);
}
else {
var protocol = '';
}
var regexStringHost = '^([^/^?]+)';
var hostResults = new RegExp(regexStringHost).exec(url);
if(hostResults) {
var host = hostResults[1];
}
else {
host = '';
}
alert('Protocol: ' + protocol + '\nHost: ' + host);
// Continue parsing if you care about the part and the parameters
}
$(function() {
$('input').val('http://stackoverflow.com/questions/6715438/parse-title-of-other-urls-using-jquery/6715527#6715527');
$('#parse').click(function() { parseUrl($('input').val());});
}
);
</script>
</head>
<body>
<input type="text" style='width:150mm' />
<br />
<button id="parse">Parse</button>
</body>
</html>

To get title of a href link you can use attr function of jQuery.
$("a").attr("title");
To get titles of all links on page:
$("a").each(function(){
var title = $(this).attr("title");
});

Related

how to update a value in database using jquery when a link is clicked in php

I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>

Loading all files in jQuery ajax before success function PHP jQuery

I have a script like this.
The jQuery ajax loads all my files with no issues.
The ajax_load_books.php file have lot of css and js(inline edit, sliders etc.) files in it.
The problem is:
How to load all the files before the success function so that the user can see the loader_div message untill all the files are loaded.
In other words - Load all the js/css files and proceed with the success function.
Even I have checked with .load() function. Could someone redefine the below code .
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
$("#loader_div").show();
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Thanks,
Kimz
For the css files, you can find them using jQuery.parseHTML() function, but the <script> will be stripped with this so instead we would have to use regex for the <script> tags.
Try:
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$("#loader_div").show();
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
//parsing <link>
var $str = $('<output>');
//loading html into fake tag
$str.load("ajax_load_books.php");
//now $str includes all your page code
temp = $.parseHTML(str);
$.each(temp, function (i, el) {
//finding the <link> tag
if (el.nodeName == 'LINK') {
//appending it to the <head> tag
$('head').append("<link rel='stylesheet' href='" + el.getAttribute('href') + "'>");
}
});
//for script we will use regex
var pattern = /<script[^>]+?>.*?<\/script>/gi;
var matches = str.match(pattern);
var scripts = "";
for (var i in matches) {
scripts += matches[i];
}
//appending script tag to <head>
$('head').append(scripts);
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Demo
There is a drawback with this, your stylesheets and script code will repeat. If the above code causes issue running because of the repetition, you should place the code of beforeSend() before the AJAX and have a parameter sent from your AJAX function indicating that when an AJAX is called with this parameter, to execute all the HTML except the stylesheets and js scripts.

Putting multiple JS scripts 1 one JS file

I'm putting multiple 2 JS scripts in 1 file, and although they worked well independently when wrapped around the when in html file, the 2nd one simply doesn't work when I calls them from an outside JS file.
Here's the JS code:
// start of open the name div
$(function() {
$('.reply_submit_name_open').click(function(){
$(this).siblings('.reply_submit_name').fadeIn();
$(this).fadeOut();
});
$('.check_author').click(function(){
if($('.check_author').is(":checked")) {
$('.name_input').val($(this).val());
$('.name_input').attr('readonly', true);
} else {
$('.name_input').attr('readonly', false);
}
});
});
// end of opening name div
// start of posting replies
var base_url = '<?php print base_url();?>';
var interview_id = '<?php echo $this->uri->segment(3)?>';
$(function() {
$('.reply_button').click(function(){
var this_a = $(this);
var reply = $(this).parents().siblings('textarea').val();
var username =$(this).siblings().find('input').val();
var parent_comment_id=$(this).closest('form').attr('id');
var last_reply_id=$(this).closest('.reply_form_div').siblings('.replies').children().last('.comment').attr('id');
$.ajax({
type:"POST",
url: base_url + "comment_upload/reply_upload",
data:{parent_comment_id : parent_comment_id, interview_id: interview_id, reply:reply, username: username},
dataType: "json",
success: function(data,status){
if(data.state == 'succ') {
this_a.html('Success');
$('.reply_button').closest('.reply_form_div').siblings('.replies').append(data.new_reply);
} else {
this_a.html('Bad');
}
}
});
});
});
// end of posting replies
What's the cause? Appreciate any advice.
You've got a bunch of PHP in there that certainly won't be evaluated if you move this to an external .js file, unless you've configured your server to run all .js files through php.

Jquery call PHP response failed

I have two files one php and one html, the html file serves as the users interface where the users input their queries, the php files serves as the process or where the event will happen then it will return them to the html file for the output. According to my friend the best way to link the two is using jquery or ajax which I'm not quite sure. I tried to link them using this code but it didn't work if you can help me find my mistake I would gladly appreciate it.
HTML File
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.buildaddress').not('#formatted_address');
var vals = form.map(function () {
var value = $.trim(this.value);
return value ? value : undefined;
}).get();
$('#formatted_address').val(vals.join(', '));
</script>
when I added this part the link didn't work
<script>
$('#Compare').click(function(e) {
e.preventDefault();
var address = $('#address').val();
var formatted_address = $('#formatted_address').val();
console.log(address);
console.log(formatted_address);
$.ajax({
type: 'POST',
url: 'Corrections.php',
data: {
var1: address,
var2: formatted_address
},
success: function(data) {
document.getElementById('cor').value = data;
}
});
});
});
</script>
PHP file
<?php
$str1 = $_POST['var1'];
$str2 = $_POST['var2'];
$tempArr;
$var2;
$ctr=0;
echo "Input: $str1\n";
echo "Output: $str2\n";
?>
You have an extra }); in your script. Just remove the extra }); in your second script, your code will work
<script>
$('#Compare').click(function(e) {
e.preventDefault();
var address = $('#address').val();
var formatted_address = $('#formatted_address').val();
console.log(address);
console.log(formatted_address);
$.ajax({
type: 'POST',
url: 'Corrections.php',
data: {
var1: address,
var2: formatted_address
},
success: function(data) {
document.getElementById('cor').value = data;
}
});
});
//}); should be removed
</script>

Jquery post, response in new window

I have a script that on.DocumentReady posts data to another page. That page responds with some HTML encapsulated in one div tag.
My goal is to have this post response/data open in a new window.
Any hints or clues?
Here is the snippet I created from Dr. Mille's advice.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var packslip_id = 35592;
var po_no = 0018439;
var box_no = 1;
$.post("https://example.com/barcode/generate", { packing_slip: packslip_id, reference: po_no, total_boxes: box_no},
function (data) {
alert(data);
var win=window.open('about:blank');
with(win.document)
{
open();
write(data);
close();
}
});
});
Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:
Example:
<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
<input type="hidden" name="packing_slip" value="35592" />
<input type="hidden" name="reference" value="0018439" />
<input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>
Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.
I did it with an ajax post and then returned using a data url:
$(document).ready(function () {
var exportClick = function () {
$.ajax({
url: "/api/test.php",
type: "POST",
dataType: "text",
data: {
action: "getCSV",
filter: "name = 'smith'",
},
success: function(data) {
var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
w.focus();
},
error: function () {
alert('Problem getting data');
},
});
}
});

Categories