problem with jquery from.submit and ajax - php

below is the code i am using
$(document).ready(function(){
$("form").submit(function(event) {
event.preventDefault();
var val = $("#captcha_text").val();
$.ajax({
url: 'checkAnswer.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
complete: function(data)
{
console.log(data);
if($.trim(data) == "true")
$("form")[0].submit();
else
alert('Wrong Answer');
}
});
});
});
checkAnswer.php has this one line only which is
echo "true";
i do not know why the javascript if condition in the complete function is always going to else part and showing alert('Wrong Answer')
does any one know what could be the problem. ? In the firebug console i do see the response comming back from my ajax and response value is "true"

use:
if($.trim(data.responseText) == "true")
complete receives as 1st argument jqXHR(an extended XMLHTTP-Request-object) and not the data depending on dataType.
Or use success instead of complete

Well i think you have to do this:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
complete: function(jqXHR, textStatus)
{ //it returns an jqXHR object
if($.trim(jqXHR.responseText) == "true")
$("form")[0].submit();
else
alert('Wrong Answer');
}
});
This is because jQuery returns a jqXHR object look here for reference.
EDIT You can also try this:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'text',
data: {
answer: val
},
success: function(data)
{
if($.trim(data) == "true")
alert('ok');
else
alert('Wrong Answer');
}
});

Related

jQuery Ajax get json returned result

I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
$is_valid = true;
$is_duplicate = false;
$email_reset = false;
$register = $this->getRegisterHelper();
$register->addEmailCheck();
$register->setData($this->getAllParams());
$validationErr = $register->getValidationResult();
if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
|| empty($validationErr['isEmailValid'])
) {
$is_valid = false;
} elseif (!empty($validationErr['duplicates']['email'])) {
$is_duplicate = true;
$email_reset = $this->sendResetEmail();
}
$result = [
'duplicate' => $is_duplicate,
'valid' => $is_valid,
'reset' => $email_reset
];
$this->getResponse()->setBody(json_encode($result));
}
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
}
});
});
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json',
success:function(response){
console.log(response);
var duplicate=response.duplicate;
var valid=response.valid;
var reset=response.reset;
},
error:function(err){
console.log('Error '+err);
}
});
You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
success : function(data, status, xhr) {
console.log(JSON.stringify(data));
},
error: function(jqXhr, textStatus, errorMessage){
console.log("ERROR " + errorMessage);
}
});
});
$.ajax({
type: 'GET',
url: url,
data: {
'email': value
},
dataType:'json',
}).success(function(response){
//YOUR Json KEY
if(response.success){
}
});
I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
url: "YOURURL",
type: "YOURTYPE",
dataType:"json",
}).done(function(data) {
console.log(data) // to see the reqested data
// manipulate data here
});
Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json'
});
});
You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);
Reference:
jQuery AJAX Call to PHP Script with JSON Return

Ajax success not reading PHP echo as string

I have a simple PHP script which, when it executes correctly from an AJAX call, ends with:
echo "ok";
Yet when I try to parse this information it tells me its not a string.
In the example below the result is: alert('error: Type Mismatch');
Why does JQuery not read the php echo as a string?
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if(typeof response == typeof 'string'){
if( response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Screenshot below shows that the response is correct and simply says 'ok'
As I'm reading from jquery Api Doc I understand that you can get a "string" or something else as a response, based on what kind of dataType you passed (if u did) in your $.ajax object. Otherwise it will be assumpted from jQuery, based on some its own logic.
In my opinion you should avoid every assumption and explicitly pass your dataType based on the response format you'll send.
So,
in case you'll set response.php to return
echo "ok";
you should set dataType "text" in your ajax call:
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "text",
...
and get the response with:
if(typeof response == "string")
{
console.info(response);
...
Or
in case you'll set response.php to return something like
echo json_encode(array("data" => "ok"));
you should set dataType "json":
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "json",
...
and get the response with:
if(typeof response == "object")
{
console.info(response.data);
...
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if (typeof response === "string"){
if (response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Do it another way:
In you php script echo back a JSON: json_encode("ok");
In AJAX specify dataType: "json" and add event:
complete: function(jsondata, stat)
{
if(stat == "success")
alert( $.parseJSON( jsondata.responseText ) );
}
The response is not string type, it is a PlainObject object.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
typeof response == 'object' // true
Try this:
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
dataType: "text",
success: function (response) {
if( response == 'ok')
alert('all is good');
else
alert('error:');
}
});

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

if statement not evaluating correctly

so i am making a $.ajax call and returning json data. in said data there is an element named status. I am testing this: if(data.status === "success"){ ..do something..}. I know that the json data from the $.ajax call is in fact "success" (i know from the developers tools in chrome that the php script is returning {status: success}) however nothing in the if statement is being evaluated. and if i add an else statement to the if statement, that code DOES get evaluated. here is my code:
$.ajax({
type: "POST",
url: "./php/checkuser.php",
datatype: "json",
success: function(data){
console.log(1);
if(data.status === "success"){
console.log(2);
$.get("./mainmenu.html", function(html){
$("#content").html(html);
console.log(3);
});
$.ajax({
type:"POST",
url:"./php/loaduserdata.php",
dataType:"json",
success:function(data){
console.log(4);
if(data.status === "success"){
console.log(5);
var lastlevel = data.lastlevel;
if(lastlevel === 0){
console.log(6);
$("#continue-wrapper").removeClass("enabled").addClass("disabled");
$('<img />').attr('src', "./images/menuitem_continue-disabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
} else {
console.log(7);
$("#continue-wrapper").removeClass("disabled").addClass("enabled");
$('<img />').attr('src', "./images/menuitem_continue-enabled.png").attr('id', "continue").attr('alt', "Continue").load(function(){
$("#continue-wrapper").html($(this));
});
}
}
}
});
} else {
console.log(8);
}
},
error: function(thrownError){
console.log(thrownError);
}
});
in the console for output i get 1 and 8. I'm stumped can someone see something that i can't?
In the first ajax request you have datatype it should be dataType, so data is just a string and data.status is undefined.

Having trouble running an if statement on a jquery ajax output

in my check.php I have an echo "ok";
however my if statement to check if the value is ok does not work.
Basically I want to execute a javascript function after check.php looks for the email in the database.
$.ajax({
type: "POST",
url: "check.php",
data: "checkit=" + $("#checkEmail").val(),
success: function(output){
$("#userCheck").html(output);
if(output == "ok"){
alert("yay");
}
}
});
I would suggest returning a JSON string rather than plain text. So your check.php should echo
{status: 'ok'}
then change your ajax handler to:
$.ajax({
type: "POST",
url: "check.php",
data: "checkit=" + $("#checkEmail").val(),
success: function(response){
$("#userCheck").html(response.status);
if(response.status == "ok"){
alert("yay");
}
}
}, 'json');
or you could even just return a boolean value:
{success:true}
try this:
$.ajax({
type: "POST",
url: "check.php",
dataType: "text", //<---
contentType: "application/x-www-form-urlencoded",
data: "checkit=" + encodeURIComponent($("#checkEmail").val()),
success: function(output){
$("#userCheck").html(output);
if(output == "ok")
alert("yay");
}
});

Categories