How to pick up JSON in PHP from Jeditable Script - php

I want to create a jeditable text area that posts the values entered in to a database and then returns the new value to the div that replaces the textarea. I found this on Stackoverflow that handles returning the new value to the div.
$(document).ready(function() {
$('.edit_area').editable(submitEdit, {
indicator : "Saving...",
tooltip : "Click to edit...",
type : "textarea",
submit : "OK",
cancel : "Cancel",
name : "Editable.FieldName",
id : "elementid",
});
function submitEdit(value, settings)
{
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
edits[settings.name] = [value];
var returned = $.ajax({
url: "http://jimmymorris.co.uk/xmas/record_xmas_msg.php",
type: "POST",
data : edits,
dataType : "json",
complete : function (xhr, textStatus)
{
var response = $.secureEvalJSON(xhr.responseText);
if (response.Message != "")
{
alert(Message);
}
}
});
return(result);
}
});
My problems is I don't know what my POST vars are called so I can insert in to my db. Does it even return POST var to php or does it send php json and how do I know what that is called?
Please help, Cheers in advance.

What it sends to the server depends on what you supply to the "post" mamber of the $.ajax options paremeter.
If you pass a query string parementer data : "name=foo&surname=bar" The PHP script would recieve it in the $_POST variable and could be accessed by means of $_POST['name'] $_POST['surname']
However if you passed an object to the data parameter it would be changed to a query string i.e
data : {name : 'foo', surname : 'bar'},
JQuery.ajax would change it into a query string like the example above then It would be sent to the server, and the PHP script would also access it same as mentioned above.
P.S I highly recommend using some type of encoding when sending data to the server, encodeURIComponent(variable) and accordingly decode it in PHP by using urldecode.

You have the id posted which you can retrieve in the PHP page as $_POST['id']. The text is posted as value which you can retrieve in the PHP page as $_POST['value']. You can of course change the default names.

Related

Serialized form data via ajax only returns one letter ("r")

I have a form that I am submitting via ajax to a php function like so:
var formData = $(form).serialize();
$.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl, //we can use this value because in our php file we used wp_localize_script
context:this,
data : {action: 'tps_save_rental_details', formData:formData },
success: function(response) {
alert (response.testing);
}
});
I thought that by using .serialize() it would pass the form data in json form and then I could use it in my php function like so:
$formData = $_REQUEST['formData'];
$rentalType = $formData['rentalType'];
$result['testing'] = $rentalType;
(rental type is the name/id of the first text input field)
But when I alert the returned value of $results['testing'] in my ajax success function I just get one character, the letter "r" which doesn't even appear in the value of that field (which is "class-education").
Is this the best way to pass form input values via ajax? If so, what might I be doing wrong here.
The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"
You can get these values in php like:
$params = array();
parse_str($_GET, $params);
Specific to the OP's case:
$formData = array();
parse_str($_REQUEST['formData'], $formData);
$result['testing'] = $formData['rentalType'];

php - how to access object passed through jquery ajax

I have a javascript object like below
var customerinfo = {
customer_name : $('#customer_name').val(),
customer_address: $('#customer_address').val(),
customer_city : $('#customer_city').val(),
customer_state : $('#customer_state').val(),
customer_zip : $('#customer_zip').val(),
};
Then I try to pass that to php using $.ajax like below
$.ajax({
url: "../folder/file.php",
type: "POST",
data: {
'customerinfo' : customerinfo,
},
success:function(){
window.location = "file.php";
}
})
In php I try to print the object out
$customerinfo = json_decode($_POST['customerinfo']);
print_r($customerinfo);
or
$customerinfo = $_POST['customerinfo'];
print_r($customerinfo);
I get undefined index customerinfo
I also tried to json.stringify in the javascript before passing it but get same error.
I found a very similar post such as
jquery ajax object array php but I couldnt get the code to work either.I think the ajax was able to pass the data through, just I dont know how to decode it on the php side.
I know I could just post it from html submit button, but This is simplified testing for a larger issue where I want to pass object that have many objects inside of it using jquery.
if the javascript side is correct, the question is "how to access objects passed through jquery ajax in PHP."
if not, the question would be "how to pass objects from javascript to php."
from what i see the problem might be in the data.
try posting with static data, meaning replace the
var customerinfo = {
customer_name : $('#customer_name').val(),
customer_address: $('#customer_address').val(),
customer_city : $('#customer_city').val(),
customer_state : $('#customer_state').val(),
customer_zip : $('#customer_zip').val(),
};
with
var customerinfo = {
customer_name : 'ddd',
customer_address: 'ddd',
customer_city : 'ddd',
customer_state : 'ddd',
customer_zip : 'ddd'
};
also try sending the ajax from the browser console, that way you'll be able to see the data being posted

how to use jquery variable in php to insert into database

hello in the following code variable checked_num contains the integer value like 1,2,.
now i want this value in database using php code using mysql insert query..
the jquery code i have is:
<script type="text/javascript">
// function for counting check boxes
$(document).ready(function (){
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
});
});
now i want that variable "checked_num" is accessed in php code so i can insert this variable value into database
Have you readed the jQuery ajax/post/get ?
You can use ajax to update your database.
EG:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.ajax({
type: 'POST',
url: 'yourpage.php', //this page inserts your data in database
data: {'checked_num': checked_num},
success: function(response){
//do whatever you want on success
},
error: function(xhr, status, errorThrown){
//handle ajax error
}
});
});
You can also use $.get() or $.post() instead of $.ajax().
You can use jQuery's $.post() method:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.post('myPHPScript.php', { checked : checked_num }, function(data) {
/* data is the response you receive from the server. */
});
});
Here "checked" is the name of the post variable you're sending over. If you wanted to post a string named "myString" containing the text "Hello, world!", for example, you'd use { myString : "Hello, world!" }. This is an object, meaning multiple variables can be sent over by separating each with a comma.
In PHP you'd then retrieve this using $_POST:
<?php
$checked = $_POST['checked'];
?>
You'd probably want to encode this post data however before inserting it into your database.
As for how to insert the data into your database, check out PDO or mysqli.
You are using javascript to set a flag if one or more of the HTML checkboxs in your form are checked.
So you already have a <form> on the page.
When you submit the form you can access that information directly using PHP
All you have to remember is that checkboxes are only submitted back to the server PHP code if they ARE checked. So all you need to do is test for their existance.
if ( array_key_exists( 'checkbox_name', $_POST ) ) {
// this check box is checked
} else {
// this checkbox is not checked
}

Passing HTML INPUT field ID to PHP completion program in jQuery Autocomplete

I want to pass the id of the INPUT field to the PHP file providing options. Here's my HTML & jQuery code. But the PHP program gets the id as undefined. Thanks for helping.
jQuery :
$('.classfield').autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+$(this).attr('id')+"&callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add(suggestions);
});
},
//define select handler
change: function(e) {
$("#spill").html("change "+$(this).val()+e.type);
}
}); // autocomplete
HTML:
<input type="text" class="classfield" id="hello" value="there"></input><br>
the value of $(this).attr('id') is undefined because this is the object that is put in the parameter of autocomplete (the parameter of autocomplete accepts an object, so if you use $(this).attr('id'), you are referencing the object that was passed in the parameter on the autocomplete)
therefore you cannot use $(this).attr('id').
You have to store the id of the text field, may be as a global variable... Hope this helps a little bit
Try getting the id from this.element:
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+this.element.attr('id')+"&callback=?", req, function(data) {
Also see this example.

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

Categories