using POST to send js variable to php from iframe - javascript

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;
?>
I also tried $.post as suggested here Using $.post to send JS variables but that didn't work either.
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

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'];

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

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
});
});

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>

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>

Related

Is it possible to load content of page without Refreshing the whole page

Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );

JQuery AJAX call to php function

I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

How do i submit a hidden form using ajax when the page loads?

How can i submit a hidden form to php using ajax when the page loads?
I have a form with one hidden value which i want to submit without refreshing the page or any response message from the server. How can implement this in ajax? This is my form. I also have another form in the same page.
<form id = "ID_form" action = "validate.php" method = "post">
<input type = "hidden" name = "task_id" id = "task_id" value = <?php echo $_GET['task_id'];?>>
</form>
similar to Zafar's answer using jQuery
actually one of the examples on the jquery site https://api.jquery.com/jquery.post/
$(document).ready(function() {
$.post("validate.php", $("#ID_form").serialize());
});
you can .done(), .fail(), and .always() if you want to do anything with the response which you said you did not want.
in pure javascript
body.onload = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("task_id=" + document.getElementById("task_id").value);
};
I think you have doubts invoking ajax submit at page load. Try doing this -
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": "validate.php",
"type": "post"
"data": {"task_id": $("#task_id").val();},
"success": function(){
// do some action here
}
})
})
</script>
If you're using jQuery you should be able to get the form and then call submit() on it.
E.g.:
var $idForm = $('#ID_form');
$idForm.submit();
Simple solution - jQuery AJAX post the value as others have suggested, but embed the PHP value directly. If you have multiple forms, you can add more key:value pairs as needed. Add a success/error handler if needed.
<script type="text/javascript">
$(document).ready(function(){
$.post( "validate.php", { task_id: "<?=$_GET['task_id']?>" } );
})
</script>
As others have said, no need for a form if you want to send the data in the background.
validate.php
<?php
$task_id = $_POST['task_id'];
//perform tasks//
$send = ['received:' => $task_id]; //json format//
echo json_encode($send);
JQuery/AJAX:
$(function() { //execute code when DOM is ready (page load)//
var $task = $("#task_id").val(); //store hidden value//
$.ajax({
url: "validate.php", //location to send data//
type: "post",
data: {task_id: $task},
dataType: "json", //specify json format//
success: function(data){
console.log(data.received); //use data received from PHP//
}
});
});
HTML:
<input type="hidden" name="task_id" id="task_id" value=<?= $_GET['task_id'] ?>>

Ajax, add to database and update div content

Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.
I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.
First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.

Categories