Get data from PHP to Javascript depending on Javascript variable value - javascript

I have variable _randNum in JavaScirpt which generate random number between 1 and 50.
I need to select some data from database depending on value of this variable.
I've used following JavaScript code to select data from database via PHP (but without sending JavaScript variable to PHP).
// handles the click event for link 1, sends the query
function getSuccessOutput() {
getRequest(
'questions.php', // demo-only URL
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
$.getJSON("questions.php", function(theObject){
var d1 = theObject.data1; // Get the data from PHP
var d2 = theObject.data2;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
How can I send _randNum variable's value to PHP?
In PHP I could do something like that:
$rnd = mysqli_real_escape_string($con, $_POST['randNum']);
But no clue, how to send It from Javascript in same function.
I could create function like this:, but how to use It correctly with getSuccessOutput() function?
function sendFtId() {
$.post( "questions.php", { randNum : _randNum })
.done(function( data ) {
});
}
Have you any ideas?

You can use isset function to check any post request is coming or not.
E.g:
function getSuccessOutput($randNum) {
echo $randNum;
}
if(isset($_POST['randNum'])){
getSuccessOutput($_POST['randNum']);
}

Related

Use Javascript to call PHP file that reads website content from MySQL DB

I am working on an assignment for class and we have to create a dynamic website. We have to create all the containers in HTML, then load all out content onto a MySQL DB and then use Javascript to read the PHP file that collects the content from MySQL.
I have managed to get it to pull a list from the DB and display on my site, but now I'm stuck as to how to get it to read other parts of the page and pull them into the html.
Here is the PHP I have so far:
$con=mysqli_connect("localhost","Username","password",'DBname');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"SELECT * FROM HomeList");
echo "<ul>";
while($row = mysqli_fetch_array($result)){
echo "<li>".$row['ListItem']."</li>";
}
echo "</ul>";
mysqli_close($conn);
?>
Here is my Javascript:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById('id');
container.innerHTML = 'Error has occurred';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('id');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I'm wanting to reuse as much code as possible but for pulling content from the DB without having to have multiple JS and PHP files. And we are under strict orders to not use plugins or Bootstrap.
Any help would be great!
Thank you!
A solution could be to declare a new function (ex. updateElt) which calls getOutput by giving it the parameter url ('php/getinfo.php'), but you also need to set your 'id' parameter in order to update the correct element.
So you have to declare an id var in your script (not in a function) and assign it a value in the updateElt. This way the id will have a global scope to your script and you 'll be able to access it in your drawError and drawOutput function.

how to load json from url using javascript?

I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.

There is a delay before html textbox value gets updated after ajax function execution

I am using jcaptcha for image verification in my form. Before the form is submitted I make an ajax call using javascript to validate the text entered by the user corresponding to the image displayed. I get the result and update the value of a textbox(imageVerification). After the function that makes this ajax call is executed I pick up the value from this just updated textbox(imageVerification) for the result.
Here is the problem: I am not able to pick up the value from this textbox(imageVerification).
it always shows up as blank.
Catch: if I use an alert() before picking up the value, I am able to pick up the value correctly. I ran this in firebug debug mode and found out that it works in debug mode even without using the alert.
It seemed there is a delay before which the value in the textbox(imageVerification) gets updated. So i introduced a setTimeout() method and was able to pick up the value.
But I dont feel this is the right solution. I am assuming javascript executes sequentially. So why is my statement which is picking up the value after it has been updated by a method not able to get it immediately. Result is even though the image verification is successfull, my check fails since it is not able to pick up the result value from the textbox.
Also, if I use a simple function to update the textbox(imageVerification) instead of a ajax call, I dont face this problem.
Here is the code I am using for the ajax call.
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid);
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(parameterString);
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1)){
//document.getElementById(containerid).innerHTML = req.responseText
//document.getElementById(containerid).value=req.responseText;
document.forms['ratingForm'].elements[containerid].value = req.responseText;
}
}
This is the function for image verification:
function validateImage(){
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
fetchContainerContent('captchaController','imageVerification');
var obj = document.forms['ratingForm'].elements['imageVerification'];
//alert('val '+obj.value);
var vall = obj.value;
if(vall=='PASS'){
return true;
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
return false;
}
}
post my call to fetchContainerContent('captchaController','imageVerification'), the value for imageVerification textbox should be set. If I use the alert box which is commented after the fetchContainerContent('captchaController','imageVerification') call it works fine.
Please help me out. Thanks alot
UPDATED ANSWER: Misread program flow on first pass.
The basic problem is you're trying to get an immediate response from the validateImage() function (return true or false) when the XMLHttpRequest needs time to complete.
Move the actions taken based on the return to their own functions (validFunction, invalidFunction) and try this:
function validateImage() {}
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
var obj = document.forms['ratingForm'].elements['imageVerification'];
validReq = fetchContainerContent('captchaController','imageVerification');
validReq.onload = function () {
var validResp = this.reponseText;
if(validResp=='PASS'){
validFunction();
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
invalidFunction();
}
}
validReq.send(parameterString);
}
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return req;
}

Checking result of an html form using javascript

I am using an html form to upload a file to my server. I want to execute a javascript function only after the form has been submitted and the file has been successfully uploaded. The form opens a new page with the text "upload succeeded" if the file upload worked. I tried using a while loop that would loop until the file was found in the database but it crashed my browser. How can I do this? I'm using myform.submit() to submit my form right now.
If the post went well, and you save the file before flushing the page contents, this is easy. The page won't return until the post cycle is ready, so you could insert javascript code to the page after the saving of the file.
You can use AJAX to upload you file and you the async return function (this is a event that will trigger when your request is done) to ether a success or failed message from you php.
EDIT:
Here is a ajax function iv made that u can use, just load this in an extenal file:
var ajax = function(data){
// Return false is no url... You need an url to get url data..
if(typeof data.url !== 'undefined'){
var url = data.url;
// Adept the function depending on your method
if(data.method === 'GET' && data.params !== 'undefined'){
url+='?'+data.params;
}
}else{
return(false);}
var // Set some vars 'n' stuff
method = ( data.method === 'GET') ? 'GET' : 'POST',
params = (typeof data.params !== 'undefined') ? data.params : null,
async = ( data.async === true) ? true : false,
done = (typeof data.done === 'function') ? data.done : false,
return_value = null,
length = (data.method === 'POST') ? data.method.length : '';
var // Find out what ajax methods the browser support
request_method = function(){
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlhttp = false;
}
}
}
return xmlhttp;
}// This thing connet to the server
connect = function(){
if(request = request_method()){}else{
return(false);
}
request.open(method, url, async);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", length);
request.setRequestHeader("Connection", "close");
request.send(params);
request_handle(request);
},// This is where the result get processed
request_handle = function(request){
if(async){
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
done(data);
}
}
}else{
done(data);
}
};
connect();
return(return_value);
}
usage:
ajax({
url: 'test.php',
//// Your ajax request url // no default // Must be set!
method: 'POST',
//// Method of sending ajax data // default is POST
async: true,
//// What to do when done with the request // no default
done: function(http){
table(http,'test');
}
});
one simple thing you can do
use executescalar to insert uploading file as soon as it inserts the file return boolean value to check whether it is inserted,if so then set hiddenfield value. in javascript check the value of the hiddenfield and according to that you can call your javascript function

Multiple xmlhttprequest on a page

I am having an error when using new XMLHttpRequest() for the second time in JavaScript code called from textbox event on page.
My JavaScript finds suggestions for text entry from the SQL to do that I use xmlhttprequest, it does fine when it is the first time but when I keep typing in the text box I receive:
"typeerror: xmlhttprequest not a costructor"
(this error happens only in Firefox)
This is my code:
function fnNull() { };
function changeofstate(){
if (XMLHttpRequest.readyState == 4)
{
whatever ;
}
XMLHttpRequest.onreadystatechange = fnNull();
}
function whentextchange(){
var WebURL = "the url here ";
XMLHttpRequest = CreateXmlHttpObject(changeOfState);
XMLHttpRequest.open("GET", WebURL, true);
XMLHttpRequest.send(null);
XMLHttpRequestt.abort();
}
}
function CreateXmlHttpObject(handler) {
var objXmlHttpReq = null;
var Req = null;
if (navigator.userAgent.indexOf("Opera")>=0)
{
return ;
}
if (navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP";
if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP";
}
try
{
objXmlHttpReq=new ActiveXObject(strName);
objXmlHttpReq.onreadystatechange = handler;
return objXmlHttpReq;
}
catch(e)
{
return ;
}
}
if (navigator.userAgent.indexOf("Mozilla") >= 0) {
try
{
if (Req == null) {
Req = new XMLHttpRequest();
}
Req.onload = handler;
Req.onerror = handler;
return Req;
}
catch (e) {
alert(e);
alert(Req.responseText)
alert(e);
return;
}
}
}
You should name your request object something else than XMLHttpRequest. It might override the XMLHttpRequest object in the browser. Thus giving you the error.
XMLHttpRequest = CreateXmlHttpObject(changeOfState);
Assigning XMLHttpRequest variable like this is actually using global scope. You should use var and another variable name
var req = CreateXmlHttpObject(changeOfState);
Hope this clarifies.

Categories