Trouble with JSON returned from Ajax - 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(){});

Related

dependent form inputs need to be loaded from json file php with jquery

I am making a web form and some of it needs to be populated with a jQuery.ajax get jsonp call, and I'm having a problem coming up with the needed php code to format that json file.
I have an html page that has a <form> and the select elements are shown below here.
<!-- lang-html -->
<select id="veh_make" name="Make"><option>Make</option></select>
<select id="veh_model" name="Model"><option>Make</option></select>
I'm using jquery.js and jquery-ui.js+css files, and jquery.form.plugins with my functions to populate the vehicle makes and models, but everytime I get an error saying
Error: jQuery18302370089164328284_1491704657702 was not called
I am requesting the file with jQuery.ajax and using get json what needs to be done to my json format to wrap it in the callback=? function or is there a better way to call this file?
content of my make_model_json.php file
[
{"Make": "Other","Models": ["Other"]}
,
{"Make": "Motorcycle/ATV","Models": ["Other","ATV","Over 600cc","Under 600cc"]}
,
{"Make": "Boat","Models": ["Other","Over 20ft","Under 20ft"]},{"Make": "RV","Models": ["Other","Over 30ft","Under 30ft"]}
]
javascript to populate the select elements
var obj_make_model=Array();
function buildYearMenu(){
var date = new Date();
this_year = date.getFullYear();
jQuery('#veh_year, form [name="veh_year"]').append('<option value="Other">Other</option>');
for(i=this_year; i>=1950; i--){
jQuery('#veh_year, form [name="veh_year"]').append('<option value="'+i+'">'+i+'</option>');
}
}
jQuery(document).ready(function(){buildYearMenu();
jQuery('#veh_year, form [name="veh_year"]').change(function(){
populateVMakes();
});
jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').change(function(){
populateModels(jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').prop("selectedIndex"));
});
jQuery.ajax({
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsonp_callback',
crossDomain: true,
url:( "http://www.example.com"+"/ajax/make_model_json.php"+"?callback=?" ),
async:false,
error:function(xhr,status,errorThrown){
//j(xhr+','+status+','+errorThrown);
},
success:function(jsonp){
obj_make_model = jsonp;
populateVMakes();
jQuery('form select[name^="veh_year"]').removeAttr("disabled");
}
});
});
function populateVMakes(){
jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').children().remove();
jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').append('<option value="">Make</option>');
//jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').append('<option value="Other">Other</option>');
for (i = 0; i < obj_make_model.length; i++){
jQuery('#veh_make, form [name="veh_make"], form [name="veh_make"]').append('<option value="'+obj_make_model[i].Make+'">'+obj_make_model[i].Make+'</option>');
}
}
function populateModels(make_num) {
make_num = make_num-1;
jQuery('#veh_model, form [name="veh_model"]').children().remove();
jQuery('#veh_model, form [name="veh_model"]').append('<option value="">Model</option>');
//jQuery('#veh_make, form [name="veh_model"]').append('<option value="Other">Other</option>');
for (i = 0; i < obj_make_model[make_num].Models.length; i++){
jQuery('#veh_model, form [name="veh_model"]').append('<option value="'+obj_make_model[make_num].Models[i]+'">'+obj_make_model[make_num].Models[i]+'</option>');
}
}

How to update values in my DB with values from <select> tags - (Not $_POST)

I want to take values from <select> or <input> tags but using function onclick button, not using $_POST. I did a try but I have stack on syntax. In case of $_POST goes like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" />
My update query:
if (isset($_POST['submit']) or isset($_GET['submit'])){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = '".$_POST["name"]."',
lastname = '".$_POST["lastname"]."',
rank = '".$_POST["rank"]."'
WHERE id=1";
$db->setQuery($query);
$db->query();}
Now I am trying to do something like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" onclick="update()" />
My update query:
function update(){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = ???,
lastname = ???,
rank = ???
WHERE id=1";
$db->setQuery($query);
$db->query();}
But what is the syntax to call <select> and <input> tags names? Or their values in other words.
You're confusing the code that runs on the client-side (JS) with the code that runs on the server-side (PHP). JS runs after the PHP finished - so you can't "call" from JS to functions in PHP unless you submit a form (POST/GET) or use AJAX.
TYou must use $.ajax if you want to do this just by clicking a button and not refreshing or redirecting your browser
1) Read about http://api.jquery.com/jQuery.ajax/
2) add an eventhandler on your button onclick="update();"
3) create an ajax thingy like:
function request(variable1,variable2,variable3){
var request = $.ajax({
url: "/server.php", // The address of you php script that will handle the request
type: "POST", // Method type GET / POST in this case POST (Similar to form submission methods....)
data: { // What you send to the server 'VariableName' : VariableValue, in this case you assign the varaiables that were passed to the request function.
'var1': variable1,
'var2' : variable2,
'var3': variable3
},
dataType: "json" // The response type you expect from the server
})
request.done(function(msg) // Function being called when everything is ok and server sends back data
{
console.log(msg) // handle the reply / data
})
request.fail(function(jqXHR, textStatus) // Something went wrong...
{
console.log(textStatus); // See the error report
console.log(jqXHR);
})
request.complete(function(){
console.log("Ajax request complete!"); // This will always be executed when a request has completed even if it failed. (Executes after .done and .fail)
})
}
So you cound do this inside your update function that is being called whenever you click the button:
function update()
{
var val1 = $.('#selectbox').val();
var val2 = $.('#inputbox').val();
var val3 = $.('#textarea').val();
new request(val1,val2,val3);
}
The request / variables will be sent using the POST method so in you php script
you may process them as you would do with a form
if(isset($_POST['var1']) && isset($_POST['var2']) && isset($_POST['var3']))
{
$serverReply = doThings($_POST['var1'],$_POST['var2'],$_POST['var3']);
//and this is how you reply to your client/browser in json format
echo json_encode($serverReply);
}
Make sure to Check more in Depth tutorials regarding ajax comunication.
There are plenty around on the net.
onclick called function javascript
function javascript implements with ajax
example:
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

Ajax Post Type will not send data to php page

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

Trying to upload a file through jQuery .post() - file input not showing up on back end (using codeigniter)

First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU

ajax - access to variables set in url:

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.

Categories