I'm building a webpage where the user can 'sign' some agreements and view signed and new (unsigned) agreements. For this the webpage uses the 2 functions in the code below to get relevant information from the database and then build the webpage. Unfortenately, when -and only when- the php file (process.php) returns a variable nrofagreements=0, the console shows an error for the get function;for any other values nrofagreements>0 no error occurs - see the console log below. I also checked (with Netbeans debugger) that process.php works properly - see json output below for nrofagreements=0- but I still suspect that the error must be in this php file(?) Any idea what goes wrong and how to fix it?
A1. jquery code:
$(document).ready(function(){
function NewAgreements(){
var jqxhr = $.get( "process.php", //get all
{ command: "getnewagreements", val1: "", val2: "" },
function(msg) {
},
"json"
).done(function(msg) {
console.log( "NewAgreement. $.get result: second success" );
//some code here to build the form based on msg from $.get()
form = buildNewAgreementsform(msg); //build form with supplier agreements and related products
$("#wrapper").append(form);
})//.done(function()
.fail(function() {
console.log( "NewAgreement. $.get result: error" );
})//.fail(function()
.always(function() {
console.log( "NewAgreement. $.get result: finished" );
});//$.get(
}//function getX()
//used by: tabs-agreements
NewAgreements();
function SignedAgreements(){
var jqxhr = $.get( "process.php", //get all
{ command: "getsignedagreements", val1: "", val2: "" },
function(msg) {
//var ecorp_eprodselectid;
},
"json"
).done(function(msg) {
console.log( "SignedAgreement. $.get result: second success" );
//some code to build the form based on the msg info from $.get()
form = buildSignedAgreementsform(msg); //build form with supplier agreements and related products
$("#wrapper-signedagreements").append(form);
})//.done(function()
.fail(function() {
console.log( "SignedAgreement. $.get result: error" );
})//.fail(function()
.always(function() {
console.log( "SignedAgreement. $.get result: finished" );
});//$.get( ",
}
SignedAgreements();
}); //$(document).ready
A2 simplified php code:
session_start();
$response_array = array();
$cmd = $_GET['command'];
switch($cmd){ //command handler
case 'getsignedagreements':
//some code here
$response_array['nrofagreements'] = $k;
if($response_array['nrofagreements'] == 0){
$response_array['status_general'] = 'success';
break;
}
//some code here
break;
case 'getsignedagreements':
//some code here
break;
default: //invalid command from webpage
$response_array['status_general'] = 'error';
break;//default
}//switch
$str = json_encode($response_array);
echo json_encode($response_array);
B. log console:
NewAgreement. $.get result: error
NewAgreement. $.get result: finished
SignedAgreement. $.get result: second success
SignedAgreement. $.get result: finished
C log json output for function NewAgreements:
"{"nrofagreements":0,"status_general":"success"}"
I don't have a specific fix for you, but I've got something which will help point you in the right direction...
System Design
One of the philosophies we hold dear is the idea that everything needs to do its own job in the most efficient way. The problem for most developers is they get confused with what each part of their application will do, and consequently try & do 5 jobs with one component
The reason I'm explaining this is because part of your question asked whether you should validate with JS or PHP. The answer is that you have to know which part of the system will do -- it looks like you're using PHP to validate whether the input is valid with the session, so I would suggest that you only handle the logic for that in the PHP file
Ajax
Personally, I would handle the response in your $.get command, but I would change to Ajax as my own preference:
$.ajax({
url: "process.php",
data: { command: "getnewagreements", val1: "", val2: "" },
success: function (msg) {
//handle validation in here
},
error: function(msg) {
//only fires when the URL can't be found etc
}
});
I've tested your code, found one illogical item in process.php (one single case is handled):
//...
case 'getsignedagreements':
//...
//...
case 'getsignedagreements':
//...
==> should be corrected to something like (handling two cases):
//...
case 'getnewagreements':
//...
//...
case 'getsignedagreements':
//...
Related
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
For some reason, I need to pass an ID via AJAX to a PHP function on the same page and run a query and return the result back to AJAX which would then append the final result into a div.
As I did some research, I came across this solution, but there are some shortcomings with it.
function1($_GET['id']);**//not getting the id's value**
echo "This is function 1 AND id=".$param;**//this string must be
passed back to the previous ajax request.**
AJAX request (efund.phtml)
$.ajax({
type:'GET',
url:'efund.phtml',
data:"function_to_call=0?id"+cl[3],
success: function(data){
// alert('successful');
}
});
PHP (efund.phtml)
switch ($_GET['function_to_call']) {
case 0:
function1($_GET['id']); // not getting the id's value
break;
case 1:
function2();
break;
default:
break;
}
//And your functions.
function function1($param) {
echo "This is function 1 AND id=".$param; // This string must be passed back to the previous AJAX request.
}
function function2() {
echo "This is function 2";
}
The most common way to communicate between server/client tends to be to use XML or JSON, for your case I recommend you use JSON:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
})
.done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
And then in the server get them using:
$_GET['function_to_call'] // To obtain 'function_to_call' param
$_GET['id'] // To obtain 'id' param
To send information back as response from the server I recommend you, use the same approach and use json_encode for parse an array as JSON and return it using:
in your case for function1 it would be:
function function1($param) {
return json_encode(array ( "id" => $param ) );
}
Also, maybe you should consider if you should use GET or POST for the Http request. You can see more information about it here:
www.w3schools.com/tags/ref_httpmethods.asp
Edit:
If you have problems with the ajax request and you want to check if the ajax request is executed correctly modify the Ajax code like this:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
}).done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
Change
data:"function_to_call=0?id"+cl[3],
to
data: {function_to_call: 0,id : cl[3]},
in this case data work as object and it is easy to fetch value.
According to your only first condition called every time because you are passing function_to_call=0
I have a jQuery validation script that is working perfectly with the except of the event handler. I have simplified this post for troubleshooting purposes.
jQuery
submitHandler: function (form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json"
})
.done(function (data) {
if (data.resp > 0 ) {
alert(data.message);
}
});
return false; // required to block normal submit since you used ajax
},
// rest of the validation below, truncated for clarity
The submitHandler successfully posts to my PHP script that adds a user to a database and then echoes back a json_encode() result.
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("resp"=>1, "message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("resp"=>2, "message"=>"User account already exists.");
}
echo json_encode($resp);
?>
As you can see the idea is simple. Alert the user with the proper response message. When I run my script the user account is added successfully to the database but no alert is displayed to the user. The Console in Chrome shows no errors, what am I missing?
The data variable in the done() is a string. You have to transform it to an object like this
var response = $.parseJSON(data);
in order to access the attributes
I am sorry I missed dataType : "json" in your code in my previous answer.
Any way I tried your code and it is working. The alert shows the message. I think you have an error somewhere else. I think it has some thing to do with the array you are encoding to json(PHP part). The response you get is not complete. Try to debug your PHP and test the page separately from AJAX and see what is the result
After some tinkering I was able to get things working the way I wanted. Here's the updated code.
jQuery
.done(function (data) {
$("#user_add_dialog").dialog({
autoOpen: false,
modal: true,
close: function (event, ui) {
},
title: "Add User",
resizable: false,
width: 500,
height: "auto"
});
$("#user_add_dialog").html(data.message);
$("#user_add_dialog").dialog("open");
});
return false; // required to block normal submit since you used ajax
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("message"=>"User account already exists.");
}
echo json_encode($resp);
?>
I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.
I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );