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;
Related
I hope that you are in good mood :). I'm trying to return data which depend on text from user using AngularJS and php. So I create file php which contain my query and using $http.get in AngularJS. My problem is I want to integrate value of input in mysql query, but always using angular. I tried many times but nothing works To be more clear, here is muy code:
app.js
app1.controller('autoCompleteCTRL',function($scope,$rootScope,$http) {
$scope.search = function(){
$scope.$watch('searchText', function() {
console.log($scope.searchText);
});
$http({
method: "get",
url: "../SearchResultsQuery.php",
dataType: 'json',
data: { 'userText': $scope.searchText},
async: false,
params: {action: "get"}
}).success(function(data, status, headers, config) {
alert(data);
}).error(function(data, status, headers, config) {
alert(error);
});
};
}
index.html
<input type="text" placeholder="Search for items" id="textFiled" class="input" ng-model="searchText" ng-change="search()" />
app.php
<?php
$conn=pgsqlCon();
$searchText = mysql_real_escape_string(userText);
$query='SELECT * FROM planet_osm_roads AS a, to_tsquery_partial(\'%.$searchText.%\') AS query
WHERE ts_road ## query';
$result = pg_query($conn,$query);
$myarray = array();
while ($row = pg_fetch_row($result)) {
$myarray[] = $row;
}
pg_close($conn);
echo json_encode($myarray);
?>
I hope that you understand me Thanks for advance :)
try to make your http request like this:
app.controller('TestCtrl', function ($scope, $http){
$scope.search = function(){
$http.post('../app.php', {searchText: $scope.searchText})
.success(function (response){
console.log(response);
})
.error(function (response){
console.log(response);
});
}
});
app.php
<?php
$data = file_get_contents("php://input");
$searchText = mysql_real_escape_string($data['searchText']);
/* database code */
?>
This should work.
In your app.js file, instead of this line:
data: { 'userText': $scope.searchText}
write:
params: { 'userText': $scope.searchText}
and remove this line:
params: {action: "get"}
This way it will transfer userText variable through request URL as a GET parameter.
In your app.php file, instead of:
$searchText = mysql_real_escape_string(userText);
write:
$searchText = mysql_real_escape_string($_GET['userText']);
This will populate your $searchText php variable with text from client application (AngularJS). I'm not sure about your postgresql query. Your question title is mysql - How to get data..., but in your php code sample you use postgres extension to build query. But that's a different story I guess.
My problem is the following:
I have an ajax function that, according to the option (of a select) selected, associate a record in a database and populate another input, i.e. a p tag.
I have two td tags that have to be populated. Different data has to be displayed, so i want that, according to the input on the first select, on the second td there will be input y, in the third input z and so on... how can it be possible? If i try to append data to more than one tag, the same data is displayed in all the td columns.
Here i attach my code
Main.php
$(document).ready(function() {
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "html",
success: function(msg) {
$("#L_AMT0").html(msg);
$("#L_DESSERV").html(msg);
},
error: function() {
alert("Call failed");
}
});
});
});
Form.php
<label for="L_DESSERV">Descrizione del servizio</label>
<p class="L_DESSERV" id="L_DESSERV"></p>
</td
<td class="h4">
<label for="L_AMT0">Costo del servizio</label>
<p class="L_AMT0" id="L_AMT0"></p>
</td>
elaborazione_dati.php
$tipologia_selezionata = $_POST['L_NAME0'];
$sql = "SELECT * FROM acquisti WHERE durata = '$tipologia_selezionata' ";
$q = $db->prepare($sql);
$q->execute();
$q->setFetchMode(PDO::FETCH_ASSOC);
while($caratt = $q->fetch()) {
echo '<input readonly="readonly" type="hidden" name="L_NAME0" value="'.$caratt['durata'].'"/>';
echo '<input readonly="readonly" type="hidden" name="L_AMT0" value="'.$caratt['prezzi'].'"/>';
echo $caratt['prezzi']; ?> € <?php
}
Any suggestions?
Thanks a lot!
You need to split the results and the easiest way is to return JSON from PHP and then process it on your js code to generate the fields and text.
So in PHP something like:
while($caratt = $q->fetch()) {
$result->durata = $caratt[duratta];
$result->prezzi = $caratt[prezzi];
}
echo json_encode($result);
then in your js something like:
$('#L_NAME0').change(function() {
var L_NAME0 = $("#L_NAME0").val();
$.ajax({
type: "POST",
url: "elaborazione_dati.php",
data: "L_NAME0=" + L_NAME0,
dataType: "json",
success: function(data) {
$("#L_AMT0").html("<input type='hidden' name='L_NAME0' value='"+data.duratta+"'/>"+data.duratta);
$("#L_DESSERV").html("<input type='hidden' name='L_DESSERV' value='"+data.prezzi+"'/>"+data.prezzi+"€");
},
error: function() {
alert("Call failed");
}
});
However it seems confusing that you put another input named L_NAME0 - the id of your select control, but hey, it's your code... :)
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();
});
Page elements are defined like this.
<div id="readf" class="tabbertab">
<h2>First Reading</h2>
<div id='titlefe' class='rtitle'>
</div>
<div id='readfe' class='rtext'>
</div>
</div>
I make an ajax call to a php script to add data to these page elements.
<script>
$('#readings').ready(function(){
$.ajax({
url: "loadenglish.php",
type: "GET",
data: { },
cache: false,
async: true,
success: function (response) {
if (response != '')
{
alert (response);
}
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
});
</script>
The php script gets the data and does a script echo to add the data.
<?php
$titlefe = 'text 1';
$readfe = 'text 2';
echo "<script type='text/javascript'> $('#titlefe').append('".$titlefe."'); $('#readfe').append('".$readfe."'); </script>";
?>
The alert statements shows that the php script gets the right information. But the page elements are not updated. Is there a different way to add $titlefe to element id titlefe?
In addition to what MK_Dev posted you can use PHP function json_encode();
<?php
//loadenglish.php
$params = array(
'titlefe' => 'text 1',
'readfe' => 'text 2',
);
echo json_encode($params);
Also there is a jQuery function $.getJSON(), which is a shortcut for $.ajax() function usage like yours.
Try eval(response); after your alert in the success callback.
Returning javascript methods is not a good idea. You should return data in JSON format and use javascript on the client side to perform the actual update.
Your PHP return statement should look like:
echo "{ 'titlefe': '" + $titlefe + "', 'readfe': '" + $readfe + "' }";
and your success call back should look like this:
success: function(response) {
$('#titlefe').text(response.titlefe);
$('#readfe').text(response.readfe);
}
If you insist on returning JavaScript, you should be using getScript() instead of an Ajax get.
form_page.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="js/process_truck_req.js"></script>
<script src="js/jquery-1.2.3.pack.js"></script>
<script src="js/runonload.js"></script>
</head>
<div class="prform" id ="request_form">
<form name="truckreq" action="" method="post" class="truckreq_form">
<label for="seltruck" id="seltruck_label"><font class="whitetext">Select Truck</font></label><br />
<select name="seltruck" id="seltruck">
<option value="Select a Truck"> Select a Truck</option>
<option value="2011+Tacoma">2011 Tacoma</option>
<option value="2008+Tundra">2008 Tundra</option>
<option value="2000+Tacoma">2000 Tacoma</option>
</select><br />
<label class="error" for="seltruck" id="seltruck_error"><font class="redtext">This field is required.</font></label><br />
<label class="error" for="seltruck" id="seltruck_noavail_error"><font class="redtext">Not Available on selected Dates.</font></label><br />
</form>
process_request.js
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.radio-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var seltruck = $("#seltruck").val();
if (seltruck == "Select a Truck") {
$("label#seltruck_error").show();
$("#seltruck").focus();
return false;
}
var truckSearch = 'seltruck=' + seltruck + '&outdate=' + outdate + '&indate=' + indate;
$.ajax({
type: "POST",
url: "do_truck_search.php",
data: truckSearch,
success: function() {
var truck_status = $("#truck_status").val();
if (truck_status == "nopass") {
$("label#seltruck_noavail_error").show();
$("#seltruck").focus();
return false;
}
}
});
});
});
runOnLoad(function() {
$("input#projdesc").select().focus();
});
Take input form data from form_page.html, pass to process_request.js for validation. I only displayed seltruck, other form fields are set in form_page.html.
At the .js validation, the fields are check if they are filled out, if not, the error label class is displayed on the form_page.html.
The seltruck form field requires mysql to be queried and checked for availability. I have the do_truck_search.php script working great, but don't know how to pass the 'truck_status' variable from do_truck_search.php back to the .ajax call.
Once back at the .ajax call, I'd like a success: 'continue' or error: display the label#seltruck_noavail_error.
any help?
thanks!
UPDATE - can't get this to work? dataType: "text" in .ajax works though? any thoughts?
do_truck_search.php
if (($unixoutdate >= $dbunixoutdate) && ($unixoutdate <= $dbunixindate) && ($dbtruck == $seltruck_final)){
$truck_status = "nopass";
$data2 = array('truck_status' => $truck_status);
echo json_encode($data2);
}
process_request.js:
$.ajax({
type: "POST",
url: "do_truck_search.php",
data: truckString,
dataType: "json",
success: function(data) {
if (data.truck_status == "nopass"){
$("label#seltruck_noavail_error").show();
}
}
});
UPDATE
I think the reason why the json datatype was unreliable is because a small square (probably a space) is echo'd from the PHP script. Using datatype: 'text' and an alert() in the .ajax success callback shows the small square, prior to the actual data text. My dirty solution was to use datatype: text, then just substr the actual data I want to retrieve.
I searched hi/low in the PHP script to find the cause of the echo'd space, but couldn't find it??
One possible way to do this:
In $.ajax set dataType: "json"
In the PHP script echo json_encode(array("truck_status" => $truck_status));. Note that no other output must be present (so disable your layouts, views etc.)
Change success: function() {...} to success: function(data, status) {...}; now the variable data will contain the key truck_status with whatever you set it to. So access it using data.truck_status.