Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.
Related
I'm trying to execute a PHP script that updates a MySQL DB on click of an image. I'm using a snippet I found online to do so:
function execute(filename,var1,var2)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
//Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
//Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support AJAX!");
}
var url = filename+"?";
var params = "id="+var1+"&complete="+var2;
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
//Below line will fill a DIV with ID 'response'
//with the reply from the server. You can use this to troubleshoot
//document.getElementById('response').innerHTML=xmlhttp.responseText;
xmlhttp.close;
}
}
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
With this link: <a href="javascript:void(0);" onclick="execute(games_do.php,<?=$game['appid']?>,<?=$complete?>)" > </a>
And games_do.php contains:
$appid = $_GET['id'];
$complete = $_GET['complete'];
mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
However, nothing seems to happen on click. Any suggestions would be greatly appreciated! :)
The parameter values for the execute function in the <a> tag should be enclosed within quotes as the function expects a string as the value.
In addition, the point mentioned in D. Schalla's answer should also be considered.
There are several prolems with your code:
First of all, you should always escape or type-cast your code, because you have SQL Injections made possible in your code:
$appid = $_GET['id'];
$complete = $_GET['complete'];
to:
$appid = intval($_GET['id']);
$complete = mysql_real_escape_string($_GET['complete']);
Also I would change the mySQL Driver from mysql_ to PDO later, since it might be that it will be unsupported in a later version of PHP.
But however, to find the problem in your code I would debug the request using Firebug (an Firefox Addon) or the Chrome Developer Console. Check what the Request Returns, it might be an mySQL Error relating to your Database Design.
To do so, check in Chrome under the Tab Network in the Console the "Answer" of the AJAX Request, when there is an error, it will be displayed there.
I would also switch to jQuery if you plan to work more heavy with AJAX, since it handles the fallback solutions for some browsers and offers an more easy integration, you can find a doc relation this there:
http://api.jquery.com/jQuery.ajax/
Change mysql_query("UPDATE ownedgames SET complete='".$complete."' WHERE steamid='".$steamid."' AND appid='".$appid."'") or die(mysql_error());
to this:
mysql_query("UPDATE ownedgames SET complete='$complete' WHERE steamid='$steamid' AND appid='$appid'") or die(mysql_error());
Further, you can make your ajax call easier with jQuery, if you're not using it, I strongly suggest you do. It would make it as this:
function execute(filename,var1,var2){
$.ajax({
type: "POST",
url: filename,
data: {id:var1, complete: var2}
}).done(function( result ) {
//do whatever you want to
});
}
as for your link, you should try this:
<?php
$id=$game['appid'];
echo('<a onclick=execute("games_do.php","'.$id.'","'.$complete.'")>Click Here </a>');
?>
I'm working on my first AJAX script with some PHP pages - it's my first time with AJAX and I've finally got the script to work. I'm also a bit of a Javascript newbie too.
I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. We've now changed the "Select" link to load via AJAX so the search results page doesn't refresh.
To finish the AJAX changes I now need to pass a unique ID for each of the table cells that has the AJAX link to the script. I'm using PHP to generate a unique ID for each table cell by using the $bookID variable as follows:
<td class="hidden-narrow" id="<?php echo 'selectRecord'.$bookID; ?>">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo 'Select';
}
?>
</td>
I now need to update my script to work with the unique ID's - to get it working I hardcoded it to an ID named "selectRecord" using an example script that I found. Here's my script:
function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false; // Do not follow hyperlink
I gather I need to change this line:
document.getElementById("selectRecord").innerHTML="Selected";
but not sure of the syntax to handle unique ID's for each table row cell.
You can pass the id to the getElementById function:
document.getElementById("selectRecord" + id).innerHTML="Selected";
Have you tried
document.getElementById(id).innerHTML="Selected";
? id should get enclosed by the readystate function and keep its value.
I have a very simple form.I want to insert the form data in mysql database.using ajax.
I need to pick data from form and send them as xml to the server.
the form is as :
<form>
Name:<input type="text" id=name/>
Contact<input type="text" id=contact/>
</form>
And i am picking the data from my form using js as :
function GetData(form)
{
var name=document.getelementbyid('name');
vat contact=document.getelementbyid('contact');
}
function Ajax
{
" Here i want to send the form datas as an xml to the server"
}
Can any one help me how to do this .And also how to receive the the request from server as xml and insert to database.
Just give me the proper way.Not Query string or json or jquery.I want to use xml using ajax
Thanks,
function GetData(form)
{
var name=document.getelementbyid('name');
var contact=document.getelementbyid('contact');
Ajax(name,contact);
}
function Ajax(name,contact)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
}
}
//var datas='?name='+name+'&contact='+contact;
var xmlval='<name>'+name+'</name><contact>'+contact+'</contact>';
var datas='?xmlvalue='+xmlval;
xmlhttp.open("GET",'phpfile.php'+datas,true);
xmlhttp.send();
}
Important question: Why do you need XML to submit?
Also, to use XML, look up SimpleXML, and to save to database, there are a lot tutorials.
Update: if you meant the response as XML? That's just like the same as in JS. And to use it in JS, look at this. However, in that case, uncomment the commented line and comment the next 2.
I'm learning Ajax by failure and have hit a wall:
I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.
I have a function that is called when the user clicks the 'save' button. The function is as follows:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
My question is:
What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?
furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?
Thanks in advance.
If your array has more then 1 dimension or is an associative array you should use JSON.
Json turns a complete array structure into a string.
This string can easily send to your php application and turned back into a php array.
More information on json: http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
In php you can decode the string with json_decode:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&' to the query string each time.
furthermore, should I try using JSON?
You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.
And if so, how could I send a JSON object via ajax?
There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).
I found this question useful for Javascript enthusiasts.
Sending a javascript Object, be it js array or js object, you must stringify the setup before putting it to the server for decode & processing.
Stringifying a js object:
Based on your function:
case of Javascript Array object
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
case of Javascript Object object
let my_obj = {
name: "Daniel",
age: 23,
location: "Nigeria"
}
my_obj = JSON.stringify(my_obj);
Ones on point you can push this to the server, as per use case, u're working with AJAX GET method in sending your stringified object to the server.
Here is the full code:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById('message').innerHTML = this.responseText;
// if your returned response is in json, please, do ensure to parse the response before displaying
// like this JSON.parse(this.responseText)
}
}
let my_array = ["select1", "select2", "..."];
my_array = JSON.stringify(my_array);
var url = "create_amenities.php?my_json=" + my_array;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here are what i noticed out of your codes:
You don't need to call xmlhttp inside of xmlhttp object again, all you need is the this
I included the my_json parameter that holds the array object you are sending to the server.
Now, here in the server, you will need to catch the object and convert it to php readable object.
$my_json = $_GET['my_json'];
$my_json = json_decode($my_json);
Now, you can do whatever you wish it, because it has now become a full php array.
Example to pick the first array option:
$first = $my_json[0];
echo json_encode($first) // hahaha, you echoed it for AJAX to display
// i used to json_encode() to convert from php object to a js readable object
First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.
The best approach to your actual problem would be to submit your array as cgi parameters.
If the checkboxes are in a form, you need to do very little - simply submit the form,
<form><input type=checkbox ...><input type=checkbox ...>
$.post("test.php", $("#testform").serialize());
See http://api.jquery.com/jQuery.post/ for more details on how to do that.
Your list will turn up as an array in PHP.
Or to augment your own example with something very simple, do this:
url = url + '?checkboxes=' + checkboxes.join(',');
Now just split it inside PHP and you've got it back!
I am not aware of the proper terminology or jargon with programming, so forgive me if this question is unclear. To make if more clear here is the code I have written so far. I will explain the problem in more detail after the code:
I use this code to retrieve data from Facebook:
function rsvpEvent() {
FB.api('/me/events/', function(response) {
for (var i=0; i<=2; i++) {
eventname=response.data[i].name;
eventid=response.data[i].id;
eventstatus=response.data[i].rsvp_status;
eventInfo(eventname,eventid,eventstatus);
strEvent=strEvent + "You are " +
eventstatus + " " + eventname + ", EID: " + eventid + "<br/>";
}
document.getElementById('rsvpEvent').style.display = "block";
document.getElementById('rsvpEvent').innerHTML = strEvent;
});
}
Request to PHP file (containing mySQL calls):
function eventInfo(eventname,eventid,eventstatus) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("eventInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","event_info.php?eventName=" + eventname + "&eid=" + eventid +
"&rsvp_status=" + eventstatus,true);
xmlhttp.send();
}
So, the issue is that I need to store individual event names, ids and statuses and the code as it stands now. I can output them to a page individually, but cannot send them to the PHP file individually. How do I do this (presuming it is possible)?
Use jQuery for your ajax call to your php script.
$.post('/somefile.php', myJSobjectOrArr, function(data) {
// return something from your script to say it succeeded or not...
console.log(data);
}
In your php script just check your $_POST variable and serialize() or json_encode() it and pop it into your database.
To get your data back just unserialize() or json_decode() it.
You can join eventnames with comma(,) ,and when reading those data to save into database you can delimit comma(,), means remove commas from that and store each event name to database..
This is what i understand according to your problem..