I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.
Related
I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.
I have the following query:
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
This will return a number for any new mailbox messages, I have found an ajax code for checking if there is a change.
Code:
var previousValue = null;
function checkForChange() {
$.ajax({
url: '',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
But I really need to figure out how to update the query without refreshing the entire page? I figured maybe something with ajax can help but I am totally new to ajax and I don't have an no idea where to start.
Update: ok so I wrote a php script for the queries but not sure how to get ajax script to use my "emails" var.
here is the script.
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die();
}
include("..\internals\config.php");
$host = DB_HOST;
$user = DB_USER;
$password = DB_PASS;
$dbname = DB_NAME;
$prefix = DB_TBL_PREFIX;
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db($dbname, $cxn);
function get_user_id()
{
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $cxn->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $cxn->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $cxn->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
$profile_id = get_user_id();
public static function newMessages( $profile_id )
{
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
}
// check config for filter condition
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
}
mysql_close($cxn);
$emails = newMessages();
?>
Ajax is correct - with Ajax you can send a request to the webserver which will execute your query and receive a request.
Its like visiting a page with the browser except that it happens in the background and not reloading the browsertab/page.
Lets say this is your file query.php and you can access it via my-domain.tld/query.php
query.php:
//First make this file only executeable for AJAX-Requests but no regular visit via browser:
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die(); //User tried to enter query.php with a browser or similar...
}
//call function where query is stored or put your query here and save result
//Its important to echo what you want to be returned in the ajax-request.
echo self::$newMessageCountCache[$profile_id];
die(); //Best is die after last echo to make sure there are no extra outputs!
Now in your template or atleast where your HTML code is:
function checkForChange() {
$.ajax({
url: 'my-domain.tld/query.php', //See, here is the URL to your file on server
data: {}, //You need this only if you want to mpass any variables to your script. On PHP Server-side this data are available via $_POST array!
success: function(data) { //data contains all echo'ed content from query.php
$(".mailbox_messages").html(data); //The best is make your container to be updated to a class or ID to access. Its content can be overridden with .html() function. Simply echo all contents in query.php that you want to be displayed in your element and override the content with .html(data);
}
});
}
Now you just need to call checkForChange() when something special happens like a button click for example:
<input type="button" id="refresh-mailbox" value="Refresh my Mailbox" />
<script type="text/javascript">
$("#refresh-mailbox").on("click", function() {
checkForChange(); //Execute your function on button click and done!
});
</script>
I hope this helps. :)
I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];
I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.
I have a php file which contains the following code:
function render() {
//fetches all the data from input.
$date = date("Y-m-d H:i:s");
$con = mysql_connect("127.0.0.1","root","");
$database = mysql_select_db("guestbook");
$name = $_POST['name'];
$email = $_POST['email'];
$post = $_POST['post'];
$sql = "INSERT INTO gast(name, email, post, date) VALUES('$name','$email','$post','$date')";
$input = mysql_query($sql);
mysql_close($con);
}
With javascript, I'd like to retrieve those variables, something like this:
document.getElementById('button').onclick = clicked;
function clicked() {
var name = document.render.name.value;
var post = document.render.post.value;
var email = document.render.email.value;
}
I have included that javascript code in my body, but it doesn't work. How do I get the value?
Use AJAX. With jQuery you can get any data from the server very easy.
$.get('test.php', function(data) {
alert(data);
});
You can't really, unless the js and php code is on the same page, then you could do
var namn = "<?php echo $name; ?>";
but unless the php is passing the variables to the file that your js is in, you can't really do anything.