PHP/JS: Posting input value with js function and echoing through php - php

My goal is to have input field that will take value of whats was typed and echoed through. The js function will grab the value of the input box two seconds after user stops typing and post it. The issue seems to be with the php not echoing the value of the input box. When I take out the js function and use a button that forces refresh then
it works fine. How come php is not taking the value posted by js function?
Example SITE
JS
<script type="text/javascript">
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//then include your submit definition. What you want to do once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php', form, function(data){
});
return false;
});
});
</script>
PHP
<?php
if($_POST)
{
$url = $_POST['yurl'];
function getYoutubeVideoID($url) {
$formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})
(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
return $formatted_url;
}
$formatted_url = getYoutubeVideoID($url);
$parsed_url = parse_url($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
$hth = 300; //$_POST['yheight'];
$wdth = 500; //$_POST['ywidth'];
$is_auto = 0;
//Iframe code with optional autoplay
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
}
?>
form
<html>
<form method="post" id="ytVideo" action="">
Youtube URL: <input id="video-input1" type="text" value="<?php $url ?>" name="yurl">
<input type="submit" value="Generate Embed Code" name="ysubmit">
</form>
</html>

It's because you are not returning your php result anywhere. It's simply lost...
$.post('index.php', form, function(data){
var x = $(data);
$("body").html(x);
});

Related

How to fetch data from database based on user input and display as JSON array using asynchronous POST in php

I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});

submit form php without refresh page

I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}

Displaying Javascript Content In HTML Or Php Variable

I have javascript that gets the Facebook name of a user when they login on my file indir.php. However, I cannot get that name javascript variable to transform into a php variable or a <input type="hidden" name="name" value="" />. Currently, I can get the name using:
<script>
...facebook stuff...
function login() {
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
}
}
...
</script>
And then display the name using:
<div id="login" style ="display:none"></div>
This should let you get the name in the field
First Add an id to the input field
<input type="hidden" name="name" id="fb_name" value="" />
Then
<script>
...facebook stuff...
function login() {
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
//Enter the value in field
var field= document.getElementById("fb_name");
field.value = mos;
}
...
</script>
I think part of the problem is that the opening brackets on the FB.api call are not closed see snippet below.
If this is this done then the javascript function will update the div with the value of response.name.
It would only need to be a php variable if you are doing something with the information server side. You could then send it using AJAX if needed.
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
var mos = response.name;
document.getElementById('login').innerHTML = mos;
});
});
You can send it to php in a POST-request using AJAX:
var xhr = new XMLHttpRequest();
var content = "c=" + mos;
xhr.open("POST", "serverscript.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(content);
Receive at server side using something like
<?php
if (isset($_POST['c'])) {
$data = htmlspecialchars($_POST['c'], ENT_QUOTES, 'UTF-8');
}
?>
Try this something like this:
Javascript:
<script>
var name = 'Luis';
var variablejs = 'Your javascript value: ' + name ;
</script>
PHP:
<?php
$variablephp = "<script> document.write(variablejs) </script>";
echo "variablephp = $variablephp";
?>

Ajax call not working on enter keypress, works only for click function

I have a ajax method of calling data from php file, i learned it from one of a blog, now it works file for submit button click function, but when i press enter the variables get shown in address bar and ajax process is not executed, Can any one please help me doing it on a press enter method....
This is my code:-
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
I have tried it by taking an if condition along with keypress event still its not working:-
if (e.keyCode == 13) { // Do stuff }
else { // My above code }
//In this also it seems that i am doing something wrong.
Can anybody please enlighten me oh how to do it.
My input field is:-
<input type="text" name="searchuser_text" id="newInput" maxlength="255" class="inputbox MarginTop10">
My submit button is:-
<input class="Button" name="search_user_submit" type="button" value="Search">
You can try with event.preventDefault(); for enter keypress.
Thanks.
When you type enter there is executed default onSubmit handler for a form. You can use submit jquery function to handle both enter and click on submit button.
$("form").submit(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = { "cv" : cv, "cvtwo" : cvtwo }; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "../elements/search-user.php";
$.post(url, data, function(data) {
$("#SearchResult").html(data).show();
});
return false;
});
return false in this function will prevent submit of the form.

Send POST data to PHP without using an HTML form?

Is there anyway to send post data to a php script other than having a form? (Not using GET of course).
I want javascript to reload the page after X seconds and post some data to the page at the same time. I could do it with GET but I would rather use POST, as it looks cleaner.
Thanks a lot.
EDIT: Would it be possible to do with PHP header? I'm sure it is better to use JQuery but for my current situation I could implement that a lot easier/faster : )
Cheers
I ended up doing it like so:
<script>
function mySubmit() {
var form = document.forms.myForm;
form.submit();
}
</script>
...
<body onLoad="mySubmit()";>
<form action="script.php?GET_Value=<?php echo $GET_var ?>" name="myForm" method="post">
<input type="hidden" name="POST_Value" value="<?php echo $POST_Var ?>">
</form>
</body>
Seems to work fine for me, but please say if there is anything wrong with it!
Thanks everyone.
As requested above, here is how you could dynamically add a hidden form and submit it when you want to refresh the page.
Somewhere in your HTML:
<div id="hidden_form_container" style="display:none;"></div>
And some Javascript:
function postRefreshPage () {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'somepage.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'input_1';
newInput1.value = 'value 1';
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'input_2';
newInput2.value = 'value 2';
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
}
This is equivalent to submitting this HTML form:
<form action="somepage.php" method="post">
<input type="hidden" name="input_1" value="value 1" />
<input type="hidden" name="input_2" value="value 2" />
</form>
You can use JQuery to post to a php page:
http://api.jquery.com/jQuery.post/
By jQuery:
$.ajax({
url: "yourphpscript.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
},
error: anyFunction // when error happened
complete: otherFunction // when request is completed -no matter if the error or not
// callbacks are of course not mandatory
})
or simplest:
$.post( "yourphpscript.php", data, success_callback_as_above );
more on http://api.jquery.com/jQuery.ajax
Use the FormData API.
From the example there:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
Form your own header, as such:
POST /submit.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
userId=admin&password=letmein
How about this:
function redirectWithPostData(strLocation, objData, strTarget)
{
var objForm = document.createElement('FORM');
objForm.method = 'post';
objForm.action = strLocation;
if (strTarget)
objForm.target = strTarget;
var strKey;
for (strKey in objData)
{
var objInput = document.createElement('INPUT');
objInput.type = 'hidden';
objInput.name = strKey;
objInput.value = objData[strKey];
objForm.appendChild(objInput);
}
document.body.appendChild(objForm);
objForm.submit();
if (strTarget)
document.body.removeChild(objForm);
}
use like this:
redirectWithPostData('page.aspx', {UserIDs: getMultiUserSelectedItems()},'_top');
You can send an xhr request with the data you want to post before reloading the page.
And reload the page only if the xhr request is finished.
So basically you would want to do a synchronous request.

Categories