Javascript Output using PHP [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to execute the below code which perfectly returns me an output from database.
<?php if(isset($_POST['submit']))
{
$email = $_POST["Email_i"];
$checkRe = mysql_query("select * from contact_form where email='$email'",$con);
if(mysql_num_rows($checkRe)>0)
{
$check = 1;
}
?>
I am trying to call a function using onSubmit event as follows;
<form action="#" method="post" name="myForm" onSubmit="return CheckForm()">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
function CheckForm()
{
var calc =1;
var Checkre = "<?php
$check="";
echo $check; ?>";
if(calc == Checkre)
{
alert('phone number exists');
return false;
}
}
</script>
the above function does not set the value of $check hence not resulting into its execution.

instead of HTML FORMS, try to use and utilize jQuery AJAX.
Sample Code (where data is passed as object [or named array], dataType is declared for your api.php response, timeout is included for network error, error + success + complete functions):
$(document).ready(function(){
$("#btnSubmit").click(function(){
var x = $("#textbox").val();
$.ajax({
type: "POST",
url: "url-to-php-api",
data: { reference:x },
dataType: "HTML-or-JSON-or-JSONP",
timeout: 30000, //1 sec = 1000 ms
error: function(x, t, m) {
if (t === "timeout") {
alert("Network Connection Delayed.");
//this is for network error i.e.: connection delays
}
//and some other codes for other errors~
//error function runs when there is some error with the jQuery AJAX syntax
},
success: function(retData) {
alert("PHP RESPONSE: " + retData);
//success function runs when the js successfully communicated, passed the values to PHP, gets result and back
},
complete: function() {
alert("jQuery AJAX Function Complete.");
//complete function runs after the process is completed, regardless of being error of successful
}
});
});
});
this code is of course, as far as my personal coding is concerned

Related

$_SESSION var no passed [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I have php page which contains two javascript functions like this:
function PregledDokumenta(id)
{
var info = id.split('-');
var vrdok = info[0];
var brdok = info[1];
$.ajax({
type: "POST",
url: "../Php/Dokument/Pregled.php",
data: { vrDok: vrdok, brDok: brdok },
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
}
});
}
function UnosNoveStavke()
{
var vrdok = <?php echo($_SESSION['vrDok']);?>;
var brdok = <?php echo($_SESSION['brDok']);?>;
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
$.ajax({
type: "POST",
url: "../Php/Dokument/IzborRobe.php",
data: {vrDok: vrdok, brDok: brdok},
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
}
})
}
So when i load page and press button i run PregledDokumenta(id) function. In there i pass some values from id of element and then i echo back some other text and buttons as you can see i alert $_SESSION['vrDok'] to see if it is assigned and it returns value. Then when i click button (about 10 sec after running first function) that i echoed back from first function i run second UnosNoveStavke function. There you can see I again alert to see if $_SESSION return value but it return undefined. Why is that happening?
You are very confused regarding how JavaScript and PHP communicate with each other!
For example, with the following code, you are effectively trying to assign JavaScript variables, which you get from an AJAX request, into PHP sections:
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
This can't work, because all PHP expressions are evaluated before the page even loads.
If you need to save these values in PHP sessions, you have to do it either in the file the AJAX request is sent, in your case Pregled.php, or a PHP file that you include in it.

jQuery won't reload this div or recognise it's new PHP $_SESSION value

I am using Ajax to submit a form using a nonce stored as a PHP session which, as the name suggests, unsets itself and generates a new nonce every time it is used successfully. This works perfectly the first time the Ajax is run.
If I view the source on the page after running it, the new nonce is being updated correctly in the actual code, but for some reason jQuery refuses to read the new value from the #nonce div or update the display on the page with the new $_SESSION value.
The div holding the nonce and the submit button (index.php)
echo '<input type="text" id="nonce" value="'.$_SESSION['nonce'].'">';
echo '<div id="form-test-ajax">
<input type="submit" name="submit" value="submit" id="btn">
</div>';
The jQuery functions in external file (functions.js)
$(document).ready(function() {
$('#btn').click(function() {
$.ajax({
url: 'adminapi.php',
dataType: 'json',
method: 'post',
cache: false,
data : {
"action": "testAction",
"nonce": $('#nonce').val()
},
success: function(data) {
reloadNonce();
},
error : function(xhr, status) {
alert(xhr.status);
console.log("something went wrong");
},
timeout: 30000,
});
});
function reloadNonce() {
$("#nonce").load(location.href + " #nonce");
}
});
The Ajax handler (adminapi.php)
require_once 'inc/globals.php';
header("Access-Control-Allow-Methods:POST");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");
header("Content-Type:application/json");
// Check if the request is an AJAX request
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (isAjax()) {
if (isset($_POST["action"]) && !empty($_POST["action"]) && isset($_POST["nonce"]) && !empty($_POST["nonce"])) {
$action = strip_tags($_POST["action"]);
$nonce = strip_tags($_POST["nonce"]);
// Validate nonce
$securityCheck = validateNonce($nonce);
// Nonce checked out
if ($securityCheck) {
admin_response(200, "Success");
exit();
} else {
// Invalid nonce, failed
admin_response(200, "Error : Security token was incorrect");
exit();
}
}
}
The other relevant PHP functions (globals.php)
// Generate nonce
function generateNonce()
{
$_SESSION['nonce'] = bin2hex(openssl_random_pseudo_bytes(16));
return;
}
// Validate nonce
function validateNonce($nonce)
{
if ($nonce == $_SESSION['nonce']) {
unset($_SESSION['nonce']);
generateNonce();
sessionTimeOut();
return true;
} else {
return false;
}
}
// Set session expiry
function sessionTimeOut()
{
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (15 * 60);
}
// Deliver admin function response
function admin_response($status, $status_message)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$json_response = json_encode($response);
echo $json_response;
}
I've obviously left off chunks of irrelevant code PHP wise, session_start(); etc as the PHP side of this is running perfectly. It's only the jQuery I'm having an issue with.
The JQuery load() method internally uses the innerHTML function to populate the matched element with the ajax response. So I would say it's not appropriate for your use-case, as you need to set the value of an input field, instead of update the html contents of a div. I'd check out the JQuery docs for more info: http://api.jquery.com/load/
Just in case anybody else runs into a similar problem the answer was to return the new nonce in the ajax success response and then set the value to the nonce id.
Works now!
The jQuery
success: function(data) {
$("#nonce").val(data.nonce);
reloadNonce();
...
The PHP
admin_response(200, "Success", $_SESSION['nonce']);
...
and..
function admin_response($status, $status_message, $nonce)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$response['nonce'] = $nonce;
$json_response = json_encode($response);
echo $json_response;
}

ajax and php pettition satuts cancelled after x attempts [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my petitions
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.
Pass these values to hidden fields. These fields are called through ajax to send data to next-page to update.
<input type='hidden' value="<?echo $costo_sem;?>" class="costosemanal">
<input type='hidden' value="<?echo $fi;?>" class="fechai">
<input type='hidden' value="<?echo $ff;?>" class="fechaf">
echo "<script>
var r = confirm('OK to update, CANCEL to do nothing');
if(r === false){
document.location.href = 'costos.php';
}else{
var costosemanal=$('.costosemanal').val();
var fechai=$('.fechai').val();
var fechaf=$('.fechaf').val();
$.ajax({url:'UpdatePage.php?costosemanal='+costosemanal+'&fechai='+fechai+'&fechaf='+fechaf,cache:false,success:function(result){
alert('Updated');
}});
}
</script>";
Add one UpdatePage.php to update your query.
UpdatePage.php
<?
$costosemanal=$_GET['costosemanal'];
$fechai=$_GET['fechai'];
$fechaf=$_GET['fechaf'];
$update = "UPDATE tbl_costos SET costo_semanal = '$costosemanal' WHERE fechai = '$fechai' AND fechaf ='$fechaf' ";
//Write Mysql Command To Update This Query
?>
$('.removeItem').click(function (event) {
if (confirm('Are you sure you?')) {
$.ajax({
url: 'myUrl',
type: "POST",
data: {
// data stuff here
},
success: function () {
// does some stuff here...
}
});
}
});
Use above code inside url there must be php page url...

jQuery.ajax + php 5.3 - always executing error function

(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}

How to call php function from JavaScript function? [duplicate]

This question already has answers here:
Javascript and PHP functions
(7 answers)
Closed 9 years ago.
In my index.php file, I have a php function "InsertTheRecord" which gets a parameter and insert it into the database. It return 1 if that parameter is inserted successfully otherwise 0.
I have following JavaScript function "InsertRecord" in same index.php from where I want to call php InsertTheRecord function. How can I call php function from JavaScript function?
My JavaScript function:
function InsertRecord() {
var myParameter = 40;
var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
if result == 1 { //do something}
else { //show error message}
}
php server side scripting language and javascript is client side scripting language
you can do this by ajax call(Jquery)
<div id="yourdiv"></div>
var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output) {
alert(output);
document.getElementById("yourdiv").innerHTML += output; //add output to div
}
});
}
myscript.php
<?php
myfun();
function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>
this alert "hello world how are you?"
Try
var result = <?php echo InsertTheRecord(myParameter); ?>
updated after OP's comment
$.ajax
function InsertRecord() {
$.ajax({
type: "POST",
url: "your_php_page.php",
data: "arg1=id&arg2=name",
success: function (data) {
var myParameter = 40;
var result = data;
if result == 1 {} else {}
}
});
}
PHP is serverside,
JS is clientside,
So the PHP works first, after that the JS works dynamically in the browser.
You cannot call the PHP function in runtime. But you can use AJAX which can do that. Check this out: http://www.w3schools.com/ajax/ajax_aspphp.asp
What if you echod the myParameter to a hidden input field and then grabbed it with javascript:
HTML/PHP file:
<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>
In Javascript:
function InsertRecord() {
var myParameter = 40;
var result = document.getElementById("myParameter").value();
if result == 1 { //do something}
else { //show error message}
}
It is not possible
Javascript is client side scripting language where PHP is server side scripting language
But, you can try AJAX methods to get similar results where you can pass variables same as function
as function myfunction(var1, var2 ,....){return var1*var2}
using ajax, you can run a php script externally on button click
$.ajax({key:var},function(result){alert(result)});
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.tutorialspoint.com/ajax/

Categories