0

I am running a function and it returns download link, I'm looking forward to pass this as variable to php in same page to send notifcation with image attached in it. But I try cookies method and rest other methods suggested by many but none of them works.

After Upload is finished I store it in variable like

   var ImageLink    = downlaodURL;

and I want to accesss in php in

$notification->setImage("Here I want to get variable");

Here is my Full Code

		<div class="container" style="margin-top: 30px;">
			<div class="row">
				<div class="col-lg-6">
		
					<form action="" method="post" onchange="myFunction()">
	
					
						<div class="form-group">
							<label for="title">Title:</label>
                                      <p class="lead emoji-picker-container">
							<input  value=""  type="text" required="" class="form-control" id="title" placeholder="Enter Notification Title" name="title">
						</p>

						</div>
						<div class="form-group">
							<label for="message">Message:</label>
                                    <p class="lead emoji-picker-container">
							<textarea  required="" class="form-control" rows="5" id="message" placeholder="Enter Notification Message" name="message">  </textarea>

                                               </p>
						</div>
				
						<div class="form-group"id="image_url_group">
							<label for="image_url">Image URL:</label>
							<input type="file" class="form-control" id="image_url" placeholder="Enter Image URL" name="image_url" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf" >
						</div>
			

						<button type="submit" class="btn btn-info">Submit</button>
					</form>
				
				</div>
				<div class="col-lg-6">
		
	
				</div>
			</div>
		</div>
		

	</body>

	<script type="text/javascript">
		var config = {
    apiKey: "My Key",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};
firebase.initializeApp(config);

function myFunction(){



var messagesRef = firebase.database().ref('Notification');


  
    //firebase  storage reference
    //it is the path where yyour image will store
    var storageRef=firebase.storage().ref('Notification/'+imageName);
    //upload image to selected storage reference

    var uploadTask=storageRef.put(image);

    uploadTask.on('state_changed',function (snapshot) {
        //observe state change events such as progress , pause ,resume
        //get task progress by including the number of bytes uploaded and total
        //number of bytes  
  var progress=((snapshot.bytesTransferred/snapshot.totalBytes)*100).toFixed(0);
  
 
        console.log("upload is " + progress +" done");
    },function (error) {
        //handle error here
        console.log(error.message);
    },function () {
       //handle successful uploads on complete

        uploadTask.snapshot.ref.getDownloadURL().then(function (downlaodURL) {

   
// I want To Pass this variable to PHP in Image_url 
          var ImageLink    = downlaodURL;
            
        });
    });




}


	</script>
			<?php


    			 

					if(isset($_POST['title'])){

					
						require_once __DIR__ . '/notification.php';
						$notification = new Notification();
	
						$title = $_POST['title'];
						$message = isset($_POST['message'])?$_POST['message']:'';
						$imageUrl = isset($_POST['image_url'])?$_POST['image_url']:'';
		
						$notification->setTitle($title);
						$notification->setMessage($message);
						$notification->setImage("Here I want to get Download URL");

						$firebase_api = $_POST['firebase_api'];
						
						$topic = $_POST['topic'];
						
						$requestData = $notification->getNotificatin();
						
	
					}
					?>

Thanks in advance.

1 Answer 1

1

Put this under your Storage rules if you dont require users authenticating:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth == null;
    }
  }
}

This goes into your view file index.html or index.php :

    <form action="" method="post" onsubmit="myFunction();return false;">

        <div class="form-group">
            <label for="title">Title:</label>
            <p class="lead emoji-picker-container">
                <input  value=""  type="text" required="" class="form-control" id="title" placeholder="Enter Notification Title" name="title">
            </p>

        </div>
        <div class="form-group">
            <label for="message">Message:</label>
            <p class="lead emoji-picker-container">
                <textarea  required="" class="form-control" rows="5" id="message" placeholder="Enter Notification Message" name="message">  </textarea>

            </p>
        </div>

        <div class="form-group"id="image_url_group">
            <label for="image_url">Image URL:</label>
            <input type="file" class="form-control" id="image_url" placeholder="Enter Image URL" name="image_url" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf" >
        </div>

        <button type="submit" class="btn btn-info">Submit</button>
    </form>

AJAX Submitting image URL to php, This goes into your view file index.html or index.php :

<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-analytics.js"></script>

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-storage.js"></script>

<script>

    // Your web app's Firebase configuration
    var firebaseConfig = {
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_AUTH_DOMAIN",
        databaseURL: "YOUR_DATABASE_URL",
        projectId: "YOUR_PROJECT_ID",
        storageBucket: "YOUR_STORAGE_BUCKET",
        messagingSenderId: "YOUR_SENDER_ID",
        appId: "YOUR_APP_ID",
        measurementId: "YOUR_MEASUREMENT_ID"
    };


    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();

    function AJAXSubmit (image_url) {
        //if (!oFormElement.action) { return; }
        var oReq = new XMLHttpRequest();

        if (image_url) {
            oReq.open("post", 'ajax.php');

            oReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            oReq.onreadystatechange = function() { // Call a function when the state changes.
                if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
                    console.log("Success finished");
                }
            }
            oReq.send("image_url=" + image_url);

            //oReq.onload = ajaxSuccess; //callback once AJAX is done
        }
}

    function myFunction(){
        var messagesRef = firebase.database().ref('Notification');
        //firebase  storage reference
        //it is the path where yyour image will store
        var imageName = 'WhateverYouWantToName';
        var storageRef=firebase.storage().ref('Notification/' + imageName);
        //upload image to selected storage reference

        const selectedFile = document.getElementById('image_url').files[0];

        var uploadTask=storageRef.put(selectedFile);

        uploadTask.on('state_changed',function (snapshot) {
            //observe state change events such as progress , pause ,resume
            //get task progress by including the number of bytes uploaded and total
            //number of bytes
            var progress=((snapshot.bytesTransferred/snapshot.totalBytes)*100).toFixed(0);

            console.log("upload is " + progress +" done");
        },function (error) {
            //handle error here
            console.log(error.message);
        },function () {
            //handle successful uploads on complete

            uploadTask.snapshot.ref.getDownloadURL().then(function (downlaodURL) {

// I want To Pass this variable to PHP in Image_url
                var ImageLink    = downlaodURL;
                AJAXSubmit(ImageLink);
                console.log(ImageLink);
            });
        });
    }

</script>

My firebaseConfig (this is my sandbox test firebase object) object is, make sure you get your correct credentials (example below) from your firebase project for this to work :

var firebaseConfig = {
    apiKey: "AIzaSyAvBKb-l7n5ixDSo2py-iN7m4nwFTKJ3rY",
    authDomain: "justtesting-aa1b4.firebaseapp.com",
    databaseURL: "https://justtesting-aa1b4.firebaseio.com",
    projectId: "justtesting-aa1b4",
    storageBucket: "justtesting-aa1b4.appspot.com",
    messagingSenderId: "258097526144",
    appId: "1:258097526144:web:a65d0cfd9b315a8071fd65",
    measurementId: "G-QWS4MW056K"
};

Create a file named ajax.php to receive the image_url :

if(isset($_POST['image_url'])){
    $fh = fopen( 'success.txt', 'a');
    fwrite($fh, $_POST['image_url'] );
    fclose($fh);
    exit;
}

See screenshot results of this working :

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Chris ..I tried but I must be doing wrong..I'm not able to upload image. Here is the code..if you could help me and look into it ..what am I doing wrong. It would be very helpful. drive.google.com/open?id=18Ldn9KFblPw5egS0NdjZLpdgmv50gwWC
BlueYeti, try and declare your references to firebase javascript dependencies after the HTML form , that is how I'm doing it. So put javascript at the bottom of the page: <script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.