Mix jQuery, RSS and PHP withoutout refreshing. - php

I'm currently trying to get my head around the jQuery language. I'm trying to make sort of a RSS validator. The idea is that the user types in RSS URL and then the jQuery checks if the RSS has an title. If it does it sends it to a PHP file which checks if it already exists in the database and then sends back the results to the original page. All without refreshing.
I can make it work so the jQuery sends the information to the php which checks if it exists and then sends the result back without refreshing.
The problem comes up when I try to implement the RSS jQuery function. I have tried to simply put it in the other jQuery but it just refreshes.
The form:
<form id="lets_add" action="" method="get">
<input id="addurl" type="text" name="URL" value="URL"onfocus="searchinput();" onblur="searchinput2();" />
The jQuery code to pass it to the php, without the title:
$(function() {
$("#lets_add").bind('submit', function(){
var value = $('#addurl').val();
$.post('db_add.php',{value:value}, function(data){
$("#val_add").html(data);
});
return false;
});
});
The php:
mysql_select_db ("members");
$term = mysql_real_escape_string(#$_POST['value']);
$title = mysql_real_escpae_string(#$_POST['title']);
$ost = "SELECT * FROM linkdb WHERE URL = '$term' OR name = '$title'";
if(mysql_num_rows(mysql_query($ost))){
echo "The RSS exists in the database.";
}
else{
echo "The RSS i validated, with title: " . $title;
}
mysql_close($con);
And the RSS title:
$.get('proxy.php?url='+$('#addurl').val(), function(d) {
//find each 'item' in the file and parse it
$(d).find('channel').each(function() {
var $channel = $(this);
var title = $channel.find('title:first').text();
Perhaps needless to say, there is a div with the id="val_add" which catches the echo..

Instead of finding the title with jQuery I used cUrl to find it within the php page..

Related

How to send the values of the query variables into php variable for inserting into database? [duplicate]

I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.

jQuery AJAX request not firing when posting to a php script.

I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".

Autocomplete not working using dynamic html

Iam adding html for input tag dynamically through enterPerson() and then calling onkeyup=changeOnType(this) which on echoing $results in autoInvit.php should display autocomplete, but WHY does my autocomlete code does not work,infact data shows if I alert it. can any one please help me out ?
Thank you in advance :)
header files for jquery and autocomplete:
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="//code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
autocomplete in "main.php" :
<script>
function changeOnType(x){
$.post(
"autoInvit.php",
{
vals: $(x).val()
},
function(data){
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
//alert(data);
}
);
}
</script>
here's the dynamic html's php code in "invities.php":
<?php
echo '<input class="e" type="email" id="email" onkeyup="changeOnType(this)" autocomplete="on" role="textbox" aria-autocomplete="list" aria-haspopup="true" />';
?>
Here's my php file "autoInvit.php" which echos the result:
<?php
include("includes/connection.php");
$value = strip_tags($_POST['vals']);
$req = "SELECT email as name "
."FROM members "
."WHERE email LIKE '".$value."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = $row['name'];
}
echo json_encode($results);
?>
Please help
There's no need to make the post request. Edit: There's no need to call a separate function or attach a listener to the input, just register the autocomplete plugin. This will need to be called once the DOM is ready, so you will need to wrap it in a ready function. This should be all the javascript you need:
$(function() {
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
});
What the user has typed will be passed with the request as the parameter term
From the jQuery docs for autocomplete:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
Also, you'll want to be careful when passing content from the user directly to the DB. You can open yourself to SQL injection.

How to pass data from input form to js on another page

I have a page where a user enters an address and clicks search. The user should be taken to the next page which should contain a google map with the address the user specified. How should I pass the address from the form on page 1, to js on page 2 where I can manipulate it with the google maps api? I'm using codeigniter btw.
EDIT:
My ideal solution would be to use flash data or pass the address in the url the codeigniter way. My problem is i'm not sure how I would retrieve the data if I used either of these methods.
In the CodeIgniter view for page 1:
<form method="POST" action="getMap">
<input type="text" name="address" value="" />
<input type="submit" value="Map It!" />
</form>
In the CodeIgniter view loaded by getMap() method of the controller (in other words, in page 2):
<script>
address = "<?php echo htmlspecialchars($this->input->post['address']); ?>";
// create the map with the address here
</script>
You'll want to take care to do some validation on the user input.
Use url variables to accomplish this. An example might look like this:
http://www.testurl.com/mappage.html?address=someaddress&city=somecity&state=ca&zip=12345
You can pick up the values of these url variables in javascript and pass it to the google map.
Do you want the user to be able to save the url?
If you don't, just use POST in the input field and retrieve the data in the second page this way (inside the javascript):
var address = '<?=$this->input->post('address')?>'
Otherwise:
In javascript, in the first page, prevent the default action on form submit and instead redirect the user to [url of the second page]/[stuff written in the form] (I can give you a jquery example if you want);
In the second page controller (let's pretend the function is called get_map and it is in the maps controller you get the data in this way
function get_map($address = null)
Now you have the input address. Pass it to the view that should contain the map.
Why don't you simply print the POSTed information via PHP on the destination page using Javascript literals syntax?
As an example, if your form POSTs the following (both GET or POST query):
firstname=aaron&lastname=pink
you can print in a destination PHP page:
<html>
<head>
<script type="text/javascript">
var fname = "<?php echo addslashes($_POST['firstname']); ?>";
var lname = "<?php echo addslashes($_POST['lastname']); ?>";
</script>
</head>
<body>
...
<button onclick="alert(fname);">Say First Name!</button>
</body>
</html>
Then, you can simply use fname and lname Javascript vars as you wish, just as my sample button does on click!
I hope it was helpful, even if very simple :)
If you are using jquery, you can use the $.cookie plugin to transfer informations between PHP and Javascript.
or 2. Send data from 1. page per $_GET or $_POST and catch the data in 2. page
<script>
var myData = '<?php=htmlspecialchars($_POST['data_from_page1']);?>';
</script>
#Catfish you're getting all confused. The objective of making your urls "pretty" and having them resemble paths / files rather than query strings is for SEO & user friendliness. You shouldn't really be including any form input in as a "pretty" url. Either send your address data via the $_POSTS global or send it as a query string. CI uses the [QSA] flag in its mod_rewrite definitions in the htaccess file so you're totally fine to stick on a (IMO) semantically correct query string on the end.
Anyway, to the code.
On form.php:
<form action="map.php" method="get">
<input type="text" name="addr" />
</form>
On map.php:
<?php
$addr = $this->input->get('addr');
// or $addr = $_GET['addr'];
echo $addr;
?>
You can use sessionStorage on modern browsers to stock your datas between pages inside the same browsing session.
For older browser you can use an hacky solution that allow you to stock datas inside the window.name
if( typeof sessionStorage !== 'undefined' ){
myStorage = sessionStorage;
}else{
myStorage = {
setItem:function(key,val){
this.removeItem(key);
window.top.name+=(window.top.name.length?'&':'')+escape(key)+'='+escape(val);
}
,getItem:function(key){
var r = window.top.name.match(new RegExp('(^|&)'+escape(key)+'=([^&=]*)($|&)'));
return r?unescape(r[2]):null;
}
,removeItem:function(key){
window.top.name = window.top.name.replace(new RegExp('(^|&)'+escape(key)+'=([^=&]*)(?=$|&)'),'');
}
};
}
Now you can use myStorage.setItem('key',value) with each of the form fields you want to keep and retrieve them on the next page with myStorage.getItem('key')
It's not more complicated than using cookies, and have the benefits to not transfer the cookie datas in each request header.
Hope this help..
Why not do it entirely in JavaScript, using the Google Maps API ?
Let's say that your Map is initialized with the variable var Map and the Geocoder in the var Geocoder and that you have an <form id="searchForm">Address:<input /> <br /> <input type="submit" /></form>.
I'm also assuming you have jQuery loaded, so:
<script type="text/javascript">
$('#searchForm').submit( function(e) {
e.preventDefault();
var searchString = $(this).find('input:first').val(); // get the address
Geocoder.geocode( { 'address': searchString}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Map.setCenter(results[0].geometry.location);
} else {
alert("Geocode error: " + status + "\n" + "Try another address");
}
});
});
</script>
Demo here: http://jsfiddle.net/toxik/Xjy3S/embedded/result/
Codeigniter sessions would be the easiest to work with.
Once you get the address submitted, set some userdata like so.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mycontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//do something from post
$this->session->set_userdata('street', $this->input->post('street'));
$this->session->set_userdata('city', $this->input->post('city'));
$this->session->set_userdata('state', $this->input->post('state'));
$this->session->set_userdata('zip', $this->input->post('zip'));
//then redirect to the next page
redirect('mycontroller/map');
}
else
{
//load the form
$this->load->view('address_form');
}
}
function map()
{
$data = array(
"street" => $this->session->userdata('street'),
"city" => $this->session->userdata('city'),
"state" => $this->session->userdata('state'),
"zip" => $this->session->userdata('zip')
);
$this->load->view('map' $data);
}
}
Set the values in a hidden input. Just have javascript grab the value of that inputs ID...
check this
// JavaScript function function abc(pram1, pram2) { alert(pram1 + pram2); } // end of JS function
now call this function on your search form. pass all parameters you want to move other page
like
<a name="search" href="javascript:void(0)" onclick="abc('param1','param2')> search </a>

translate rss-feed that was grabbed by cURL

my most trusted programmers and thank for all the help!
I grab rss-feed by jquery-ajax using php curl. It's loading very nicely directly on the page. However, I would like to translate the text, that is now html, title within h2 and text within p, wrapped by a div-container.
Google's api-script for translation doesn't seem to run after the content was put into the div. Really nothing happens. I tried both putting the script in the ajax-url-file and the file that the content is displayed on.
I used .live(), but no result.
Any idea?
Thanks!
--
In one of the methods I create a table i mysql and put in title, link and text. After that I echo the table.
$query3 = mysql_query("SELECT * FROM temp_rss_$id") or die("$error_msg");
while ($row3 = mysql_fetch_array($query3)) {
$title = htmlentities($row3['title']);
$text = htmlentities($row3['text']);
$link = $row3['link'];
echo "
$titel
$text
";
}
The title is within in a h2 and an anchor, and the text is within a p.
Using simple jquery, this method without ajax, to grab this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file);
});
Works like a charm. Then there's the google-api-script:
function initialize() {
var text = document.getElementById('media').innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en", function(result) {
var translated = document.getElementById("media");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
It doesn't load the google-script. What can be done? Of course it does work if I put the text directly on the page, without loading another file. Using ajax and append(result) instead of .load doesn't make a difference. Any idea?
Thanks!
You can call that function after the .load() runs, as it's callback, like this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file, initialize);
});
This will call the initialize function once the .load() has completed and the new content in the #media element is there and ready to translate.

Categories