How do I pass javascript to PHP on a javascript command? - php

I'm new to PHP, but I'm developing in Visual Studio LightSwitch.
I'd like to pass several javascript variables from a data record to a PHP script during a javascript save event.
What are my options?

Your options are limited to ajax, or an image request.
Option 1. AJAX
function success() {
console.log(this.responseText);
}
var ajax = new XMLHttpRequest();
ajax.onload = success;
// myVars is a string containing the values you need to record. In the format
// of ?var=value&var1=value&var2=value
ajax.open("get", "/record.php?" + myVars, true);
ajax.send();
Option 2. Image
var a = document.getElementById('my-button');
a.addEventListener('click', function(e) {
var target = e.target || e.srcElement;
var img = new Image();
// get your variables values and create a url here.
img.src = 'http://myserver.tld/record.php?' + myVars;
});

Related

Sending multiple data through jquery ajax

I am building a form to process text input, multiple check boxes and 4 images. currently I am to process the check boxes using the each function to put all the values of the checkboxes in an array before sending it through ajax. Now the problem is that I can't send the images with ajax too. And also I can't access the images too.
Code:
$(document).ready(function () {
//alert("this page works");
$('#uploadProperty').on('submit',function (e){
e.preventDefault();
var hname = $('#hname').val();
var location = $('#location').val();
var htype = $('#htype').val();
var rooms = $('#rooms').val();
var price = $('#price').val();
var hdetails = $('#hdetails').val();
var feature = [];
$('.feature').each(function() {
if($(this).is(":checked")){
feature.push($(this).val());
}
});
// if (feature.length == 0)
// alert("Select atleast 1 Feature");
// else{
// feature = feature.toString();
// alert(feature);
// }
var file1 = $('#file4').val();
//alert(file1);
$.ajax({
url : 'core/upload.php',
type : 'POST',
data : new FormData(),
contentType : false,
processData : false,
success : function (ep){
alert(ep);
}
});
});
});
You need to upload images first via ajax ( ex: http://hayageek.com/docs/jquery-upload-file.php ) and after make another ajax for the form fields. But you need an ID link between Property and images. you cand add an empty record and remember the mysql_insert_id to make update with the form fields and insert images or update ( depend how is your table structure )
So if i got it right, you want to fill the FormData object. Because currently it's empty.
You can use append method:
var formData = new FormData();
var $myField = $('#myField');
formData.append('myField', $myField.val());
To append file:
var $fileField = $('#fileField');
var myFile = $fileField.get(0).files[0];
formData.append('myFile', myFile);
To append multiplie files you should set the name properly:
formData.append('myFile[]', myFileFirst);
formData.append('myFile[]', myFileSecond);
Check it here: Uploading multiple files using formData()
Also, you can grab the whole form data through constructor:
var form = $('form').get(0);
var formData = new FormData(form);

JQuery Ajax Calls -- Intermittent image display issues (Chrome & FF) (some PHP and MySQL)

I use JQuery to pull form data and send an XMLHttpRequest(); I open the request using the POST method. The image and supplementary data are passed to a PHP script that handles, resizes, and saves it to the server. The file name and location of the image are updated in the relevant fields in a MySQL database. On the uploadComplete(evt) I attempt to display the newly uploaded image by calling .load() to populate a div.
80% of the time, the image displays correctly when the content is loaded into the div. 20% of the time, the image is displayed as if the link provided were a broken link. However, if I refresh the page, the image is displayed correctly.
Why does the image sometimes show as a broken link?
How do I stop it from doing this?
* EDIT
function loadFile()
{
var fileURL = $( "#url" ).val();
if(fileURL == "")
{
// Retrieve the FileList object from the referenced element ID
var myFileList = document.getElementById('upload_file').files;
// Grab the first File Object from the FileList
var myFile = myFileList[0];
// Set some variables containing the three attributes of the file
var myFileName = myFile.name;
var myFileSize = myFile.size;
var myFileType = myFile.type;
// Let's upload the complete file object
imageUpdate(myFile);
}
else
{
var newinfo = new Array();
newinfo[0] = "URL";
newinfo[1] = fileURL;
imageUpdate(newinfo);
}
}
function imageUpdate(newinfo)
{
var formData = new FormData(); // data object
// extra
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
formData.append("stylistID", stylistID);
// IF URL
if ( newinfo[0] == "URL" ){
formData.append("type", "URL");
formData.append("url", newinfo[1]);
}
// IF LOCAL FILE
else
{
formData.append("type", "FILE");
// Append our file to the formData object
// Notice the first argument "file" and keep it in mind
formData.append('my_uploaded_file', newinfo);
}
// Create our XMLHttpRequest Object
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
// Open our connection using the POST method
xhr.open("POST", "u/stylist_avatar.php", true);
// Request headers
//xhr.setRequestHeader("Content-Type", formData.files[0].type);
// Send the file
xhr.send(formData);
}
// While xhr is in progress
function updateProgress(oEvent)
{
if (evt.lengthComputable)
{
//var progressBar = document.getElementById("progressBar");
//var percentComplete = oEvent.loaded / oEvent.total;
//progressBar.value = percentComplete;
}
else
{
// unable to compute progress information since the total size is unkown
}
}
// onComplete
function uploadComplete(evt) {
//alert("The transfer is complete.");
resetForm($('#uploadImageForm'));
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
$('#uploadImageModal').modal('toggle');
// Reload right div
$( "#editStylistRight" ).load( "u/stylist_lookup.php", {stylistID: stylistID}, function (){});
// Reload stylist list
var index = 0;
var numRecords = 10;
$( "#stylistTable" ).load( "u/stylist_lookuptable.php", {start: index, end: numRecords}, function (){});
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
It seems that you are trying to show the new image before the PHP script in fact create and save the new image.
Instead of calling the javascript function that loads the new image on the "uploadComplete", use the "success" param (if you are using jQuery $.ajax function) that call the function that loads the new image.
The "success" function is called only when the server finish processing the request (when the PHP script finish editing and saving the image) and not when the new image params were succesfully sent to the server.
This happens because of image cache,force browser to fetch image evrytime.
use this in uploadcomplete event
var timestamp = new Date();
timestamp = timestamp.getTime();
imageurl+'?t='+timestamp;

How to add a PHP template to a dynamically generated Javascript code

I'm using Code Igniter and the Googlemaps library. This library generates a lot of Javascript code dynamically, including the contents of the InfoWindows for each new marker, but I'd like to keep that in a separate template file, like a regular View.
I have this Javascript code (from Googlemaps' library):
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var windowContent = "";
if( _new ) {
var newIW = new google.maps.InfoWindow( { content: windowContent } );
What I want to do is to load windowContent from a template file. I have already succeeded in dynamically generating a form for this variable and using lat and long variables defined just above, but how can I achieve this in Code Igniter? I can't use load->view because I'm not in a Controller's context. And I cannot use include() or readfile() either because of CI's security constraints.
Any hints?
Using pure javascript, get the lat and long, make a url with the lat and long in the query string, and use xhr to do the ajax call.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var xhr;
var url = "http://myurl.to/script.php?lat="+lat+"&lng="+long;
if(typeof XMLHttpRequest !== 'undefined')
xhr = new XMLHttpRequest();
else {
//Get IE XHR object
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
}
}
xhr.onreadystatechange = function(){
//This function is called every so often with status updates
//It is complete when status is 200 and readystate is 4
if(xhr.status == 200 && xhr.readyState === 4) {
//Returned data from the script is in xhr.responseText
var windowContent = xhr.responseText;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
};
xhr.open('GET', url, true);
xhr.send();
if using a library like jQuery it would be like
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var url = "http://myurl.to/script.php";
jQuery.ajax({
"url":url,
"data":{ //Get and Post data variables get put here
"lat":lat,
"lng":long
},
"dataType":"html", //The type of document you are getting, assuming html
//Could be json xml etc
"success":function(data) { //This is the callback when ajax is done and successful
//Returned data from the script is in data
var windowContent = data;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
});

Passing a image size variable using Javascript to a PHP page

I am trying to send a canvas drawing to the server using javscript.
Having a function such as :
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
window.location = "myPHPfile.php?imageData=" + imgData;
}
What would the best way to pass the imgData variable to the php page due to its large size.
Thanks in advance!
User post request to pass large data. You can use jQuery post method
$.post('myPHPfile.php', { imageData: imgData }, function(data) {
// completed
});
Or create and post form:
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
var form = document.createElement('form');
form.method = "POST";
form.action = "myPHPfile.php";
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = 'imageData';
hidden.value = imgData;
form.appendChild(hidden);
document.body.appendChild(form);
form.submit();
}

pass xmlhttp.responseText data to php variable

i have a jquery that brinds text from a page through ajax and displays that text in a div
i want to pass that data to a php variable how can i do that ?
my jquery code is
<script type="text/javascript">
var xmlHttp = null;
window.onload = function() {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "abc.php", true);
xmlHttp.onreadystatechange = onCallback;
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.send(null);
}
function onCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
document.getElementById('show').innerHTML=xmlHttp.responseText;
}
}
}
</script>
here i want to save xmlhttp.responseTexrt in a php variable in the same file how i can do that ?
Javascript is executed on the browser, and php is executed in the web server. You can not directly pass values from javascript to php.
Therefore, you need to make another ajax call (POST) from javascript to the web server that sends the xmlHttp.responseText, and write php code in the server to store the value to database.
Pass your data in URL,
var data = "somedata";
xmlHttp.open("GET", "abc.php&send=" + data, true);
For Passing a serialized array, first convert it into string
var send = toString(array);
xmlHttp.open("GET", "abc.php" + send, true);
For storing array to PHP variable use $receive = explode(',',$_POST['send']);

Categories