I have a function on a website where I have a img reference leading to a php page
<img src="selectimage.php?uid=21312412">
which I need to return an image and update a database file
<?php
$servername = "localhost";
$username = "webz";
$password = "BLAH";
$dbname = "contactlist";
$readid = $_GET["uid"];
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "UPDATE emails SET `read`='1' WHERE `id`='" .$readid. "'";
if ($conn->query($sql) === TRUE) {
echo "<img src='logo11w.png'>";
}
$conn->close();
?>
I figured this would not work as I am referencing a php page in which is referencing the HTML tag
While this is updating my database it is not displaying the image.
how do I make this php file send the image logo11w.png to that img tag
Further note : include or other methods of including this code on the page loading are out of the question because this procedure may be called from a off-server source.
Store user id in one hidden field
You can use ajax for get respone back from php page after updating value in database
<input type="hidden" id="userid" value="user_id_value">
<input type="button" id="getimage" value="GET IMAGE">
<div id="u_img"></div>
$(document).ready(function(){
$('#getimage').click(function() {
var uid = $('#userid').val();
var datastring = "uid="+uid;
$.ajax({
type: "POST",
url: "php_page.php",
data: datastring,
cache: false,
success: function(result) {
$('#u_img').append(result);
}
});
});
});
The most effective method for what I am trying to do turns out to be:
...
if ($conn->query($sql) === TRUE) {
header('Content-Type: image/jpeg');
echo file_get_contents('https://www.google.com/images/srpr/logo11w.png');
} else {
echo "Error updating record: " . $conn->error;
}
...
Related
I am doing email verification on my website. When user submits the form, it starts ajax post request, which posts the email to PHP which compares it with a datebase.
Than still in the form verification process, I have ajax GET request, which should return from the same PHP file whether the email has already been used.
But. Everything works fine when I proceed to the PHP, but GET request is always blank. URL of POST request is EmailDuplication.php but URL of GET is EmailDuplication?_=somerandomnumbers. Might that be the problem?
I am not experienced in this, will be glad for any help.
Here are the codes
JavaScript
function EmailSendForDupe()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'post',
async: false,
cache: false,
timeout: 30000,
data: {email: email.toString},
success: function (){
window.alert("email sent");
}
});
}
function EmailDuplication()
{
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
async: false,
cache: false,
timeout: 30000,
success: function (callback){
console.log(callback.length);
console.log(callback);
if (callback.length !== 0){
window.alert("Email is already in use");
return false;
}
else {
window.alert("Email valid");
return true;
}
}
});
}
PHP
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}
else {
echo "User Email is already in use.";
}
}
?>
First, I would advise cleaning up your PHP and making sure it is not vulnerable to SQL Injection.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
$returnData = new array();
$conn = mysqli_connect($servername, $username,$password,$dbname);
if (mysqli_connect_errno()) {
$returnData['SQL Error'] = "Connect failed: %s\n", mysqli_connect_error();
header('Content-Type: application/json');
echo json_encode($returnData);
exit();
}
if(isset($_POST['email'])){
// POST
$email = mysqli_real_escape_string($conn, $_POST['email']);
$resultData["AHOJ"] = true;
$Emailquery = "SELECT * FROM Members WHERE email='$email' LIMIT 1;";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
$resultData['inUse'] = false;
$resultData['email'] = $_POST['email'];
} else {
$resultData['inUse'] = true;
}
} else {
// GET
$resultData["AHOJ"] = false;
$resultData['inUse'] = true;
}
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($returnData);
die();
?>
This will return JSON details back to your jQuery script and can be more helpful than plain text.
I also use mysqli_real_escape_string() to help escape any potential injection attempts. I would advise switching to Prepared statements: http://php.net/manual/en/mysqli-stmt.prepare.php
In your JavaScript, you will want to make a few changes too.
function EmailSendForDupe(email){
$.ajax({
url: '/files/EmailDuplication.php',
type: 'post',
cache: false,
timeout: 30000,
data: {
email: email.toString()
},
dataType: "json",
success: function (json){
console.log(json);
if(json.inUse == false){
alert("Email Sent to " + json.email);
} else {
alert("There may have been an error: " + json.error);
}
}
});
}
function EmailDuplication(email){
$.ajax({ url: '/files/EmailDuplication.php',
type: 'get',
data: {
email: email.toString()
},
dataType: "json",
cache: false,
timeout: 30000,
success: function (json){
console.log(json);
if (json.inUse){
window.alert("Email is already in use");
} else {
window.alert("Email valid");
}
}
});
}
Hope this helps.
Generally you want to use async: true.
Also, you do not want to allow the form submit to actually Happen, as that blows away your whole page (reloads the entire thing, if not navigates to somewhere else entirely). So in fact the blank get you could be seeing could be the form submit blowing away your page.
If you are sending ajax requests, the trigger for those simply needs to be a button with a click handler, not an actual submit (unless in that submit input you do something like "onclick='doMyAjax();return false;'" so that the submit action does not actually occur).
If you are actually uploading a file, which for the purpose you appear to be showing here dear goodness please don't let the client drive that functionality via files on their system, the upload post needs a target to post To, so it does not hit your page. For that, the classic embedding of an iframe is still the way to go. Ugh.
posting to an iframe
I have no idea why Two requests need to be sent to do the job. It should probably be just one POST (assuming the ultimate outcome here is you want to send an email if it is a valid email), and the server checks the email and then does the send if it is valid.
And do not use GET versus POST to distinguish what the server should do (such as verifying an email versus sending one) - the Request itself or the Url, for example include "action=verifyEmail" in your form data being passed up, to tell the server what to do rather than it assuming just because it's a POST.
Hopefully some of this is helpful.
you are missing to handle GET Request Data.if some try to using get URL then your code don't have any condition to handle it. check modified code.
<?php
$servername = "*";
$username="*";
$password="*";
$dbname="*";
try{
$conn = mysqli_connect($servername, $username,$password,$dbname);
}catch(MySQLi_Sql_Exception $ex){
echo("error in connection");
}
if(isset($_POST)){
$email = $_POST['email'];
echo "AHOJ";
$Emailquery = "SELECT * FROM Members WHERE email='$email' ";
$Emailresult = mysqli_query($conn,$Emailquery);
$Emailcount = mysqli_num_rows($Emailresult);
if($Emailcount == 0) {
}else {
echo "User Email is already in use.";
}
}else{
echo " Get Method Data";
}
?>
Please try it and give your feedback.
I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});
i try to displaying value of my table in android, and i put my code into hosting,
but when i try to running my app, my link doesn't work,
and i tried to create new link that displays the same output , and its works fine,
this is my code to encode json
send_data.php
<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con, $query);
while ($r = mysqli_fetch_array($result)) {
extract($r);
$rows[] = array(
"id"=>$id,
"ask"=>$ask
);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>
did I'm doing something wrong??
because I want to set the output from the database
This is just a suggestion without seeing your AJAX code:
Add this code to the top of your PHP code:
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
And use this code as an example of AJAX:
var poutput = $('.itemsHolder');
$.ajax({
url: 'https://yourdomain.com/php/YOUR-PAGE.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(pi,item){
str = item.id;
var products = '<div id="'+item.id+'">'+
'</div>';
poutput.append(products);
});
},
error: function(){
//alert('There was an error loading the data.');
}
});
Don't forget to add an element with the class name of itemsHolder to your page.
Pretty new to php/mysql and jquery, and I'm having trouble getting my form data to upload to my mysql db. I've tried a few different approaches and done my research, but none of the suggestions I've found online are working for me, which is why I'm posting here. So here's my most recent failed approach:
in my index file:
<head>
...
<script type="text/javascript">
$(document).ready(function() {
// Announcement form AJAX submit
$('#announcementForm').submit(function() {
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.error) {
$('#error').css('display', 'block');
} else {
$('#note').show();
$('#error').hide();
$('#fields').hide();
}
}
});
return false;
});
});
</script>
</head>
<body>
...
<form class="dl_form" id="announcementForm" method="post">
<dl>
<dt>Announcement</dt>
<dd><textarea id="Announcement" sytle="width: 300px; height: 150px;" name="Announcement"></textarea></dd>
</dl>
<dl>
<dt>Announcement Type:</dt>
<dd><input type="radio" name="Type" value="schedule">Scheduling</input></dd>
<dd><input type="radio" name="Type" value="general">General</input></dd>
</dl>
<dl>
<dt></dt>
<dd><input type="submit" value="submit" /></dd>
</dl>
</form>
<div id="note">
<p>Announcement posted successfully!"</p>
</div>
<div id="error">You haven't completed all of the required fields</div>
And then in my ajax.php file I have (some lines have been replaced with "######" for security reasons):
<?php
//database credentials
$server = '######';
$username = '######';
$password = '######';
$database = '######';
$connect = mysql_connect($server, $username, $password ) or die(mysql_error.'error connecting to db');
//select database
mysql_select_db($database, $connect) or die(mysql_error.'error selecting db');
//$typeValue = $('input:radio[name=Type]:checked').val());
if (!empty($_POST)){
$Announcement = $_POST['Announcement'];
$Type = $_POST['Type'];
if (!empty($Announcement) && !empty($Type) )
{
//insert data into db
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
}else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fields!"
));
exit;
}
}
?>
Any help you guys can provide would be much appreciated.
Thanks
UPDATE IN RESPONSE TO Jay Blanchard:
I just ran the console in my browser. The only error I'm getting is:
SCRIPT1004: Expected ';'
in reference to the first line of my JS:
$function() {
...
UPDATE 2:
Just updated my code to reflect my most recent changes...before I could at least trigger the submit click even and the fields would empty, indicating that at least something was happening. With my new round of changes however, not even that triggers, so I'm still pretty stuck
In your php you've made a mistake with your echo statement its not jason_encode instead its json_encode.
Additionally
Also you Should remove AnnouncementID from your query if in database it is auto increment, because db will warn you for incorrect integer value for column AnnouncementID.
EDIT: In your php part in statement
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement"')") or die(mysql_error());
You are forgetting a concatenation operator . after '".$Announcement which should be
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
and in your jquery instead of
$function() {
use
$(document).ready(function(){
I have an HTML form(2 list-boxes and a check-box) which I want to use for filtering results on the page.
How can I make it so when I press the Submit button(.onclick(function(){})) it would execute a jQuery AJAX call to a PHP script on my local server that will, firstly, check if anything was selected in the list-boxes and if the check-box was checked and then based on that build a SQL statement to query my database and retrieve the result as JSON.
How would you do it, theoretically. I already have the PHP script to simply grab everything from my table and save it as JSON:
<?php
// databse connection info
require("dbinfo.inc.php");
// try to open a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// grab data about every campus and which instituion they belong to
$query = 'select statement to grab all the data from a table';
$result = mysql_query($query);
// check if $results has anything
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// time to start generating our huge XML
while ($row = #mysql_fetch_assoc($result)){
$finalarray[] = $row;
$main_arr['products'] = $finalarray;
}
// close connection to the database
mysql_close($connection);
// echo, save and write the file
// print json_encode($main_arr);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($main_arr));
fclose($fp);
?>
First send the data from the form with ajax:
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : 'myPHPfile.php',
data: {form : $('form').serialize()}
}).done(function(data) {
var myJSONresult = data;
});
});
In your PHP file you'll get the form with
$form = $_POST['form'];
and there's no need to save to a file, just send it back by echoing
echo json_encode($main_arr);
Here is an example of posting to a php file and grabbing the data with ajax.
The result will get logged into the console.
I assume you know how to process the json with js once it has been retrieved?
//the php
<?php
//bla bla connect to database etc
//if form has been submitted with ajax
if(isset($_POST["ajax_request"])){
//build query
$id = $_POST["id"];
$fruit = $_POST["fruit"];
$query = "SELECT * FROM fruits WHERE id=$id AND fruit='$fruit'";
//fetch from db
$result = mysql_query($query);
//send out json
die(json_encode($result));
}
?>
//the jquery
<script type="text/javascript">
$(document).ready(function(){
//on submit
$("#ajaxForm").submit(function(e){
//stop default page refresh
e.preventDefault();
//define the form
var form = $(this);
//get the form data
var data = form.serialize();
//send it via ajax
$.ajax({
type : "post",
dataType : "json",
url : "url to your php here",
data : data+"&ajax_request=1",
success : function(json){
console.log(json);
},
error : function(a,b,c){
console.log(a,b,c);
}
});
});
});
</script>
//the html
<form id="ajaxForm" method="post" action="">
<input type="text" name="id" required="required" placeholder="enter id"/>
<input type="text" name="fruit" required="required" placeholder="enter fruit"/>
<input type="submit" name="submit"/>
</form>