How do i change this into JSON? - php

How can I send multiple values to be picked up like this using JSON?
foreach($_POST['listItem'] as $key => $values){
list($eventDate, $eventTitle) = $values;
}
At the moment the values are sent as follows. But this doesn't appear to work properly as it is only sending some of the string. I also can't figure out where/how to send the caltitle value.
This is sending me crazy. Any help would be great.
var txt = $("#listbox");
var caltitle = copiedEventObject.title
var dtstart = $.fullCalendar.formatDate(copiedEventObject.start, 'yyyyMMdd');
var txt = $('#listbox');
txt.append("<li class ='listItem'> " + dtstart + "</li>")
// remove the element from the "Draggable Events" list
$(this).remove();
}
});
$('#calendarform').submit(function(e) {
var form = $(this);
var listItems = $('.listItem');
listItems.each(function(index){ //For each event do this:
var listItem = $(this);
$("<input type='hidden'/>").val(listItem.text()).appendTo(form).attr('name', 'listItem[' + index + ']');
});
//Get text information from elements
});
EDIT:
(using JSON)
$('#calendarform').submit(function(e) {
var form = $(this);
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':'test',
'title': 'test'
});
});
$('#stuff').val( JSON.stringify(going_to_be_json) );
});

Prepare the data into an array of objects then convert that array to JSON using JSON.stringify() and set the hidden form value to said string (or use XHR to submit it to the server).
Here is a very limited example of how to prepare the data:
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':item.id,
'title': item.title,
'date': (new Date()).now()
});
});
hidden_form_element.val( JSON.stringify(going_to_be_json) );
and on the server
<?php
$json_data_string = $_POST['hidden_form_field_containing_json_data']; // sanitize however
$array_data = json_decode($json_data_string);
More can be ready about JSON (Javascript Object Notation) from json.org and the Tag Wiki (although the tag wiki just shows you more examples and links)
it seems you needed a little more direction. I was hoping you wouldn't just copy and paste what I had and you would read and attempt to understand what it is doing....
$('#calendarform').submit(function(e) {
var form = $(this),
listItems = $('.listItem'),
data = [],
hidden = $('<input />'); // create a hidden field for the form.
// or just select the hidden form element from the page
hidden[0].type = 'hidden'; // set the type
hidden[0].name = 'some_name_for_php_to_recognize'; // and name
listItems.each(function(i,el){
data.push({'index': i, 'text': $(el).text()});
});
hidden.val(JSON.stringify(data));
$(this).append(hidden); // not needed if the hidden element is already in the DOM
});

send it with jQuery Post or Get method and fetch it by php you can send multiple values
use $.post or $.get

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 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*/
})

submit a value from span field

i have a from with a submit button
after using jquery the page will have :
for(var i=0 ; i <10 ; i++){
'<span class="ioAddConcept">'+ currentConcept[i] +'</span>\n\
with\n\
<span class="ioAddRelation">'+ currentRelation[i] +'</span>\n\'
}
(that piece of code is just an example)
the variables currentConcept[] and currentRelation[] i got its values from database using Ajax
**i am using PHP**
and my question how to submit the page with these two variables ?
i mean in the server i hope something to be like this
$concepts = $_POST['currentConcept[]']
Get these values in jQuery like this:
var ioAddConcept = $(".ioAddConcept").html();
var ioAddRelation = $(".ioAddRelation").html();
Now you can set these values into form text boxes:
$('input.ioAddConcept').text( ioAddConcept );
$('input.ioAddRelation').text( ioAddRelation );
OR if you are submit form via AJAX request:
$.ajax({
url : '/path/to/action.php',
type : 'POST',
data : 'value1=' + ioAddConcept '&value2=' + ioAddRelation,
success : function( data ) {
alert(data);
}
});
Get these values on server side:
print_r( $_POST );
Add an ID to your span element
<span id="ElementID"> your variable text here</span>
Then use jquery to get the text out
var spanText = $('#ElementID').html();
Something like that
var currentConcept = $('currentConcept').html();
And then you can send this var as a param in you request to server
Update
$("form").submit(function() {
var currentConcept = $('.currentConcept').html(); // it's an Array
var currentRelation = $('.currentRelation').html(); // it's an Array
$.ajax({
url : // your URL,
data : 'currentConcept=' + currentConcept '&currentRelation=' + currentRelation,
success : function( html ) {
// write your code here
}
});
}
// server side (php)
$currentConcept = $_GET('currentConcept');
$currentRelation = $_GET('currentRelation');

jquery .post elements created with append

I have a code with input field, and with clicking on add it adds new input field with new name:
/* multiply recepient */
var number = 1;
$('a.plus').live('click', function() {
number += 1;
$('.multiple').append('<p><input type="text" name="recepient_' + number + '"></p>');
});
this works fine. But then I want to post entered values with $.post() and only the first input fileld is posted, the original one, all created with append are note posted... Here is my post function:
$('input.submit').live('click', function() {
var postdata = $('form#form1').serialize();
$.post('result.php', postdata, function(data) {
$('div.result').html(data);
});
return false;
});
any ideas?
ok, found the error - has to be outside of .....

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