I am trying to adapt the following code to my application.
Multiple Autocomplete jsfiddle The jsfiddle works -- my PHP application doesn't.
My application is a PHP based Xataface application that I have added a custom mobile create page to. I want to get the suggestion list from mysql.
It works fine for the first suggestion and then pops in the comma.
THE PROBLEM: The problem is that in my application it doesn't show a suggestion list for the second entry (after the comma).
I have done a lot of google searching and I don't see relevant pages that may help me out.
Can someone please help me get this to show the suggestion list for the second and subsequent entries into the field?
Below is my code...
My form is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Create Form Mobile 9</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<link rel="stylesheet" href="css/create9form.css" />
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script type="text/javascript">
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ initialize validation plugin jquery.validate.min.js
$(document).on("pageshow", "#create9Page", function() {
$("#cform9").validate();
});</script>
<script type="text/javascript">
$(function() {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tagsf2").autocomplete({
//reference: http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
minLength: 1,
source: "actions/tags.php",
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(",");
return false;
}
});
});
</script>
</head>
<body>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ debugging -->
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ end debugging -->
<div data-role="page" id="create9Page">
<div id="errorBox"><ul></ul></div>
<form action="index.php" id="cform9" method="POST" data-ajax="false">
<div data-role="fieldcontain">
<label for="notef2">Note:</label>
<textarea cols="40" rows="8" name="notef2" id="notef2" class="required"></textarea>
</div>
<div class="control-group">
<label for="tagsf2">TagsField: </label>
<div class="controls">
<input type="text" id="tagsf2" name="tagsf2" autocorrect="off" class="required" />
<!-- <input type="hidden" id="form_submitted" name="form_submitted" value="true" />-->
</div>
</div>
<input type="hidden" name="urlsave" value="<?php echo $url ?>" />
<input type="hidden" name="-action" value="create9note" />
<input type="submit" value="Submit" id="submit" name="submit" data-theme="a" />
</form>
</div>
</body>
</html>
My tags.php file is as follows..
<?php
require_once "configphp.dbc";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = \mysql_query("SELECT * FROM nte_tags where tags_list like '%" . mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query. */
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['tags_id'] = $row['tags_id'];
$row_array['value'] = $row['tags_list'];
//$row_array['abbrev'] = $row['abbrev'];
array_push($return_arr, $row_array);
}
}
/* Free connection resources. */
//mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
Screenshots:
First suggestion list shows OK.jpg
Suggestion list for second entry is not showing.jpg
As I was reading more and searching more, I found multiple-remote autocomplete code on the jquery ui website. Funny how you can search and read for a long time and not run across some obvious helpful information.
jquery ui website .. http://jqueryui.com/autocomplete/#multiple-remote
I used the example code below and edited it to suit my application.
It works now and solved my problem in my application.
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
Related
I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>
I have a textbox (auto-complete) where users can enter an actor/actress name which works fine.
As soon as user insert a name in the textbox, a dynamic dropdown should be populated showing list of movies by that actor.
Problem:
when user insert a name in the textbox, an empty dropdown is populated, but if user click on the dropdown or somewhere in the page, then list of movies are shown in the dropdown! Another issue is that if user press Enter inside the textbox (after he inserted the name), the textbox will be cleared!!
Could someone kindly let me know what is the problem with my code?
Here is the code:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault();
return false;
},
select: function (event, ui){
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
}
});
});
</script>
</form>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$html = "";
if(isset($_POST['q']) && !empty($_POST['q'])){
try{
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM cast_movie WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_ASSOC)){
$option = '<option value="' . $rows['movieName'] . '">' . $rows['movieName'] . '</option>';
$html .= $option;
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html;
exit;
}
?>
this part.
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
Action will be made on "change". . try to change it as on "keyup"
change will only be trigger if the element loses its focus.
EDIT: you should change this part ..
$("#tags").on('autocompletechange keyup', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).keyup();
I have a PHP survey form in which there is a question "Which are your favourite movies?". for this question, I put a dropdown which enable users to select movies by title or by actor. If user select "by title", a textbox (auto-complete) will be shown where he can insert a movie name. If user select "by actor", a new window will be opened containing a textbox where user should insert an actor name, then a dynamic dropdown is populated showing list of movies by that actor.
Question:
How can I get the selected movies (from textbox and also dropdown in new window) and put them in a basket like amazon shopping cart? I searched a lot, but I really could not find the solution.. I can put the selected values in a new dropdown, but my professor asked me to use the same method like amazon and put them in a basket!!
UPDATE:
Here is what I have tried:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="size=5px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<select id="selectedItems" name="selectedItems[]" multiple="multiple" style="width:200px; size:10px;">
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#selectType").change(function () {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay:5,
source: "mona.php",
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function( event, ui ) {
$(this).val( ui.item.movieName );
return false;
}
}).data("uiAutocomplete")._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + (item.posterLink?"<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />":"") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>" )
.appendTo( ul );
};
} else
if ($(this).val() == "byActor"){
window.open("target.html","_blank","height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function (d) {
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
}
$('#selectedItems').append(new Option(selected));
var title = new Option(selected);
$("#q").val("");
d.preventDefault();
});
</script>
</body>
</html>
and this is target.html:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function (event, ui){
var selectedVal = ui.item.value;
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}
});
});
</script>
</form>
</body>
</html>
Could someone kindly inform me if there is any tutorial or sample that I can use for this purpose?
All ideas are highly appreciated,
Thanks
ok for the first part I would do the following:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<style>
#basket{
padding: 10px;
border:1px solid #ccc;
}
#basket h3{
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="font-size:15px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<div id="basket">
<h3>Basket</h3>
<div id="basket_content">
</div>
</div>
JS:
var master_basket = new Array();
$(document).ready(function() {
$("#selectType").change(function() {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay: 5,
source: "mona.php",
focus: function(event, ui) {
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function(event, ui) {
$(this).val(ui.item.movieName);
return false;
}
}).data("uiAutocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + (item.posterLink ? "<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />" : "") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>")
.appendTo(ul);
};
} else
if ($(this).val() == "byActor") {
window.open("target.html", "_blank", "height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function(d) {
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
addToBasket(selected);
}
$("#q").val("");
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div>" + v + "</div>");
});
}
I'm trying to pass javascript array to php using ajax and jQuery.
I have simple page that contains a series of numbers that I've made selectable via jQuery UI (see below) When I select a group of numbers, I use array.push to add those numbers to an array called "shift". Here's the question: What's the simplest way to send this array to PHP? Will it remain an array after it comes over? I'm new to coding and would appreciate any help I can get. After a lot of research, here's what I've tried. Oh, I've managed to figure out how to submit the form to PHP, it's the jQuery UI array that i'm stuck on.
here's my main.php
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class = "container">
<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="submit" id="btn" value="send" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4.custom.js"></script>
<script src="globe.js"></script>
<ul id ="hours_zoned">
<li class="nine">9</li>
<li class="ten">10</li>
<li class="eleven">11</li>
<li class="twelve">12</li>
<li class="one">1</li>
<li class="two">2</li>
<li class="three">3</li>
<li class="four">4</li>
<li class="five">5</li>
<li class="six">6</li>
<li class="seven">7</li>
<li class="eight">8</li>
<li class="nine">9</li>
</ul>
</div>
</body>
</html>
here's my post.php
<html>
<body>
/* I'm using all of these echoes to verify that the data is coming
over. Only "shift" fails to come over */
NAME <?php echo $_POST["name"]; ?><br>
DATE <?php echo $_POST["date"]; ?><br>
TIME <?php echo $_POST["time"]; ?><br>
SCORE: <?php echo $_POST["score"]; ?><br>
SHIFT: <?php echo $_POST["shift"]; ?>
<?php
include("db.php");
$name = $_POST["name"];
$date = $_POST["date"];
$time = $_POST["time"];
$query = "INSERT INTO leaders (name, shift_date, shift_time) VALUES ('$name', '$date', '$time')";
$result = $db->query($query);
?>
</body>
</html>
here is my globe.js
var shift = []; //create array to store zoned hours
$(function() {
$( "#hours_zoned" ).selectable();
$( "#hours_zoned" ).on('click', 'li', function() {
$(this).addClass("clicked ui-selected");
$( this ).css( "background-color", "#e74c3c" );
$( this ).selectable({ disabled: true });
var floorTime = $(this).text(); // get the value of the hour that was clicked
shift.push(floorTime); // add that hour to the floorTime
});
/*$('#add').on('submit', function() {
var name = $('.leader').val(); */
$('#btn').on('submit', function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: shift,
success: function(msg) {
alert(msg);
}
});
});
return false;
});
You are only sending the key
data: shift,
according to the docs - Object must be Key/Value pairs. (https://api.jquery.com/jQuery.ajax/)
try
data: {shift: shift},
so it is now
$('#btn').on('submit', function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: {shift: shift},
success: function(msg) {
alert(msg);
}
});
return false;
});
EDIT: Your ajax function was a bit jacked up. Fixed that for you also. See new code.
Your ajax submit isn't running. Add return false; to prevent the main form from submitting. I'm thinking the easiest way to add the array would be to insert it into a hidden input immediately after being pushed in your jQuery function. Then you would just serialize the form data and send it all in your ajax function. See below:
New form:
<form action="post.php" method="post" id="add">
<input type="text" class="leader" name="name" placeholder="Leader">
<input type="text" class="date" name="date" placeholder="date">
<input type="text" class="time" name="time" placeholder="time">
<input type="text" class="score" name="score" placeholder="score">
<input type="hidden" class="shift" name="shift">
<input type="submit" id="btn" value="send" />
</form>
New function:
var shift = []; //create array to store zoned hours
$(function() {
$( "#hours_zoned" ).selectable();
$( "#hours_zoned" ).on('click', 'li', function() {
$(this).addClass("clicked ui-selected");
$( this ).css( "background-color", "#e74c3c" );
$( this ).selectable({ disabled: true });
var floorTime = $(this).text(); // get the value of the hour that was clicked
shift.push(floorTime); // add that hour to the floorTime
$("#add .shift").val(shift); // add shift array to hidden input in form
});
/*$('#add').on('submit', function() {
var name = $('.leader').val(); */
$('#add').submit(function() {
$.ajax({
type: 'POST',
url: 'post.php',
data: $("#add").serialize(),
success: function(msg) {
alert(msg);
}
});
return false; // you need this to prevent the other form submission
});
return false;
});
Untested, but that should get you going in the right direction.
Just wanna add to the answers given here..
You also need to check if the items selected are in array already (prevent duplicate).. so to do that you can do it like this
*code is taken from Matt answer
if($.inArray(floorTime, shift) === -1) {
shift.push(floorTime);
$("#add .shift").val(shift);
}
Try parse_str().
$array = parse_str( $_POST['data'] );
I found this script from (http://w3lessons.info/2012/01/03/facebook-like-fetch-url-data-using-php-curl-jquery-and-ajax/) Problem is that i want to do in loop with multiple urls.
<link rel="stylesheet" type="text/css" href="style.css" />
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style-ie.css" />
<![endif]-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="js/jquery.livequery.js"></script>
<script type="text/javascript" src="js/jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// delete event
$('#attach').livequery("click", function(){
if(!isValidURL($('#url').val()))
{
alert('Please enter a valid url.');
return false;
}
else
{
$('#load').show();
$.post("curl_fetch.php?url="+$('#url').val(), {
}, function(response){
$('#loader').html($(response).fadeIn('slow'));
$('.images img').hide();
$('#load').hide();
$('img#1').fadeIn();
$('#cur_image').val(1);
});
}
});
// next image
$('#next').livequery("click", function(){
var firstimage = $('#cur_image').val();
$('#cur_image').val(1);
$('img#'+firstimage).hide();
if(firstimage <= $('#total_images').val())
{
firstimage = parseInt(firstimage)+parseInt(1);
$('#cur_image').val(firstimage);
$('img#'+firstimage).show();
}
});
// prev image
$('#prev').livequery("click", function(){
var firstimage = $('#cur_image').val();
$('img#'+firstimage).hide();
if(firstimage>0)
{
firstimage = parseInt(firstimage)-parseInt(1);
$('#cur_image').val(firstimage);
$('img#'+firstimage).show();
}
});
// watermark input fields
jQuery(function($){
$("#url").Watermark("http://");
});
jQuery(function($){
$("#url").Watermark("watermark","#369");
});
function UseData(){
$.Watermark.HideAll();
$.Watermark.ShowAll();
}
});
function isValidURL(url){
var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
}
</script>
<input type="hidden" name="cur_image" id="cur_image" />
<div class="wrap" align="center">
<div class="box" align="left">
<input type="text" name="url" size="64" id="url" />
<input type="button" name="attach" value="Attach" id="attach" />
<div id="loader">
<div align="center" id="load" style="display:none"><img src="load.gif" /></div>
</div>
</div></div>
Is there any i can do loop and load the different different url same time? Please help me!
In JavaScript who can't create thread.
So you can't fetch all those "different url at same time".
But you can "almost" achive the same thing using the event loop to request them quickly one by one without waiting for the HTTP response. Who end up being very quick !
Let's say for exemple you want to featch 3 url:
www.mysite.com/myurl1
www.mysite.com/myurl2
www.mysite.com/myurl3
You can write something like that using jQuery:
$.get('http://www.mysite.com/myurl1', function(data) {
alert('html for site 1:' +data);
});
$.get('http://www.mysite.com/myurl2', function(data) {
alert('html for site 2:' +data);
});
$.get('http://www.mysite.com/myurl3', function(data) {
alert('html for site 3:' +data);
});
It will request the 3 page "almost" in the same time.
The first HTTP request will call the "alert('html for site x:...');"
but you don't know witch one will arrived first.
Anyway you probably need something more flexible.
Let's say you want to request 50,000 pages requesting them in "almost" the same time using 200 simultaneous request.
You can write something like that in JavaScript:
function getNextUrl(){
urlIndex ++;
if(urlIndex >= stopAtIndex){
//nothing to do anymore in the event loop
return;
}
$.get('http://www.mysite.com/myurl'+urlIndex, function(data) {
// html receivend here
getNextUrl();
});
}
/* program start here */
int urlIndex = 0;
int stopAtIndex = 50000;
int simultaneousRequest = 200;
for( var i = 0; i < simultaneousRequest; i++ ) {
getNextUrl();
}