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.
Related
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)
I've built a page (in WordPress) that is supposed to submit a form via AJAX, but whenever the form is submitted, the url changes to the form handler's url, and it just displays the JSON its supposed to return instead of using it to update the current page. It just looks like a blank page with:
{"id":"1","task":"test","status":"complete"}
Here's what I'm using for the form:
<div id='test'>
<form action ='handler.php' method='post' class='test_form complete'>
... hidden input fields ...
<input type="submit" name="markcomplete" value="Mark Complete" /></form>
</div>
Here's the ajax that is submitting the form:
jQuery('.test_form').on('submit', function(e) {
jQuery(this).hide();
jQuery.ajax({
url : myAjax.ajaxurl, //this is required for using ajax in WordPress
dataType : "json",
type: "POST",
data: jQuery(this).serialize(),
success: function (response) {
otherform = "#" + response.task + " form" + "." + response.status;
jQuery(query).show();
jQuery('#message').html("<p>status changed</p>");
}
});
e.preventDefault();
});
What this is supposed to do is hide the current form, show another form, and display a simple message that the status has been changed.
and here's the handler.php:
if (isset($_POST['markcomplete'])){
$id = $_POST['id'];
$task = $_POST['task'];
$cparray = array('userid' => $id, 'task' => $task, 'satus' => "complete");
// function that makes changes to database...
wp_send_json($cparray); // this is the equivalent of echo json_encode($cparray);
}
I know the post is being sent, because I'm seeing the changes made to the database, and its displaying the JSON I want the current page to use. I'm pretty inexperienced with AJAX so I wouldn't be surprised if its something simple.
Edit1: JQuery is included in the project. I don't get any javascript errors, but on further inspection I see this message in the console when I click submit:
"Resource interpreted as Document but transferred with MIME type application/json: "handler.php".
<div id='test'>
<form action="" method="POST" id="testForm" class='test_form complete'>
... hidden input fields ...
<input type="submit" name="markcomplete" value="Mark Complete" .></form>
</div>
jQuery('#testForm').on('submit', function(e) {
e.preventDefault();
jQuery(this).hide();
jQuery.ajax({
url : myAjax.ajaxurl, //this is required for using ajax in WordPress
dataType : "json",
type: "POST",
data: jQuery(this).serialize(),
success: function (response) {
otherform = "#" + response.task + " form" + "." + response.status;
jQuery(query).show();
jQuery('#message').html("<p>status changed</p>");
}
});
});
Use e.preventDefault() first to avoid form submission.
Solved: The issue was I didn't put the jquery inside
jQuery(document).ready(function(){});
I have the following AJAX:
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
})
.done(function(resp){
$('#plant-tree-inner').html(resp);
});
base is my base URL, tree is a controller and plant is a method in that controller.
The URL is correct, the controller and method are in place, with correct names. I've made sure of that by echoing a string in the plant method and it appeared correctly on the client after the AJAX response.
However, none of the post data seems to be arriving at the server.
Doing echo $this->input->post('name'); inside the plant method gives an empty string. Doing var_dump($_POST) gives an empty array. I even tried giving parameters to the plant method but that just throws a missing parameter error.
So where is the data getting lost and why?
EDIT: I see now that my question is wrong. It has nothing to do with CodeIgniter, since the data isn't being sent at all. The field values are undefined according to Javascript, but they certainly exist in HTML:
<input type="text" id="field_treename" placeholder="Tree name" value="" />
Seems like something is wrong with jQuery library.
For test' sake, try to send request avoiding it.
You may try this also..
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
success:function(resp){
$('#plant-tree-inner').html(resp);
}
});
Try to simulate the problem in the very basic method like creating another directory in your localhost or server like this and create files as describe below.
in the index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>POST Sending Problem</title>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
Link
<script src="custom_function.js"></script>
</body>
</html>
Create js file for example test.js and put this as test
function test (id, base) {
$.ajax({
type: "POST",
data: {
'id': id
},
url: base,
success: function(data) {
alert(data);
},
error: function(data) {
alert('no data');
}
});
}
Next create a php file your_phpfile.php
<?php
if (isset($_POST['id'])) {
echo $_POST['id'];
} else {
echo "no-result";
}
?>
This would help you determine the problem. If this works fine, try applying it using codeigniter.
Good Luck
User this one..
var request = "name="+$('#field_treename').val()+"&"
request += "summary="+$('#field_summary').val()+"&"
request += "description="+$('#field_description').val()+"&"
request += "address="+$('#field_url').val()+"&"
request += "category="+$('#field_category').val()
and in set as data=request. This should work.
I have the following form for users to reset their password it is within the file forgotten.php in the root directory.
<form id="pass_form" action="" method="post" name="pass_form">
<label>Username:</label>
<input type="text" class="blank" name="name" id="name" value="Trader Username" data-default="Trader Username" data-message="Please enter your username..."> *<br>
<input class="sub-btn" type="submit" value="Submit">
</form>
I would like to post the username to inc/sendreset.php so I have the following Ajax in js/scripts.js
$("#pass_form").validator({
offset: [0, 354],
position: 'center left',
messageClass: 'conerror'
}).submit(function(e) {
if (!e.isDefaultPrevented()) {
var form = $(this);
var serdata = form.serialize();
$.ajax({
type: "POST",
url: "sendreset",
data: serdata,
cache: false,
success: function (html) {
log('inside ajax sendreset', this, arguments);
$('#pass_form').fadeOut(400,function(){
if (html=="0") {
} else {
$('#pass_form').html('<p>The password reset instructions have been sent. Please check your email.</p>');
}
$('#pass_form').fadeIn();
});
},
error: function (err) {
log('error inside ajax sendreset', this, arguments);
}
});
//$('#pass_form').fadeOut(400);
e.preventDefault();
}
});
However it does not seem to post the username into the file. The inc/sendreset.php is as follows
<?php
require_once('./library.php');
require_once('./PHPMailer/class.phpmailer.php');
$Trader = new CompanyTrader();
$resetdata = $Trader->resetTrader($_POST['name']);
print_arr($resetdata);
//more php which isn't relevant
?>
I know the file inc/sendreset.php works as when I the file to use $_GET['name'] and i use inc/sendreset.php?name=username the array is returned for the relevant user. It does not work from forgotten.php using Ajax though. Please help!
i really think this is wrong:
url: "sendreset",
try with an relative or absolute url like http://mysite.com
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;