How do I pass JQuery values to next PHP page? - php

Background info: I am using Spectrum.js http://bgrins.github.io/spectrum/ for a color picker. To utilize this within a form it is set as input type text. This is used in the form to pass the color to a php parser that then passes the value to be combined with a .pov povray file that is then rendered on a unix box.
I am trying to pass the value from this color picker to the next php page. I've spent hours trying to find a solution and came up with nothing.
The weird thing is I am 'alerting' the values out to my tester_done.php page and I can see the correct values in the alert. This works when I have the button just function as a button. When I change the button type to submit though it no longer works. I want to see the values of the color picker when I click submit. Any help is greatly appreciated as I'm pulling my hair out! I just want the values from tester.php to post to tester_done.php and I have no idea why it's not working when I have it alert I get the right values, but when I try to change the button to submit so that values post all I get is rgb<0,0,0>.
Code for tester.php:
<form action="tester_done.php" method="post">
<input type='text' class = "basic" name ="field1" id = "field1"/>
<input type='text' class = "basic2" name ="field2" id = "field2"/>
<input type="button" value="Submit" id="send">
</form>
<script type="text/javascript">
$(".basic").spectrum({
preferredFormat: "rgb",
color: "#ffcccc"
});
$(".basic2").spectrum({
preferredFormat: "rgb",
color: "#ff0"
});
jQuery(function(){
var field1 = $('#field1');
var field2 = $('#field2');
$('#send').click(function(){
jQuery.ajax({
type: "POST",
url: "tester_done.php",
data: {field1value: field1.val(), field2value: field2.val()},
dataType: "html",
success: function(data){
alert(data);
}
});
});
});
</script>
Code for tester_done.php:
<?php
$base_value=255;
$characters = array("(", "r", "g", "b", ")");
$field1value = isset($_POST['field1value'])? $_POST['field1value'] : '';
$nfield1value = str_replace($characters, "", $field1value);
$nsfield1value = $nfield1value;
$nsf1arr = array_map("intval", explode(", ", $nsfield1value));
$c_body_r = $nsf1arr[0] / $base_value;
$c_body_r_round = round ($c_body_r, 6);
$c_body_g = $nsf1arr[1] / $base_value;
$c_body_g_round = round ($c_body_g, 6);
$c_body_b = $nsf1arr[2] / $base_value;
$c_body_b_round = round ($c_body_b, 6);
$c_body = "rgb<".$c_body_r_round.", ".$c_body_g_round.", ".$c_body_b_round.">";
echo $c_body;
$field2value = isset($_POST['field2value'])? $_POST['field2value'] : '';
$nfield2value = str_replace($characters, "", $field2value);
$nsfield2value = $nfield2value;
$nsf2arr = array_map("intval", explode(", ", $nsfield2value));
$c_top_r = $nsf2arr[0] / $base_value;
$c_top_r_round = round ($c_top_r, 6);
$c_top_g = $nsf2arr[1] / $base_value;
$c_top_g_round = round ($c_top_g, 6);
$c_top_b = $nsf2arr[2] / $base_value;
$c_top_b_round = round ($c_top_b, 6);
$c_top = "rgb<".$c_top_r_round.", ".$c_top_g_round.", ".$c_top_b_round.">";
echo $c_top;
?>

You dont need JQuery! "< form action="tester_done.php" method="post">" Takes care of posting the data contained within the input tags of the form.
But, incase you want an ajax response, i will suggest getting rid of the action attribute, and using .serializeArray() in the data field of your $.ajax call to pass the data in the form as url parameters.
Possible Usage: Given that form id="NewForm", $.ajax({type: "POST",
url: "tester_done.php",
data: $('#NewForm').serializeArray(),dataType: 'html',success: function(data){alert(data);}});
NOTE: The name of the parameters passed is the same as that of the input tags in your html form, i.e for field1 input, $_POST['field1'] in tester_done.php, when using this method.

You can use submit as well:
$('form').submit(function(){
jQuery.ajax({
type: "POST",
url: "tester_done.php",
data: {field1value: field1.val(), field2value: field2.val()},
dataType: "html",
success: function(data){
alert(data);
}
});
});
You can also make the button a simple button (not submit) as before, then submit the form with JavaScript:
$('#send').click(function(){
jQuery.ajax({
type: "POST",
url: "tester_done.php",
data: {field1value: field1.val(), field2value: field2.val()},
dataType: "html",
success: function(data){
alert(data);
}
});
$('form').submit();
});

Related

AJAX How to use key:value

My form:
<form action="html_post.php" method="post" id="myform">
<textarea id="textarea" placeholder="Add your comment" name="posting"> </textarea>
<input class="button" type="button" name="send" value="Send">
</form>
I have such code
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: {
text: content,
action: "add_post"
},
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
And such php:
echo mysqli_error($connection);
if (strlen($_POST['posting']) >= 5) {
$text = htmlspecialchars($_POST['posting']);
$insert = "INSERT INTO post(content) VALUE ('$text')";
mysqli_query($connection, $insert);
}
But it does not add text to db. I'm just learning ajax and it's my first experience with key:value so can you help me?
And yep, there is no shown errors
The way you've written it, there is no $_POST['posting']. Instead, $_POST['text'] contains a URL-encoded string containing all the inputs in the form, i.e. a string like "posting=blah blah blah".
What you probably want is:
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: content + '&action=add_post',
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
Based on your posted code, on the server there will be two keys set in the $_POST variable. These are the ones that you define at your ajax request in javascript: text and action.
So while you check $_POST['posting'] it does not exists, but there are $_POST['text'] and $_POST['action']. $_POST['text'] will contain all the form fields as an URL-encoded string, like "posting=xyz". In order to access these values, you could use the parse_str() php function that parses this string as it were a query string.
So the condition at the server side could be something like as follows.
if (isset($_POST['text'])) {
// $formdata passed in by reference, it will contain all the form fields
parse_str($_POST['text'], $formdata);
}
if (isset($formdata['posting']) && strlen($formdata['posting']) >= 5) {
// Perform db operation
}

How to post more than 1 var’s with ajax

I've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.

Submit Form Array Via AJAX

I have a form which I would like to submit via Ajax, however, part of it contains an array. I am having difficulty passing this array via Ajax. An example of my Ajax is below, where I would usually pass the form entry data via how it is below after data (one: $('#one').val()) where I would have one row of this for each field.
Now I have a new set of fields, where the information needs to be passed through as an array. I have tried using serialize and formData -- var fd = new FormData("#form") -- and so far either just this array has been passed through, or nothing from the form is passed through, or just the array is not passed through.
Can anyone please point me in the right direction?
$("#form").submit(
function() {
if (confirm('Are you sure you want to edit this?')) {
$("#formMessages").removeClass().addClass('alert alert-info').html(
'<img src="images/loading.gif" /> Validating....').fadeIn(500);
$.ajax({
url: $("#form").attr('action'),
dataType: 'json',
type: 'POST',
data: {
one: $('#one').val(),
two: $('#two').val()
},
success: function(data){
//success stuff would be here
}
});
}
return false;
});
Thanks.
You could try using :
var dataSend = {};
dataSend['one'] = $('#one').val();
dataSend['two'] = $('#two').val();
dataSend['three'] = $('#three').val();
then in the ajax
data: {dataSend:dataSend}
You can gather data in php with json:
$json = json_encode($_POST['dataSend']);
$json = json_decode($json);
print_r($json);
To see output.
Edit:
You can gather data in php like below:
$one = $json->{'one'};
$two = $json->{'two'};
Have you tried this:
Written in JavaScript:
your_array = JSON.stringify(your_array);
And in PHP:
$array = json_encode($_POST['array']);

onchange F(x) to php to Highchart on same page

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Jquery Serialization not working

Have a simple form (only extract fields here) but for some reason the JQserilization is not working; looks fine in alert() but only the first form field gets posts. Suggestions please - thanks in advance
Form:
<form id="neweventform" method="post" action="">
<div class="grid_4 alpha">Setup date *</div>
<div class="grid_7 omega">
<select name="setup_day" id="setup_day"><?php days_list(); ?></select>
<select name="setup_month" id="setup_month"><?php month_list(); ?></select>
<select name="setup_year" id="setup_year"><?php year_list(); ?></select>
<div class="grid_11">
<input type="submit" name="createevent" value="Create" id="createevent" />
</div>
</form>
Jquery
$j(document).ready(function(){
$j('#neweventform').live('submit',function () {
var data= $j('#neweventform').serialize();
alert(data);
$j.ajax({type: "POST", url: "scripts/process.php",data: "newevent=newevent&event_options=" + data, cache: false, complete: function(data){
$j('#neweventform').fadeOut(2000),loading.fadeOut('slow'),$j('#content').fadeIn(2000), $j('#content').load('scripts/events.php #eventslist');
}
});
return false;
});
});
And the PHP processing
if(isset($_POST['newevent'])) :
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('".$_POST['event_options']."')");
endif;
Any suggestions?
Have a look how serialize() works. It creates a string that, in your case, should look like this:
"setup_day=foo&setup_month=bar&setup_year=baz"
Then you concat this string with another (as data), which results in an invalid parameter string:
data: "newevent=newevent&event_options=" + data
// gets
"newevent=newevent&event_options=setup_day=foo&setup_month=bar&setup_year=baz"
Depending what type event_options is in your database (from the data in your form I assume it is a field containing a date), you might want to do this:
Javascript:
data: "newevent=newevent&" + data
PHP (sanitize the user input!):
if(isset($_POST['newevent'])) :
$date = $_POST['setup_year']. '-' . $_POST['setup_month'] . '-' . $_POST['setup_day'];
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('". $date . "')");
endif;
first. Try doing a simple
<?php
print_r($_POST);
?>
to see what are you getting on the post var.
Second. Rename your parameter
var data
to something more "exclusive"
I don't recall at the moment if you can have a conflict with the "data" symbol used to make the call but at least you can start debugging from here.
Your data will be serialized into something like this:
setup_day=1&setup_month=2&setup_year=2010
You then construct your data like this:
newevent=newevent&event_options=setup_day=1&setup_month=2&setup_year=2010
This query string is wrong (two '=' without an '&') and probably this the root of your problem.
Try this:
$j.ajax({
type: "POST",
url: "scripts/process.php",
data: { newevent: newevent, event_options: $j('#neweventform').serialize() },
cache: false,
complete: function(data) {
...
}
});
OK, tried a mix of, but eventually got this to work:
$j(document).ready(function(){
$j('#neweventform').live('submit',function () {
var optdata= $j('#neweventform').serialize();
$j.ajax({
type: "POST",
url: "scripts/process.php",
data: "newevent=" + $j('#neweventform').serialize(),
cache: false,
complete: function(data) {
$j('#neweventform').fadeOut(2000),
loading.fadeOut('slow'),
$j('#content').fadeIn(2000),
$j('#content').load('scripts/events.php #eventslist');
}
});
return false;
});
});
then in the PHP
if(isset($_POST['newevent'])) :
$tryit = serialize($_POST);
$insert = mysql_query("INSERT INTO events (event_options) VALUES ('".$tryit."')");
endif;

Categories