I got the following ajax response.
{"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
now the problem is that i want to display only code and item fields & value but i am unable. please help me how to access that fields.
my code is following.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
$("#OrdItem").html(data);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
Try this:
var abc = {"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
var a = JSON.parse(abc.ord_item_Json_string)
$.each(a, function(index,value){
console.log(value.code+'--'+value.item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try the code below...in success callback you will be getting data in json object format. so just get value using its key.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (jsonResponse) {
var itemsList = jsonResponse.ord_item_Json_string;
$.each(itemsList, function (index, value) {
console.log(value.code + '--' + value.item);
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
try this: you can try below code where you can iterate over json array and read each attribute
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
var dataStr = "";
var jsonData = data.ord_item_Json_string; // this is already json
jsonData = JSON.parse(jsonData);//value need to parse
for (var i = 0; i < jsonData.length; i++) {
var ord= jsonData[i];
console.log(ord.code);
dataStr += ord.code;
}
$("#OrdItem").html(dataStr);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
JSFiddle
Related
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
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;
});
post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});
Hi all I have a site developed in codeigniter.
In some function I have to retrieve data from mysql and print the result in javascript because is an ajax call.
Thi is my php function to retrieve data:
public function getCityByNameOnly($name) {
$query = $this->db->query('SELECT * FROM city WHERE name LIKE "%'.$name.'%" ');
$city = array();
foreach ($query->result() as $row)
array_push($city, $row);
return json_encode($city);
}
}
And this is my ajax call:
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "text",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name_en + '<br> ');
}
}
});
}
})
I append the result into a div but is always undefined.
This is the console.log of my created json:
{"id":"125","name_it":"Lèsina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Traù)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Città del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]
How to print this json into my success function in javascript?
Thanks
change the datatype:"json" in the ajax will solve the issue
$('#ricerca-ajax').keyup(function(){
var val = $(this).val();
if (val.length>2){
var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
$.ajax({
url: site_url_city,
type: "POST",
data: {search: val},
dataType: "json",
success: function(data) {
console.log(data);
for(var i=0;i<data.length;i++)
{
$('#msgid').append(data[i].name + '<br> ');
}
}
});
}
})
I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});