What is the correct way to handle Ajax success callback events using jquery?
In my code, when I run instead of displaying data, it alerts object:object. However, if I use say msg.box it returns the data correctly.
I am trying to create an if statement where if text equals a certain word then the variable from json is placed in the html of the result div BA_addbox.
I cannot seem to get this to work and would be grateful if someone could point out my error. I have only included the relevant code as the form is posting the correct data and the php code is catching all the posts. Many thanks.
ajax code
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
if(msg == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
//alert(msg);
console.log(msg);
//$("#BA_addbox").html(msg.box);
//$("#formImage .col_1 li").show();
//$("#BA_boxform").get(0).reset();
//$("#boxaddform").hide();
}
});
boxesadd.php
$box = mysql_real_escape_string($_POST['BA_box']);
$boxerrortext = "You need to input a box";
if (isset($_POST['submit'])) {
if (!empty($box)) {
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised, 'submit'=>$submit);
$result = json_encode($form);
echo $result;
}
else
{
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
//echo "You need to input a box";
}
}
In javascript associative arrays are called objects, so there's no bug in the transmitted data.
Why do you compare msg to "You need to input a box"? You cannot compare object and string, this makes no sense.
if(typeof msg.boxerrortext !== "undefined" && msg.boxerrortext == "You need to input a box") {
$("#BA_addbox").html(msg.boxerrortext);
} else {
$("#BA_addbox").html(msg.box);
}
Try this instead:
if(msg.boxerrortext) {
$("#BA_addbox").html(msg.boxerrortext);
}
else {
$("#BA_addbox").html(msg.box);
}
Hope this will help !!
Related
I'm trying to use AJAX properly to display an incremented value from a separate PHP file, but I'm a little iffy on the code. This is what it looks like:
$("#submit").click(function()
{
$.ajax({
type: 'POST',
url: 'info.php',
dataType: 'json',
data: {$_SESSION['totalCorrect'}
success: function()
{
if ($_SESSION['totalCorrect'] >= 8 && $_SESSION['totalCorrect'] <= 10)
{
window.location.replace('success.php');
}
else
{
window.location.replace('retake.php');
}
}
});
});
The value is stored in info.php and I'm trying to pull that value from that file, but I'm not sure on how to code the AJAX syntax. I'm certain this data: {$_SESSION['totalCorrect'} code isn't correct.
I can display the incremented value so I know, at least, that the variable is being incremented, but what I want to do now is to use that variable to check if they passed or not. If they did, then they get redirected to success.php. If not, then they get sent to retake.php.
EDIT: info.php
if (empty($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
foreach ($correctAns as $key => $answer)
{
if (!empty($_POST[$key]))
{
if ($_POST[$key] == $answer)
{
echo $correct[$index];
$_SESSION["totalCorrect"]++;
}
else if($_POST[$key] != $answer)
{
echo $incorrect[$index];
}
$_SESSION[$key] = true;
}
$index++;
};
You haven't posted all code, so I can only answer the one question.
First:
You're mixing php and javascript. You cannot access php variables in javascript unless you assign them as string to the output html or post them via an ajax - that's what you want to do.
So let's have a look at your jQuery-ajax:
$("#submit").click(function() {
$.ajax({
type: 'POST',
url: 'info.php',
// dataType: 'json', // I deactivated this to recieve a string only
// in data you should get the answers the user gave - another topic
data: {question1: '42', question2: 'Douglas'}, // that ',' was missing
// you'll get whatever you echo in info.php as 'result' as parameter
// in this success-callback-function (as result [json]):
success: function(result) {
// now you can check what the result is:
console.log(result); // make it visible to you for debugging
if (parseInt(result) >= 8 && parseInt(result) <= 10) {
console.log('redirecting to SUCCESS');
//window.location.replace('success.php'); // uncomment when working
}
else {
console.log('redirecting to RETAKE');
//window.location.replace('retake.php'); // uncomment when working
}
}
});
});
now lets adjust your info.php:
if (empty($_SESSION["totalCorrect"]))
{
$_SESSION["totalCorrect"] = 0;
}
else
{
$totalCorrect = $_SESSION["totalCorrect"];
}
foreach ($correctAns as $key => $answer)
{
// remember, that in $_POST you'll get everything you've put in 'data' before!
if (!empty($_POST[$key]))
{
if ($_POST[$key] == $answer) // better change to === if you know what data-types you'll get (and google the difference)
{
//echo $correct[$index]; // do not echo anything else but the result
$_SESSION["totalCorrect"]++;
}
else if($_POST[$key] != $answer)
{
//echo $incorrect[$index];
}
$_SESSION[$key] = true;
}
// $index++; // we don't need that, do we??
};
// here's the actual response/result:
// All you echo will be in 'result' of your ajax succes-callback-function
echo $_SESSION["totalCorrect"];
I don't know what your form looks like, how all the pages are set up, so I can't provide a complete code - also this would go far beyond the question.
But this should give you an idea of how getting are variable from php via ajax works.
Further Info:
Getting form data using JavaScript and sending data with Ajax
usefull stuff about json:
http://www.w3schools.com/js/js_json.asp
http://php.net/manual/en/function.json-encode.php
I need help in Ajax.
I got this code online.
This function is to check the contact.php
I have some few question so someone could assist me.
My questions :
1. Is this code good and possible to run ?
2. Can someone explain me what does the function in line 4 and line 5 does.It seems it send data to the contact.php but what is it returning?
Ajax:
var validateEmailForm = {
dataType: 'json',
submit: function(form) {
var redirect = false;
$.ajax('contact.php', {data:{'email':form.email.value}}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
}
} else {
alert('Failed to connect to the server.');
}
}
}
}
Contact.php:
<?php
error_reporting(0);
$email = $_POST['email'];
if (isset($_$POST['email']))
{
// How to return valid to the ajax
} else {
// How to return invalid to the ajax.
}
?>
You need to return a JSON_encoded array to the ajax function, like below:
$email = $_POST['email'];
$status = false;
if (isset($_$POST['email']))
{
$status = 'success'
} else {
$status = false
}
echo json_encode(array('status' => $status));
?>
Further, add dataType: 'json' to your $.ajax() so that the deferred function automatically parses it as such.
Remove the typeof() as we know what we're expecting in return.
AJAX is much easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
https://stackoverflow.com/questions/25945137/php-fetch-content-from-one-form-and-update-it-in-other-form/25954450#25954450
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#formID').submit({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, to definitively answer your second question, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
I have created a form using ajax and php. The initial load and entering values into the form are all working fine, but where I am getting errors, is after the submit button has been pressed. Here is the markup for the form, and the ajax and php handlers:
relevant parts of form:
<form id="edit_time">
<!-----form fields here----!>
<button class="saveRecurrence" type="button" onclick="editTimeDriver('.$_GET['driver_id'].')">Save</button>
ajax part:
function editTimeDriver(driver_id) {
var time = "";
if (driver_id)
{
time += "&driver_id="+driver_id;
}
var data = $("#edit_time").serialize();
$.ajax({
url: "ajax.php?action=save_driver_event"+time,
dataType: "json",
type: "post",
data: data,
beforeSend: function()
{
$(".error, .success, .notice").remove();
},
success: function(json)
{
if (json["status"]=="success")
{
alert(json["message"]);
$("#edit_time")[0].reset();
}else{
if(json["error"]["date_from"]){
$("input[name=date_from]").after("<div class="error">"+json_time["error"]["date_from"]+"</div>");
}
}
}
});
}
This then passes to the php part which is:
$json = array();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$date_from = tep_db_prepare_input($_POST['date_from']);
if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date_from)) {
$json['error']['date_from'] = 'Start Date is not valid!';
}
if (isset($json['error']) and !empty($json['error'])){
$json['status'] = 'error';
$json['message'] = 'Please check your error(s)!';
}else{
$json['status'] = 'success';
$json['message'] = 'Time Data has been successfully updated!';
}
}
echo json_encode($json);
Now for some reason, if the date_from field is left blank, and the form submitted, it doesn't come back with error message, instead it returns the success message. Can anyone tell me why it is not reading the errors?
Change your code by this one
onclick="editTimeDriver('<php echo $_GET['driver_id'] ?>'); return false;"
The return false statement prevent the form to be submitted using http (as you want to send an ajax request)
And You where doing something weird with your $_GET['driver_id']
Don't forget that php is running server-side
Im trying to get starting with JSON and jQuery. I'm not a JavaScript programmer at all so I'm mixing and matching and having quite a few issues getting my code to work. I thought someone might be able to help me out.
I have a model which uses the following PHP code to check if an email address is registered with the system:
function is_email_available($email) {
$this->db->select('1', FALSE);
$this->db->where('LOWER(email)=', strtolower($email));
$this->db->or_where('LOWER(new_email)=', strtolower($email));
$query = $this->db->get($this->table_name);
return $query->num_rows() == 0;
}
The above code is being called by my ajax controller using the following, and if it is registered returns a json true or false
function email_availability() {
// Check to see if the username is available or taken
if ( $this->users->is_email_available( $this->input->post('emailaddress'))) {
echo json_encode(TRUE);
} else {
echo json_encode(FALSE);
}
}
The above is called from my JS file using the following jQuery, but it doesn't seem to be working at all.
if(iEmail.val()) {
$.ajax({
url: '/ajax/email_availability',
data: 'emailaddress=' + iEmail.val(),
dataType: 'json',
type: 'post',
success: function(msg) {
iEmail.next('.error').text('This Email Address is not registered');
error = true;
}
});
}
I think my jQuery is completely off but can't figure it out. Any help would be greatly appreciated.
You didn't really check if the result was true or false.
success: function(msg) {
if (msg){
//email is available
}
else{
//email is not available
}
}
i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance
Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.
In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)