How can we encode the Multi JSON data response in ajax - ajax

I have a problem with json encoded information which loaded via ajax.I pass the multi JSON to the ajax for display the field value.
How can i fetch the field value from the json using query ajax.
ajax code :
....success:function(data){
var TotalBuyPrice = 0;
var TotalItem = 0;
$.each(data, function(c,cart){
//Condition follow 1
var InStockQty =cart.products_qty;
alert(InStockQty);
//And also follow 2
var name =cart["withoutdiscount"][0]["products_name"];
alert(name);
});
}...
The PHP code :
These are my steps following for json response.By using array collect the result
$response = array();
$response['withoutdiscount'] = $withoutdiscount;
$response['withdiscount'] = $withdiscount;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
jsoncallback:
({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
"withdiscount":[{"products_id":"2","discount_qty":"8"},
{"products_id":"3","discount_qty":"1"}
]
});

I Solve the problem like this:
Using PHP file get one response like this:
$response = array();
$response['withoutdiscount'] = $withoutdiscount;
$response['withdiscount'] = $withdiscount;
echo $_GET['jsoncallback'] . '(' . json_encode($response). ');';
jsoncallback: //JSON response
({"withoutdiscount":[{"products_id":"1","products_name":"Lumia"}],
"withdiscount":[{"products_id":"2","discount_qty":"8"},
{"products_id":"3","discount_qty":"1"}
]
});
using ajax function call the json response like this:
function querySuccess(tx,results) {
var jsonString = JSON.stringify(results);
$.ajax({
url:'getcart.php',
data: {data : jsonString},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success:function(data){
var withdiscount=data.withdiscount;
var withoutdiscount=data.withoutdiscount;
if(withdiscount!='')
{
$.each(withdiscount, function(c,cart){
var discount_qty =cart.discount_qty;
alert(discount_qty);
);
}
if(withoutdiscount!='')
{
$.each(withoutdiscount, function(c,cart){
var products_name =cart.products_name;
alert(products_name);
});
}
}
});
}
This is working with me.
NOTE: There is only 2 JSON response is pass so i given directly.

Related

How to remove dublicate values using codeigniter and ajax?

I return passports from my database when I select user using codeigniter and I'm getting these data using ajax.
This is my php code in the controller:
public function contactsPassports(){
// POST data
$this->load->model('contacts/contacts_international_pass_m');
$data = $this->input->post();
$passports = array();
$where = array('contact_id'=>$data['selected_id']);
$passports = $this->contacts_international_pass_m->where($where)->order_by('id','DESC')->get_all();
if(!empty($passports)) {
foreach($passports as $item)
{
$item->pass = $this->contacts_international_pass_m->get($item->nat_passport_num);
}
}
$this->data->passports = $passports;
echo json_encode($this->data);
}
And this is my ajax code:
$.ajax({
url:'/companies/ajax/contactsPassports',
method: 'post',
data: {"selected_id": contactID},
dataType: 'json',
async: true,
success: function(data){
var html = '';
$.each(data.passports, function(key, value) {
console.log(data);
html += '<div class="nationality_name" style="float:left">'+ value.nat_passport_num + '</div>' + '<div class="nationality_name_delimiter" style="float:left">'+', '+'</div>';
});
$('#passport').html(html);
}
});
But I want to remove the dublicate passports for every user. For example now I am getting this:
User 1
12345678, 1234, 1234, 123456, 123456
And I want to getting this:
User 1
12345678, 1234, 123456
You can use distinct query builder to select only distinct values:
$passports = $this->contacts_international_pass_m->distinct()->select('nat_passport_num')->where($where)->order_by('id','DESC')->get_all();

ajax success print multiple data

i am new in this ajax . i got a problem that is in my ajax coding i get a multiple data in loop so how can print that multiple data in ajax success
here is my code :
$.ajax({
url: 'ajaxdate',
data: {ending:ending},
type: 'POST',
success: function(data) {
$('#info1').text(data);
console.log(data.length);
alert(data);
/*for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}*/
}
});
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
echo $data['full_name'] = $detail['list']['full_name']."\n";
}
}
How i print that multiple data in ajax success
What you can do with is expect JSON as response.
I see the problem in your function if you are printing the full_name in loop and expecting HTML response, all it will be just a string.
What you can do is something like this
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
$data[]['full_name'] = $detail['list']['full_name'];
}
die(json_encode($data));
}
This will return a json array with collection of object of full_name eg [{full_name: 'ABC'},{full_name: 'cde'}]
Then add dataType : 'json' in you ajax.
Now you can iterate thorough the response you get in ajax success.
For an example you have this <ul id="showResultHere"></ul> tag, where you would like to show the result, then TRY this in your "success" AJAX :
success: function (data){
$.each(data, function(index) {
//alert(data[index]);
$("#showResultHere").append("<li>" + data[index] + "</li>");
});
}
Or, another way to show your "full_name" from your guestbook array, here is another option too :
success: function (data){
data.forEach(function(data) {
$("#showResultHere").append("<li>" + data + "</li>");
});
}

pass an array to action using ajax YII

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

RecorderJS uploading recorded blob via AJAX

I'm using Matt Diamond's recorder.js to navigate the HTML5 audio API, and feel this question probably has an apparent answer, but i'm unable to find any specific documentation.
Question: After recording a wav file, how can I send that wav to the server via ajax? Any suggestions???
If you have the blob you'll need to turn it into a url and run the url through an ajax call.
// might be nice to set up a boolean somewhere if you have a handler object
object = new Object();
object.sendToServer = true;
// You can create a callback and set it in the config object.
var config = {
callback : myCallback
}
// in the callback, send the blob to the server if you set the property to true
function myCallback(blob){
if( object.sendToServer ){
// create an object url
// Matt actually uses this line when he creates Recorder.forceDownload()
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create a new request and send it via the objectUrl
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "blob";
request.onload = function(){
// send the blob somewhere else or handle it here
// use request.response
}
request.send();
}
}
// very important! run the following exportWAV method to trigger the callback
rec.exportWAV();
Let me know if this works.. haven't tested it but it should work. Cheers!
#jeff Skee's answer really helped but I couldn't grasps it at first, so i made something simpler with this little javascript function.
Function parameters
#blob : Blob file to send to server
#url : server side code url e.g. upload.php
#name : File index to reference at the server side file array
jQuery ajax function
function sendToServer(blob,url,name='audio'){
var formData = new FormData();
formData.append(name,blob);
$.ajax({
url:url,
type:'post',
data: formData,
contentType:false,
processData:false,
cache:false,
success: function(data){
console.log(data);
}
}); }
Server side code (upload.php)
$input = $_FILES['audio']['tmp_name'];
$output = time().'.wav';
if(move_uploaded_file($input, $output))
exit('Audio file Uploaded');
/*Display the file array if upload failed*/
exit(print_r($_FILES));
I also spent many hours trying to achieve what you are trying to do here. I was able to successfully upload the audio blob data only after implementing a FileReader and calling readAsDataURL() to convert the blob to a data: URL representing the file's data (check out MDN FileReader). Also you must POST, not GET the FormData. Here's a scoped snippet of my working code. Enjoy!
function uploadAudioFromBlob(assetID, blob)
{
var reader = new FileReader();
// this is triggered once the blob is read and readAsDataURL returns
reader.onload = function (event)
{
var formData = new FormData();
formData.append('assetID', assetID);
formData.append('audio', event.target.result);
$.ajax({
type: 'POST'
, url: 'MyMvcController/MyUploadAudioMethod'
, data: formData
, processData: false
, contentType: false
, dataType: 'json'
, cache: false
, success: function (json)
{
if (json.Success)
{
// do successful audio upload stuff
}
else
{
// handle audio upload failure reported
// back from server (I have a json.Error.Msg)
}
}
, error: function (jqXHR, textStatus, errorThrown)
{
alert('Error! '+ textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
// handle audio upload failure
}
});
}
reader.readAsDataURL(blob);
}
Both solutions above use jQuery and $.ajax()
Here's a native XMLHttpRequest solution. Just run this code wherever you have access to the blob element:
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, "filename");
xhr.open("POST","upload.php",true);
xhr.send(fd);
Server-side, upload.php is as simple as:
$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output)
source | live demo

How to return ajax quired value in wordpress?

I have created a ajax call back but it returns an error value. The code is bellow which I'm using.
I'm sending value from checkboxes when it checked. and want to return value from postedfile listing_submit_demo.php
jQuery(function() {
jQuery('.list_category').bind('click',function() {
if(jQuery(this).is(':checked')) {
jQuery('#some_textarea').html(jQuery(this).val());
var id = jQuery(this).attr('id');
jQuery.ajax({
type:"POST",
data: {idvalue: id},
url: "<?php echo FRONTENDURL; ?>listing_submit_demo.php",
success:function(data){
alert(data);
}
});
}
});
});
In listing_submit_demo.php I'm getting checkbox id value and retrieving values from database and then returning the listed value but it returns value with debug error. So how to get proper value from it? The listing_submit_demo.php code is bellow:
<?php
//error_reporting(0);
$idvalue = $_POST['idvalue'];
global $cfield_tbl_name;
global $wpdb;
$query = "SELECT * FROM $cfield_tbl_name";
$val = $wpdb->get_results($query);
foreach($val as $x){
$cate = explode(',',$x->field_cate);
if(in_array($idvalue, $cate)){
$y .= $x->f_var_nm . ",";
}
}
echo $y;
//?>
Any help will be thankful in advance.
I have a suggestion that you can hook with the action "wp_ajax_$youraction" and "wp_ajax_nopriv_$youraction"
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
The example is inside the link, wordpress ajax should work fine with these hook.

Resources