VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10 - javascript

I want to get data with ajax and jquery. But i get thhis error and i dont know how to fix it.
VM5601:2 Uncaught SyntaxError: Unexpected token < in JSON at position 10
This is my code.
Model
public function GetBloodCatById($id)
{
$this->db->from('tbl_blood_cat');
$this->db->where('id_blood_cat',$id);
$query = $this->db->get();
return $query->row();
}
Controller
public function ajax_edit($id)
{
$data = $this->Blood->GetBloodCatById($id);
echo json_encode($data);
}
View
function edit_blood(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('Home/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
contentType: 'application/json',
success: function(data)
{
$('[name="id_blood_cat"]').val(data.id_blood_cat);
$('[name="catName"]').val(data.category);
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
This is data that will be get
{"id_blood_cat":"1","category":"Plasma","createBy":"nicky","updateBy":null,"createAt":"2017-05-11 18:30:09","updateAt":"2017-05-11 18:30:09","flag":"1"}
I had been strugle with this for hours. Please help me thx.

wrapping json in array is always good choice.Here i have modified your function little
public function ajax_edit($id)
{ $res = array();
$data = $this->Blood->GetBloodCatById($id);
$res = $data;
echo json_encode($data);
}
and ajax success handler is like
........
success: function(data)
{ response = $.parseJSON(data);
$.each(data, function (i, item) {
$('[name="id_blood_cat"]').val(response.id_blood_cat);
$('[name="catName"]').val(response.category);
}
$('#myModalBloodCat').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Blood Cat'); // Set title to Bootstrap modal title
},
........

Reomve php tag and try to set url like this
url : "/Home/ajax_edit/?id=" + id,

Try: url: 'file:///Home/ajax_edit/?id='+id

Related

Extract text from DIV on HTML jQuery POST response

I'm coding a website and decided to perform a jQuery POST to call a PHP function, everything worked but instead of only a DIV as a response I got a whole HTML page. My doubt is: how can I extract the text from the DIV I encapsulated it with the id "response"?
Here is the JS and PHP code:
const showModal = (id) => {
$.post("<?php echo SITE_URL;?>/index.php/crewdesk/getFlightInfo/"+id, (data) => {
console.log(data)
});
$("#modalTitle").text(id);
$("#bookModal").modal("show")
}
public static function getFlightInfo($id)
{
$condition = " AND s.id = '$id'";
echo "<div id='response'>";
echo json_encode(CrewDeskData::getFlights(self::$stats['location'], "$condition"));
echo "</div>";
}
And here is the console log of the response->
Change you jQuery code to this below.
Using $.ajax which is similar to $.post
If you just want to return json data from your PHP file just use dataType: 'json' in your $.ajax I am set to receive html as your echo a div only.
const showModal = (id) => {
$.ajax({
type: 'POST',
url: '<?php echo SITE_URL;?>/index.php/crewdesk/getFlightInfo/' + id,
dataType: 'html',
success: function(data) {
console.log(data)
$("#modalTitle").text(id);
$("#bookModal").modal("show")
}
},
error: function(xhr, textStatus, errorThrown) {
//handle error here
}
)
}
}
Change your PHP code to this below
public static function getFlightInfo($id){
$condition = " AND s.id = '$id'";
echo "<div id='response'>".json_encode(CrewDeskData::getFlights(self::$stats['location'],"$condition"))."</div>";
}

AJAX POST group of form variables to PHP

I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?
You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};
You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

500 Internal server error when save proccess using ajax

I want to ask why my codeigniter when add data become error 500 internal server when the save proccess. I dont know anything about this problem please help me all.
This is ajax code in view
function save()
{
$('#btnSave').text('menyimpan...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('edulibs/ajax_add')?>";
} else {
url = "<?php echo site_url('edulibs/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('menambahkan / update data error');
$('#btnSave').text('Simpan'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
And this is my controller
public function ajax_add()
{
$this->_validate();
$data = array(
'nama' => $this->input->post('nama'),
'nim' => $this->input->post('nim'),
'pembimbing1' => $this->input->post('pembimbing1'),
'pembimbing2' => $this->input->post('pembimbing2'),
'subyek' => $this->input->post('subyek'),
'judul' => $this->input->post('judul'),
'tanggal' => $this->input->post('tanggal'),
'tautan' => $this->input->post('tautan'),
);
$insert = $this->edulibs->save($data);
echo json_encode(array("status" => TRUE));
}
In order to use site_url() load url helper in your controller first.like this..
$this->load->helper('url');
OR load helper in application/config/autoload.php
And in success function of your ajax use JSON.parse() to parse your json response into object.Like this
success: function(response)
{
var data = JSON.parse(response);//OR var data = eval(response);
if(data.status) //if success close modal and reload ajax table
{
//code here
}
else
{
//code here
}

jQuery's JSON Request

I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');

Categories