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
Related
I want to get the value from $data->username but it returns NULL because input is not json. What am I doing wrong here?
Here is my current code.
JS:
$(function() {
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: 'http://penguin.linux.test/api/login.php',
type: 'post',
dataType: 'application/json',
data: $("#login-form").serialize(),
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
PHP:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents("php://input", true));
}
I've been trying some stuff with Ajax and laravel, I've tried a lot at this point and have no idea what is going wrong. I can't seem to get the form data (that's what this is mainly about). If ANYONE is able to help, it'd be great. Here's the code, and thanks in advance.
$('.bier').on('click', bier);
$('.delete-check-close').on('click', closeDelete);
$('.delete-check-show').on('click', showDelete);
$('.message').on('click', closeMessage);
hideMessage();
$('form.page').on('submit', bier);
function bier() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
}
});
Try the following code:
$('form.page').on('submit', function() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
});
As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');
var myData = JSON.stringify($('form').serializeArray());
$.ajax({
cache: false,
url: "http://localhost/Demo/store.php",
type: "POST",
data: myData,
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert(status);
}
else {
var r = xhr.responseText;
}
}
});
$decoded = json_decode($_REQUEST['myData'],true);
print_r($_REQUEST);
exit;
if (is_array($decoded))
{
foreach ($decoded as $value) {
echo $value["name"] . "=" . $value["value"];
}
}
When i am trying to decode the data in php the error is undefined index myData..Please help me..Thanks.
Give it a try with:
$decoded = json_decode($_POST['myData'],true);
Try this when call ajax
data: {'myData' : myData},
Then access using
json_decode($_POST['myData'],true);
or
json_decode($_REQUEST['myData'],true);
try this pass datatype :
$.ajax({
url: 'http://localhost/Demo/store.php',
type: 'POST',
dataType: 'json',
data: $('#form').serialize(),
success: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert(status);
}
else {
var r = xhr.responseText;
}
}
});
When you pass a string as the data property is just appends it as a parameter query string to the URL. If you want to send an encoded JSON string you still need to give it a name:
data: {myData: myData}
Now you can use the myData request parameter in your PHP script.
used dataType:json;tosend json.
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');
}
});