Javascript + Load AJAX function on page load + Pass Javascript vars to PHP - php

I have again a little problem with a javascript (i am a real noob regardin that). This time I would like to load an AJAX function on page load in order to save some javascript variables to php sessions. I figured out thats the best way to pass javascript vars to php. If there is a better way (besides cookies), dont hesitate to let me know :)
For now I would like to:
-pass javascript variables to an external php page on page load
-save variables in php
-use the php variables without pagereload
Here is my script so far:
$(document).ready(function () {
function save_visitor_details() {
$(function() {
var visitor_country = geoip_country_name();
var visitor_region = geoip_region_name();
var visitor_lat = geoip_latitude();
var visitor_lon = geoip_longitude();
var visitor_city = geoip_city();
var visitor_zip = geoip_postal_code();
var dataString = 'visitor_country='+ visitor_country +'&visitor_region='+ visitor_region +'&visitor_lat='+ visitor_lat +'&visitor_lon='+ visitor_lon +'&visitor_city='+ visitor_city +'&visitor_zip='+ visitor_zip;
$.ajax({
type: "POST",
url: "inc/visitor_details.php",
data: dataString,
success: function(res) {
alert ("saved");
//$('#result').html(res);<-- should contain variables from inc/visitor_details.php
});
}
});
return false;
}
});
Thanks in advance!
Edit: I changed it a little and got it to work by adding the javascript variables into a hidden form, submit the form with the ajax script above and save variables into php session array at the backend php file.Thanks any1 for your time!!!

I don't really understand what is the question here. But here are a few advices.
rather than serializing the data yourself, you should rather let jQuery do that for you:
$.post('inc/visitor_details.php', {country: geoip_country_name() /* stuff */}, function(data) {
alert('ok!'); alert(data);
});
be aware that, by passing data to your server using Javascript, users can send whatever data they want, including fake data. So handle it with care.
Then entire process may looks like this:
/* javascript */
$(document).ready(function() {
function save_visitor_details() {
$.post('inc/visitor_details.php', {
country: geoip_country_name(),
region: geoip_region_name(),
lat: geoip_latitude(),
lon: geoip_longitude(),
city: geoip_city(),
zip: geoip_postal_code()
}, function(data) {
/* do whatever you want here */
alert(data);
}, 'json');
}
save_visitor_details();
});
/* PHP */
<?php
$keys = array('country', 'region', 'lat', 'lon', 'city', 'zip');
$output = array();
foreach($keys as $key) {
do_some_stuff($_POST[$key]);
$output[$key] = $_POST[$key];
}
header('Content-type: text/plain; charset=utf-8');
echo json_encode($output);
?>

JavaScript:
var http = createRequestObject() ;
function createRequestObject(){
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(str){
http.open('get', str);
http.onreadystatechange = handleResponse;
http.send(null);
}
sendReq("someurl?var=yourvar");
Php:
$var = $_GET['var']; // use some security here.

Related

Ajax not passing values to php

I have been working this crap for many weeks.
This PHP Ajax CRUD is such a pain in the head. That's why I prefer WordPress than this crap.
I tried my examples from the internet given that this is such a simple stuff but this garbage ajax doesn't want get fixed.
This crap can't even get a value I put in the variables. Sighhhhh
Ajax file:
function save_row(id)
{
var product_name=document.getElementById("product_name_val_"+id).value;
var description=document.getElementById("description_val_"+id).value;
var serial_number=document.getElementById("serial_number_val_"+id).value;
var date_delivered=document.getElementById("date_delivered_val_"+id).value;
var warranty_expiration=document.getElementById("warranty_expiration_val_"+id).value;
var dr_number=document.getElementById("dr_number_val_"+id).value;
var reports=document.getElementById("reports_val_"+id).value;
var reported_data=document.getElementById("reported_data_val_"+id).value;
var replaced_unit_serial_number=document.getElementById("replaced_unit_serial_number_val_"+id).value;
var replacement_data=document.getElementById("replacement_data_val_"+id).value;
var remarks=document.getElementById("remarks_val_"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
product_name_val:product_name,
description_val:description,
serial_number_val:serial_number,
date_delivered_val:date_delivered,
warranty_expiration_val:warranty_expiration,
dr_number_val:dr_number,
reports_val:reports,
reported_data_val:reported_data,
replaced_unit_serial_number_val:replaced_unit_serial_number,
replacement_data_val:replacement_data,
remarks_val:remarks
},
success:function(response) {
if(response=="success")
{
document.getElementById("product_name_val_"+id).innerHTML=product_name;
document.getElementById("description_val_"+id).innerHTML=description;
document.getElementById("serial_number_val_"+id).innerHTML=serial_number;
document.getElementById("date_delivered_val_"+id).innerHTML=date_delivered;
document.getElementById("warranty_expiration_val_"+id).innerHTML=warranty_expiration;
document.getElementById("dr_number_val_"+id).innerHTML=dr_number;
document.getElementById("reports_val_"+id).innerHTML=reports;
document.getElementById("reported_data_val_"+id).innerHTML=reported_data;
document.getElementById("replaced_unit_serial_number_val_"+id).innerHTML=replaced_unit_serial_number;
document.getElementById("replacement_data_val_"+id).innerHTML=replacement_data;
document.getElementById("remarks_val_"+id).innerHTML=remarks;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
PHP file:
<?php session_start();
include_once('../includes/config.php');
if(isset($_POST['edit_row']))
{
if(isset($_GET['uid'])) {
$userID=$_GET['uid'];
$row=$_POST['row_id'];
$product_name=$_POST['product_name_val'];
$description=$_POST['description_val'];
$serial_number=$_POST['serial_number_val'];
$date_delivered=$_POST['date_delivered_val'];
$warranty_expiration=$_POST['warranty_expiration_val'];
$dr_number=$_POST['dr_number_val'];
$reports=$_POST['reports_val'];
$reported_data=$_POST['reported_data_val'];
$replaced_unit_serial_number=$_POST['replaced_unit_serial_number_val'];
$replacement_data=$_POST['replacement_data_val'];
$remarks=$_POST['remarks_val'];
mysqli_query("update devices set uid='$userID' product_name='$product_name',description='$description',serial_number='$serial_number',date_delivered='$date_delivered',warranty_expiration='$warranty_expiration',dr_number='$dr_number',reports='$reports',reported_data='$reported_data',replaced_unit_serial_number='$replaced_unit_serial_number',replacement_data='$replacement_data',remarks='$remarks' where id='$row'");
echo "success";
exit();
}
}

Cannot store localstorage values via AJAX

Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}

jQuery Array to PHP

I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php

How do I send and receive vars with jquery and AJAX?

so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);

PHP - AJAX Process HTTP requests

I have a form with x number of fields. When submitted, I want to;
get all input data, $var = $_POST['input']
validate input, (!empty($var) && is_numeric($var))
stick it in an array, array_push($myArray, $var)
generate URLS, $url.=$var
process the URL's without leaving the page
1 - 4 already done in php
Simply, im not familiar with Ajax. Been a decade since ive touched Javascript. Im not sure if i should be using javascript to do the whole process. However, would prefer php to validate, Ajax to do http requests. Any sample code/sites available that passes php var's/array to Ajax to handle http requests?
You'll want to use some kind of format to pass data from the server to the client. I recommend JSON. PHP has a built-in function to encode an array into it, and JavaScript parses it natively.
As for the AJAX part itself, I recommend using a framework like JQuery. Makes it way simpler, and you don't have to deal with the different browsers yourself.
$.ajax({
url: "yourpage.php",
success: function(data){
alert(data);
}
});
I guess something like this-
$urlfield = explode(",", $urls);
You want to pass this array via jQuery AJAX, with this:
<form id="myForm">
<input type="hidden" value="'.$urlfield.'">
<input type="submit" id="processURL" class="Submit" name="ok" value="Send Reply"/>
</form>
And here's your jQuery:
$("#processURL").click(function(event){
event.preventDefault();
var urlUsed = $("#urlfield").val();
$.ajax(
{
type: "POST",
url: urlUsed,
data: ,// you can send some data
beforeSend: function() {
$("#processingURL").show(); //SOME FUNCTION TO SHOW URL PROCESSING
},
success: function() {
alert("Success");
}
});
});
// browser support code
function getXMLHTTP()
{ //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
// external file to linkup
function secondpage(countryId) {
var strURL = "secondpage.php?country=" + countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('sid').innerHTML = req.responseText;
} else {
document.getElementById('sid').innerHTML = req.responseText;
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
in secondpage.php page ( i will get $_REQUEST['country'];)

Categories