jQuery Array to PHP - 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

Related

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 post data to a php script and display it immediately in the same php script file

How to post data to a php script (showitemid.php) using ajax and open the same script (showitemid.php) immediately in a thickbox on a hyperlink click and display that posted data. Below is my code:
postitemid.php
This file consists of multiple check-boxes. The user will tick the checkboxes and click a hyperlink. On clicking the hyperlink all the selected check-box values would be posted to showitemid.php and then immediately showitemid.php would open in a thickbox and display the received values. But it isn't receiving any values in my code ? Need help.
$('#showitem).click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
$.ajax({type: 'POST',
url: 'showitemid.php',
data: data,success: success,dataType: dataType});
});
showitemid.php
$data = '';
if (isset($_POST['data']))
{
$data = $_POST['data'];
}
elseif (isset($_GET['data']))
{
$data = $_GET['data'];
}
echo 'd='.$data;
use something like this
$('#showthickbox').click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();//your code
$.post("showitemid.php",{data:data},function(data){
$("#thickbox").html(data);
})
})
})
in your showitemid.php
echo "your data";
The main problem with the original code is the data being sent has no key named data to match $_POST['data']) so $_POST['data']) is empty. You have to send key/value pairs, you are only sending a value with no key. You are likely getting a bit confused since you use the same variable name constantly
var dataArray = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
var dataToServer= { data : dataArray} /* now have the key to match $_REQUEST in php */
Now can use AJAX shorthand method load() to populate content
$('#myContainer').load( "yourfile.php", dataToServer, function(){
/* new html exists run open thickbox code here*/
})

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

Javascript + Load AJAX function on page load + Pass Javascript vars to 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.

Jquery get all input values and create an array (with names)

Hay guys, I'm doing some work where i have a large collection of forms. Seems these aren't 'posted' the traditional way (i.e using a submit button). I need a way to collect all the names and values of all form data when clicking a link (document.location is then used for redirects).
I want names to stay intact so that i can used a simple PHP script to work with the data.
any suggestions?
Might I suggest Serialize Form to JSON:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and then you can do:
var formArray = $("#myform").serializeObject();
$.fn.valuesArr = function()
{
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
USE:
var myArr = $('input', $parentJQelem).valuesArr();
You could use something like my submit helper as a base
function submit(form) {
var form = $(form);
$.ajax(
{ data: $.param( form.serializeArray()),
dataType:'script',
type:'post',
url: form.attr("action")});
}
instead of a 'serializeArray()' i would use 'serialize()' and instead of posting it using ajax you could do whatever you want.
Sorry, dont have more time right now, but hopefully this snippet helps you.
cletus's answer is the best one in terms of efficency.
This is however another working solution that does not rely on JSON:
//this is my object I will fill my array with
function myObject(name, value)
{
this.name = name;
this.value = value;
}
var arr = $.map(
$('span'), function (item) {
var $item = $(item); //no need to $(item) 2 times
return new
myObject(
$item.attr("name"), //name field
$item.text() //value field
);
}
);
arr will be an array of myObject, each of them containing a name property and a value property.
Use your selector instead of $('span').
but all this functions dont work witch array names in inputs.
example -
this is correct for submit post form but when serialize i get
form[type[]]:2
this is not correct - i need - form[type][]:2

Categories