I'm relatively new to javascript, but I've read lots of posts talking about Jquery .get and the need to use a callback function today... but I guess I'm still not doing it right. I have a function that 'gets' the result from a PHP page which accesses a MySQL table.
I've included alerts in my code so I can see that the page is called correctly and is returning the result I expect. If the file already exists in the database then the 'get' returns "exists" if the file is in the database but flagged as deleted 'get' returns "deleted" and if the file isn't in the database 'get' returns nothing.
However, when I place alerts inside the if(file_exists=="exists") statement they never get triggered. I even tried moving the entire evaluation section to another function and calling that function from inside the first. still no joy. docReplace never gets set to true and I never see the dialog asking if I want to replace it.
Please, some helpful suggestions?
<script type = "text/javascript" language = "javascript">
function docCheck(){
var attachfilepath = document.getElementById("AttachFile").value;
var docguid = document.getElementById("DocGuid").value;
//cut the file path down so just get the filename
attachfile = attachfilepath.substr(attachfilepath.lastIndexOf("\\")+1);
// Check to see if file exists.
$.get("Doc_Check.php", {guid:docguid, filename:attachfile}, function(file_exists){
alert(file_exists);
if(file_exists=="exists"){
if(confirm("The file \"" + attachfile +"\" already exists. Would you like to replace it?")){
document.getElementById('docReplace').value = "true";
}else{
return false;
}
}else if(file_exists == "deleted"){
document.getElementById('docReplace').value = "true";
}
});
var rreplace = document.getElementById('docReplace').value;
alert (attachfile);
alert (docguid);
alert (rreplace);
}
</script>
Related
I passed a parameter through an URL using javascript. Here's the code:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username="+cookie_user);
};
</script>
The page that received the parameter is called ChangeInfo
This is what I see in the URL when I get to the ChangeInfo page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
When I'm trying to get the parameter username from the URL, I get this error:
Notice: Undefined index: username in C:\xampp\htdocs\test\ChangeInfo.php on line 5
The way I'm trying to get this parameter is to use $_GET like that: $username = $_GET['username'];
Does anyone know why this makes me a problem?
Thanks in advance
I just solve the problem
I deleted the Page parameter from the URL I created in javascript part.
this is the updated Javascript part:
<script>
window.onload = function() {
// Creating a cookie after the document is ready
var cookies = document.cookie.split(";")
var cookiePair = cookies[0].split("=");
var cookie_user=cookiePair[1]; // remove ending parenthesis here
window.location.replace("http://192.168.206.1/test/ChangeInfo.php?username="+cookie_user);
};
</script>
thank you :)
Ignoring the javascript part, needing to focus on PHP.
You are on this page:
http://192.168.206.1/foodblog/?page=http://192.168.206.1/test/ChangeInfo.php&username=nitzan
And when you use $_GET['username'] you get the error, that it is not assigned.
It seems that your $_GET is not working at all, probably Apache settings.
Also, it is safer to get GET parameters with isset first.
if(isset($_GET['username']) && $_GET['username']] {
$username = $_GET['username'];
}
else {
$username = '';
}
Then you can compare, if username is set or not in your php code:
if($username) {
//Do something
}
Final thought. Is your first parameter page=http://192.168.206.1/test/ChangeInfo.php working? Can you get it through $_GET?
The problem seems to be just in the way you set and get the url parameter though $_GET. If you use some framework, it might be disabled to use $_GET directly and for example in Symfony you need to use:
$request->get('username');
So my problem is actually pretty simple:
I have this function (simplified) - it is triggered when a button is clicked:
$search.onclick = function () {
// let's just say the user did put in a valid documentname
// something like "John"
documentname = $('#userinput').val();
url = "https://example.api.url.com/" + documentname + "&format=json"
// looks weird but "source = $.getJSON(url).done..." works like expected
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
// this findid(); below is just a function that takes the id i'm looking for
// out of the just stringified JSON (works also), it does "id = "123456"
// (just a number but in string format)
findid();
// id has a value now ("123456"), so lets console.log it
console.log(id);
});
};
What I want to do is:
After findid(); is executed and id has a value I want to save this value as a readable file on the server. It's filename should be the same as the name of the document it's coming from (in this case John). The content of the file should just be the value of id (in this case 123456). Which file format? I don't know. And here is the next problem...
Reuse the file:
The next thing I wish I would be able to do is, to load this generated file when the exact documentname was inputted again by another user. Because if the file already exists, it would be unnecessary to load the whole JSON again. So the updated code would look like this (i know that this isn't actual code, but maybe it's easier to understand with this):
$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if ([A FILENAME ON THE SERVER] == documentname) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
[OPEN FILE/TAKE CONTENT]
// and just assign it to the variable
id = [CONTENT OF FILE]
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// and of course save this now on the server
[SOME PHP ACTION HERE]
});
}
};
I already tried a lot of things with Ajax and jQuery's $.get, I just have no idea how to handle sent things with PHP. I don't know which file format is best for this, or if this is even possible. I don't know how to transfer variables from JavaScript to PHP documents or how to use them there or vice versa.
PS: My developer environment: I don't run a server by myself, I have some webspace and a domain from a web service. Yes it supports PHP. MySQL and other database types are available too, if that's a useful information. jQuery is also installed.
Sorry again, for my bad english and for my lack of knowledge and interest in PHP and other serverside things. However, I hope you can help me somehow.
You can use localStorage to store a file at users browser configuration folder : user filesystem. If file exists at localStorage, use the file from localStorage without making $.getJSON() request, else call $.getJSON(); at success of $.getJSON() set the file at localStorage.
$search.onclick = function () {
// another user inputs "John"
documentname = $('#userinput').val();
// so we want to prove if a file called "John" already exists on the server
if (localStorage.getItem(documentname) != null) {
// if it exists, we just have to open that file and take the content (the id we saved before) out of it
// and just assign it to the variable
id = localStorage.getItem(documentname);
// console.log it
console.log(id);
}
else {
// if it doesn't already exist, just run the normal code
// and of course save this now on the server
// [SOME PHP ACTION HERE]
url = "https://example.api.url.com/" + documentname + "&format=json"
source = $.getJSON(url).done(function () {
sourcestring1 = JSON.stringify(source);
findid();
// console.log it
console.log(id);
// set `localStorage` item key to `documentname`
// set value to `id`
localStorage.setItem(documentname, id);
});
}
};
See also How to cache a downloaded javascript fle which is downloaded using script tag
Flow process to make this work should be more like:
ajax request to php endpoint on server.
php checks if data stored locally ( in file or database)
If not stored already , php makes request to other api. When the api returns data, php stores it in file or database.
php returns the data to ajax from either the local source or from api response.
So the javascript would only make one request to your server and get the data returned and not know or care how php found it
jQuery has a $.post() function, https://api.jquery.com/jquery.post/
$.post(url, { id: 123456 });
or
$.ajax({
method: 'POST',
url: 'http://example.api.domain.net/document.php',
data: { id: 123456 },
success: function(responseData) {
}
});
PHP will then be able to read it like so:
$post_data = $_POST['id'];
// Here you do whatever with it, for example store to database
Edit/Clarification: I have a php page, call it displayPhotos.php, in which I set up an Ajax call to a different php page, call it getPhotos.php, which queries a database and returns photo information (caption, file name etc) to displayPhotos.php where they are displayed. I use php in displayPhotos to manipulate the data returned from getPhotos. The returned data from the Ajax call is a javascript 2-dimensional array. I need to turn the javascript array into a php array so I can do they display and other stuff. How do I do that?
Hope this helps.
My eyes hurt from reading all of the docs.
I want to use ajax to query a database, return the data then use php to continue with the web page.
All of the examples I've looked at start with creating the json in php. I need to start with the json object in javascript.
<script>
var photoarray = [];
var ajaxRequest = $.ajax
({
url : "fhs_get_photos.php",
type: "POST",
dataType: "json",
success: function(photo_array)
{
photoarray = photo_array;
//line below works. the file name is correct but disappears
//outside of this function
console.log("photoarray[0][file_name] is: " + photoarray[0]['file_name']);
},
error: function(request, status, error)
{
alert('An error occurred: ' );
}
});
In this instance I'm not passing anything to the php file that query's the db. The console log shows that the file name in photoarray is correct but once outside of this function it disappears even though it's declared as global, I think it is anyway. Why and what do I need to do to fix this.
The php file just does a SELECT * FROM..... and returns everything.
// in fhs_get_photos.php
// SELECT * FROM table......
echo $json = json_encode($result);
return $json;
So I now have the array back but it's in javascript. Once I figure out the scope problem, how can I convert this javascript array to a php array?
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<figure id="photo_figure">
<script>
//line below gets me: SCRIPT5007: Unable to get property 'thumb' of
//undefined or null reference
console.log("photoarray thumb: ") + photoarray[0]['thumb'];
</script>
Am I explaining this properly?
First of all AJAX is async. This means it sends the request when you ask it to, but receives the response sometime later in the future. And it works after php has rendered and sent the page. So. When you get an update via AJAX, you have to use javascript to make that update matter. The most simple solution is to process the response right there in the success callback. That way you don't need to mess with the global scope (which is a bad practice).
Supposedly, your HTML is like this:
<header>
<h3>Welcome to the Historical Society's historical photo archive
</h3>
</header>
<div id="figures"></div>
You can do it by declaring a function that handles the processing:
function updateDom(photoArr) {
var $figures = $('#figures');
$.each(photoArr, function() {
console.log(this);
$figures.append('<img src="' + this.thumb +'">');
});
}
Code below is placed in the success callback
And execute that function in the success callback and pass it the array from json, that was parsed and became a valid js object.
var photoArray = JSON.parse(photo_array);
updateDom(photoArray);
here's the fiddle, but it's for the DOM part only
I have taken some source code from here to submit a form using AJAX. The form is basically taking some information from a user and putting it into a database via PHP. The code I have works, but given that what I am working on has many forms all doing the same thing, I - obviously - want to make sure my code is lean and mean. So, making sure that each of my form field names have the same as my database with some matching IDs for various parts of the form for user feedback, have changed it to the following:
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
The code as above works absolutely fine; the relevant PHP file is called and - although I have no processing done in this particular file yet - does its stuff (I have it echoing the $_POST array to a file and returning to view in the console log atm).
However, when I try and make it a function, it doesn't - the console log simply echoes out the source code for this document instead of the PHP array that it supposed to be doing. The function is placed above the $(document).ready line; specified as function completeForm(formID) { . . . } , contains the section of code as noted in the comments and called in the commented out line as shown. So, logically (to me) it should work.
The ultimate idea is to have the function to do this in a file that can be called by all the forms that call it, while the code to call the function is in the relevant part of the page. Some pages will have more than one form using it. (I mention that should even if what I am doing here works, it wouldn't when I come to reuse the code!)
(I'm relatively new to JS and JQuery, although have a fairly good grasp of some programming techniques, mainly these days just in PHP.)
The issue you are having with making that a function is you forget to include the "thisBinding". As a result, when you tried to use the form's action target in your ajax call with this code:
url : $(this).attr('action')
it does not find an "action" attribute - basically the issue is that this is actually window and as a result there is no action attribute. Simply bind this to your function call and your code will work as written.
completeForm.call(this,'#formId');
.call MDN
I'm doing my first mobile app with jquery mobile and phonegap/cordova. All goes great until I create the pages themselves, but as soon as I want to access some variables i access from the remote server, it fails at specific places. I already tried about 30 variations re-writing the same code again - literally spent 4 hours already on outputting a simple var -, but no success, and i simply pulling my remaining hair out now.
Here's my code snip
I have an html file, a js file and a php on serverside, outputting a json answer
php response i get:
{"item":{"ID":"1","fname":"Kris","lname":"Nagy","email":"myemail#email.com","password":"abc123","role":"1","practice":"0","address":"","city":"","zip":"","phone":""}}
login.js
var userName;
function getUser() {
$.getJSON( "http://myserver.com/getuser.php?email=myemail#email.com&pass=absc123", function( json ) {
console.log( "JSON Data: " + json.item.fname );
console.log( "JSON Data: " + json.item.email );
// testing if i have the correct data, console outputs the rigth values
userName = = json.item.fname;
window.userName = json.item.fname;
//trying to assign value to variable
console.log( "Variable data" + window.userName );
// testing if i have the correct data stored, console outputs the right value
});
}
getUser();
console.log( "test outside function" + window.userName );
//gives back undefined
index.html (here I'm just trying to access the variable, sure i have the full html, including the js, jquery and all necessities)
<script>
getUser(); //outputs the values to console
console.log( "test in html" + window.userName ); /*/gives back undefined
</script>
As i need some vars in my html to work with, how do i achieve to be able to output them in the html. This example tries to make some kind of login, but my question is more abotu the variables, as i want to understand them. In my understanding I have global variables with the window. call, but it seems everything but to be global, and I'll need to work with variables all along the app, so its vital i understand them. Though as you see it seems i miss a point, so any help is so appreciated.
I know how to work with php, but as the final product needs to run on cordova, I'm limited to html/js on the client side, and javascript is not my strength (yet).
You could return the promise interface exposed by ajax request from your function:
var userName;
function getUser() {
return $.getJSON(...);
}
getUser().done(function () {
console.log("test outside function" + window.userName);
});
You cannot access userName outside the JSON success callback, since you are assigning teh value only in success callback of an asynchronous method.
console.log( "test outside function" + window.userName ); // it wont work
If you still want to access immediately, make synchronous call by setting one of ajax settings async:false, but the overall goal of ajax is lost