I got problem when parsing JSON from my AJAX. This is my error and the data that I want to parse
This my code:
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
data: { kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust:
codeCustomer },
success: function(result) {
if(result) {
console.log(result);
obj = $.parseJSON(result);
}
My controller
public function get_produk_by_eancode() {
$eancode = $this->input->post('kodePilihan');
$kodeScala = $this->input->post('kodeScala');
$codecust = $this->input->post('codecust');
$barangPilihan = $this->web_ordering_model->get_produk_by_eancode_page3($eancode, $kodeScala, $codecust)->row_array();
echo json_encode($barangPilihan);
}
My result data from the controller or you can see in picture
{"SC01132":"*1038 AR BRU KM","SC01002":"BOX-50 dengan Roda","SC01011":"A-19","brand":"Kiramas","verpacking":12,"List1":"76250.00000000","SC01001":"625050","Free":".00","LastTglProduksi":"1900-01-01 00:00:00.000","PricelistName":"Netto"}
You get this error because what you give to parseJSON is not a string.
First try to add content-type to you AJAX call :
contentType: "application/json; charset=utf-8",
dataType: "json",
Also you can convert your object to a string.
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
dataType: "json", //changes
data: ({ kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust: codeCustomer }),
success: function(result) {
if(result) {
console.log(result);
var obj = JSON.parse(result); //changes
console.log(obj); //changes
}
}
Solved by this code
$.trim()
Sorry for my long report, thanks.
Related
New to Web development and multiple scripting languages and how they mesh together...
I'm looking to return the entire SQL table (or a subset of it) from PHP and iterate through the values in JS and can't quite get it to work any help is appreciated.
In PHP encoding the array like this.
//get SQL data
$return_arr[] = array("id" => $id, "otherinfo" => $otherinfo);
echo json_encode($return_arr);
The ajax code I have looks like this but is where I'm getting tripped up...
jQuery.ajax({
type: "POST",
url: 'example.php',
type: 'POST',
data: { i: i },
dataType: "json",
success: function(response)
{
for(var i=0; i<response.length; i++)
{
var info = response[i].otherinfo;
var title = document.createElement("div");
var titletext = document.createTextNode(titledb);
title.appendChild(info);
}
}
)}
Thanks
I think its a syntax mistake.
jQuery.ajax({
url: 'example.php',
type: 'POST',
data: { i: '' },
dataType: "json",
success: function(response)
{
// code here
}
}) // <--- here
hy please help me i working on ajax but when i var_dump the data it seem empty
object(stdClass)#20 (0) { }
$.ajax({
url: base_url+"process_redeem_check",
data: $("#formId").serializeArray(),
type: "POST",
dataType: "json",
contentType: "application/json",
thats is my javascript code
public function process_redeem_check()
{
$input = (object) $this->input->post();
$check = $this->gemstone_model->redeem_check($input);
if ($check->success === TRUE) {
echo json_encode(array('status'=>true));
} else {
echo json_encode(array('status'=>false));
}
}
that my controller please help me i done searching all day
To use $this->input->post() initialize the form helper. You could do that by default in config folder's autoload.php.
include form in the the array.
$autoload['helper'] = array('form');
and use .serialize() instead of serializeArray()
$.ajax({
url: base_url+"process_redeem_check",
data: $("#formId").serialize(),
type: "POST",
dataType: "json",
contentType: "application/json",
And then check you datas your are getting or not
public function process_redeem_check()
{
$input = $this->input->post();
print_r($input);exit;
}
I'm writing my first Ajax request, on a Groovy/Grails platform.
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
data: {source:"${source}"},
success: function (response) {
jsonData = response;
var res = JSON.parse(jsonData);
alert(res);//
}
});
Here is the response of my controller "url"
def result = [ value: 'ok' ]
render result as JSON
But it does not work and i get an error message in my browser
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var res = JSON.parse(jsonData);
I don't understand , the response seems to be a nice formatted JSON ?
EDIT i did a print as Paul suggests :
If i execute
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response)
console.log(response.value)
jsonData = response;
}
});
The first print is :
Object { value="ok"}
The second print is
ok
If i want to get the result, how is the proper way ?
Do i have to assign the value inside the statement "success: function (response) { "
doing something like
var result
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
result = response.value
}
});
console.log("result : "+result);
This code works for me !!
Or perhaps there is a way to get the result, doing something like
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
}
});
var result = newDataB.response.somethingblablabla
or
var result = OneFunction(newDataB.response)
??????
You can make object stringified before passing it to parse function by simply using JSON.stringify().
var newDataB = $.ajax({
method: 'post',
url: "${createLink(controller: 'util',action: 'test')}",
async: false,
data: {source: "abc"},
success: function (response) {
jsonData = response;
var res = JSON.parse(JSON.stringify(jsonData));
console.log(res);//
}
});
Hopefully this may help.
You shouldn't need to parse it, if your server is providing json.
You can use dataType though to force jQuery to use a particular type:
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response);
}
});
Notice: Undefined index: query in C:\xampp\htdocs\Java\Search\instant-search.php on line 71
{"names":[]}
This is my Php
$query=$_POST["query"];
$matchType=isset($_POST["match_type"])? $_POST["match_type"]:MatchType::CONTAINS;
processRequest($query,$matchType);
Here is my ajax script
$("#query").keyup(function(){
var q=$(this).val();
var match_type=$("input[type=radio]:checked").val();
var data={'query':q,'match_type':match_type};
if(q.length==0){
$("#results").html("");
return false;
$.ajax({
url:"/Java/Search/instant-search.php",
data:data,
type:"post",
dataType:"json",
success:function(res) {
var tmpl=$("#names_tmpl").html();
var html=Mustache.to_html(tmpl,res);
$("#results").html(html);
}
});
As per your comments if both of them match_type and q are getting values than use ajax with data as:
$.ajax({
url:"/Java/Search/instant-search.php",
data: "query="+q+"&match_type="+match_type ,
type:"post",
dataType:"json",
success:function(res) {
var tmpl=$("#names_tmpl").html();
var html=Mustache.to_html(tmpl,res);
$("#results").html(html);
}
});
To change the type of request use method property not type and use Uppercase string POST jQuery.ajax:
$.ajax({
url: "/Java/Search/instant-search.php",
data: data,
method: "POST",
dataType: "json",
success: function(res) {
var tmpl=$("#names_tmpl").html();
var html=Mustache.to_html(tmpl,res);
$("#results").html(html);
}
});
I have a javascript function that calls a Webmethod. I tried sending a regular string to the webmethod and it works. On var empid= $('#' + txtId).val() Im getting the right value of the text box. What is the right way of sending empid over ajax ? I have tried a few thing and they dont work. Any help would be appreciated. Thanks
.js
function toggle(txtId, lblname, txtcode) {
var empid = $('#' + txtId ).val();
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{ id: empid }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).html(data.d);
}
});
}
.asmx.vb (webmethod)
Public Function GetEmployeeName(ByVal id As String) As String
Return "It works"
End Function
This is a screen shoot when removing contentType
Instead of
data: '{ id: empid }',
use
data: { id: empid },
Its sending JSON
Use dataType:"json" for json data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablname> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
You can use like below:
var empid=$('#txtEmpId').val();
Pass empid in data as
data: { id: empid },
Check out the fiddle here: http://jsfiddle.net/gN6CT/103/