1

I am trying to pass a variable from js to a backoffice page. So far I've tried using a form and submitting it from javascript (but that refreshes the page, which I don't want)

  • I ditched the form and when for an iframe (so the page doesn't reload everytime the data is submitted). The function is run every few seconds (so the form should be submitting):

<iframe style="visibility:hidden;display:none" action="location.php" method="post" name="location" id="location">
 <script>
   /*Some other stuff*/
    var posSend = document.getElementById("location");
    posSend.value = pos;
 posSend.form.submit();
  </script>
  • However my php page does not display the value posted (im not quite sure how to actually get the $_POST variable):

<?php
$postion = $_POST['location'];
echo $_POST['posSend'];
echo "this is the";
echo $position;
?>

How do I get the $_POST variable value? I cannot use $_SESSION - as the backoffice is a different session. What is the best method to do this?

EDIT I'd rather avoid ajax and jquery

Community
  • 1
  • 1
Oliver
  • 821
  • 5
  • 12
  • 28
  • Why are you using iframe like a form? – Jan.J Aug 25 '15 at 09:13
  • 1
    In the HTML part, you're mixing an , a
    and an element together into one. They should be 3 distinct elements.
    – marekful Aug 25 '15 at 09:13
  • because form submission refreshes the entire page, while the iframe sticks to itself and doesn't mess with the page. – Oliver Aug 25 '15 at 09:13
  • @oliver - is there any reason not to simply use a `
    ` to collect the data, a `FormData` object to bundle it all into a single object and then finally, A.J.A.X to submit it?
    – enhzflep Aug 25 '15 at 09:16
  • I've generally been avoiding AJAX and jquery, since I am quite new to web development and so far php, js and some mysql have been doing the job fine. The other issue is that form submission refreshes the page - I dont want that to happen (so far iframes have provided the solution with "get" forms, still trying to figure out $_POST) – Oliver Aug 25 '15 at 09:20
  • ^^ As @enhzflep you should consider using AJAX to submit your form. http://api.jquery.com/jquery.post/ – James111 Aug 25 '15 at 09:20
  • Go back to using a form. Instead of `submit`ing it do an AJAX `POST` - check out jQuery for a helpful way of doing this. – Eborbob Aug 25 '15 at 09:20
  • isn't there a way to this without AJAX or jquery – Oliver Aug 25 '15 at 09:21
  • 2
    An `iframe` does not have `action` and `method` attributes. – CBroe Aug 25 '15 at 09:21
  • @Oliver - if you use AJAX to submit the form's data, it doesn't cause a page refresh - that's the whole purpose of using AJAX in such a scenario. I dont jQuery either, it's quite straight forward with 'vanilla' JS actually. – enhzflep Aug 25 '15 at 09:22
  • @Oliver you can submit the data with an iframe and i will be inserted in the database but you cannot get this new data without refreshing the page that's where the ajax comes in – herriekrekel Aug 25 '15 at 09:22
  • any basic ajax things I should know? – Oliver Aug 25 '15 at 09:24
  • I will recommend you don't use form it refreshes the page use some button instead and send data in post – Domain Aug 25 '15 at 09:26
  • I want the whole process to happen without the user knowing - it is effectively sending their location to a backoffice page, where they can be tracked. – Oliver Aug 25 '15 at 09:27

5 Answers5

1

And i think you no need to use form or iframe for this purpose . You just want to know the user onf without refreshing then use the following method with ajax.

index.html the code in this will

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script>
    navigator.geolocation.getCurrentPosition(function(position) 
    { 
        pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        $.ajax(
        {
            url:'location.php',
            type: 'POST',
            datatype: 'json',
            data: {'pos':pos},   // post to location.php
            success: function(data) {
                aler(data);
                // success
            },

            error: function(data) {
                alert("There may an error on uploading. Try again later");
            },

         });  
    });  
    </script>

location.php

echo "position :=".$_POST['pos'];
Manoj Dhiman
  • 5,096
  • 6
  • 29
  • 68
  • im implementing this atm, however after I get the user location, how do i pass it into the form? say I have the variable `pos`, which needs to go to the other page, where in the function do I assign `pos` – Oliver Aug 25 '15 at 11:03
  • and what does ipinfo.io do? – Oliver Aug 25 '15 at 11:05
  • ipinfo.io get the user location like ipaddress , city country etc. and all this data is available on location.php. you can save it now in db or whatever you want to do with this . – Manoj Dhiman Aug 25 '15 at 11:11
  • and why you want to pass this to form ?? – Manoj Dhiman Aug 25 '15 at 11:11
  • sry didnt mean the form. I meant how do i get `pos` to be sent. `pos` holds the exact coordinates for the person, so i can map them onto a map in the other page. The question was where to put `pos` in the function? like is it in `$.ajax({`... or somewhere else. also running the code like this currently outputs the text, but there are no values for the `$_POST` variables – Oliver Aug 25 '15 at 11:22
  • i use `navigator.geolocation.getCurrentPosition(function(position) { pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); });` to get the position, how do I pass this pos to the other php page? – Oliver Aug 25 '15 at 11:26
  • check now . I have add `pos` to send in post. – Manoj Dhiman Aug 25 '15 at 11:27
  • ok -> So it works fine - the alert comes up with the correct data, but when I go to /location.php it does not have any of the variables/doesn't display them – Oliver Aug 25 '15 at 11:59
  • how do I make sure it sends it to the other .php page? – Oliver Aug 25 '15 at 12:05
  • what do you want to do with this location ?? – Manoj Dhiman Aug 25 '15 at 12:06
  • 1
    then why you are sending pos to location.php?? ajax will send value to location.php with the hidden way . You can save in db with query on location.php. – Manoj Dhiman Aug 25 '15 at 12:09
0

Instead of using iframe to submit your form with out reloading you submit form using ajax call.

$.ajax({
  type: "POST",
  url: url,
  data: $("#formId").serialize(), // This will hold the form data
  success: success, // Action to perform on success
  dataType: "JSON" or "HTML" or "TEXT" // return type of function
});

There are various alternative to submit the form without reloading the page check here

Thanks

Lakhan Kriplani
  • 464
  • 3
  • 9
0

You can use plugin ajaxForm. On action and method you can form options

$(function() {
            $('#form_f').ajaxForm({ 
                beforeSubmit: ShowRequest, //show request
                success:SubmitSuccesful, //success 
                error: AjaxError //error
            });
        });
0

Lakhan is right, you should try to use ajax instead of an iframe as they cause a lot of issues. If you absolutely need to use an iframe add a target attribute to your form (target the iframe not the main page) and only the iframe will reload.

<form action="action" method="post" target="target_frame">
    <!-- input elements here --> 
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe> 
Auris
  • 1,309
  • 1
  • 9
  • 18
0

Here's a fully worked example that makes use of a <form>, the FormData object and AJAX to do the submission. It will update the page every 5 seconds. Do note that in PHP, the use of single quotes ( ' ) and double quotes ( " ) is not always interchangeable. If you use single quotes, the contents are printed literally. If you use double-quotes, the content is interpretted if the string contains a variable name. Since I wanted to print the variable name along with the preceding dollar sign ($) I've used single quotes in the php file.

First, the PHP

location.php

<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];

echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>

Next, the HTML

index.html

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}

function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            successCallback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
        errorCallback(this);
    }
    ajax.open("POST", url, true);
    var formData = new FormData(formElem);
    ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 );       // call the function to submit the form every 5 seconds
}

function doAjaxFormSubmit()
{
    myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
    function onSubmitSuccess(ajax)
    {
        byId('ajaxResultTarget').innerHTML = ajax.responseText;
    }
    function onSubmitError(ajax)
    {
        byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
    }
}

</script>
<style>
</style>
</head>
<body>
    <form id='myForm'>
        <input name='location'/><br>
        <input name='posSend'/><br>
    </form>

    <hr>

    <div id='ajaxResultTarget'>
    </div>
</body>
</html>
enhzflep
  • 12,927
  • 2
  • 32
  • 51