jquery ajax not posting any data on codeigniter - javascript

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;
}

Related

Have problem when parsing data with JSON Parse

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.

AJAX success function not working when the page is load

here is my code in ajax
function loadcountries()
{
var p = document.getElementById("selectCntry");
while(p.firstChild)
{
p.removeChild(p.firstChild);
}
var data = {
action: "loadccc"
};
jQuery.ajax
(
{
type: "POST",
url: "ajax-ows2.php",
dataType: 'json',
async:false,
data:data,
success: function(msg)
{
alert(msg.test);
}
}
);
}
here is my ajax-ows2.php
<?php
$action = $_POST["action"];
include "dbconnect.php";
if($action == "loadccc")
{
$var = $action;
$response_array['test'] = $var;
header('Content-type: application/json');
echo json_encode($response_array);
}
?>
and here is my function call:
<script>
window.onload = loadcountries;
</script>
my ajax way is different. I really have no idea why it is not alerting when the page is load. Im really sure that my ajax-ows2.php is good and im sure that my function call is correct. Can somebody help me with this. This is not a duplicate one. I tried to used asynch:false but still not working.
try this format:
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: data,
url: 'ajax-ows2.php',
success: function (data) {
console.log(data);
},
error: function (error){
console.log(error);
}
});
since you are doing POST method, your data parameter must be a stringify, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How can I send files along with other field's data to webmethod is asp.net using jquery ajax call?

I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});

What is the right way of sending a var on AJAX

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/

Saving data to the database via JQuery .ajax

I am attempting to save 2 pieces of information to the database via JQuery using the .ajax function. I want to save the postID and the userID in WordPress. I think I get the jist of most of the function but need to figure out how to send an array to the processing page so I can insert it. This is what i have written so far:
$(document).ready(function() {
$('#saveme').click(function() {
$.ajax({
type: "POST",
url: "save_data.php",
contentType: "application/json; charset=utf-8",
data: "",
dataType: "json",
success: function (msg) {
alert("This recipe has been saved in your profile area!");
}
});
});
Can anyone shed some light one what goes into the data value to store the 2 pieces of information that I can send to the processing page?
I am using PHP and the code is in a .js file so I might need to also know to send the information over to the js file. Thanks!!
The type of Data to be sent to the server is JavaScript object containing zero or more key-value pairs or String. For your case
data: {
'postID' : $('#postID').val(),
'userID' : $(('#userID').val()
},
data should be a JSON object containing the data you want to save, i.e.
$(document).ready(function() {
$('#saveme').click(function() {
$.ajax({
type: "POST",
url: "save_data.php",
contentType: "application/json; charset=utf-8",
data: {postID: "A123456", userId: "HGSADKJ"},
dataType: "json",
success: function (msg) {
alert("This recipe has been saved in your profile area!");
}
});
});
Just create a JSON object and send it:
(assuming say there is an element on the page by the id of postID and userID
var jsonData = { "postID" : $("#postID").val(),
"userID" : $(("#userID").va;() }
$(document).ready(function() {
$('#saveme').click(function() {
$.ajax({
type: "POST",
url: "save_data.php",
contentType: "application/json; charset=utf-8",
data: jsonData,
dataType: "json",
success: function (msg) {
alert("This recipe has been saved in your profile area!");
}
});
});
You forgot to add data
$(document).ready(function() {
var postID='<?php the_id(); ?>';
var userId='<?php author_id(); ?>';
$('#saveme').click(function() {
$.ajax({
type: "post",
url: "save_data.php",
contentType: "application/json; charset=utf-8",
data: {postID: postID, userId: userId},
dataType: "json",
success: function (msg) {
alert("This recipe has been saved in your profile area!");
}
});
});

Categories