return object get into a variable - javascript

I need to get object array into a variable which is return from controller,to the success function in the ajax function,I need to concatenate id to the site_url,
here is my code
view
<div id="abc"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(document).ready(function() {
$('#myForm1').on("submit",function(e) {
//var form = $(this);
//dataString = $("#myForm1").serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('form_controller/insert_into_db'); ?>",
data: $(this).serialize(),
//dataType: "html",
success: function(data){
// top.location.href = "<?php echo site_url('form_controller/callform'); ?>";
//$.each(data.results, function(){
// $("#abc").append('<div><b>' + id.id + '</b></div><hr />');
//});
/*var site_url = "<?php// echo site_url('form_controller/callform/') ?>";
site_url = site_url +"/" + id;
$("#abc").load(site_url);*/
<?php //foreach(): ?>
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
site_url = site_url +"/" + "mydata" ;
//alert(mydata);
$("#abc").load(site_url);
$('#abc').html(data);
alert(data);
}//,
//error: function() { alert("Error posting feed."); }
});
});
});
</script>
here is my alert output
here I need to concatenate data as id for the site_url. here is my alert
[{"id":"215"}]
I need to get this as :
var id=215;

You can use JQuery for a parse JSON.
...
success: function(data){
...
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
var jobj=jQuery.parseJSON(data.responseText); //<---JSON to object
site_url = site_url +"/" + jobj.id ; //<--- jobj.id - your id
....

Set datatype to "json" and use data.id
dataType
Type: String
The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).

Related

Send js varible to php file with ajax

I would like to send my variable "var targetId" to my php file.
I try to make ajax request but nothing happens.
My js file :
$( ".project_item" ).click(function(e){
var targ = e.target;
var targetId = targ.dataset.id;
console.log(targetId);
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.ajax({
url: 'function.php',
type: "POST",
data: {idVoulu: targetId},
success: function(data){
alert(data);
console.log(data);
}
});
});`
And my php file to get the data
$idProject = (isset($_POST['idVoulu'])) ? $_POST['idVoulu'] : 0;
if($idProject==0) { echo ' ID not found';}
Can you tell me what's going wrong?
Well I can't Find a problem on your code but you can try this may be this will help you
var mydata = "idVoulu='+targetId+'"; // make a string
$.ajax({
url: 'function.php',
type: "POST",
data: mydata,
success: function(data){
alert(data);
console.log(data);
}
});
So, i made this and it works:
My js:
$( ".project_item" ).click(function(e) {
var targ = e.target;
var targetId = targ.dataset.id;
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.post('../function.php', { id: targetId }, function(response) {
console.log("reponse : ", response)
});
My php :
if (isset($_POST['id'])) {
$newID = $_POST['id'];
$response = 'Format a response here' . $newID;
return print_r($response);
}

How to change Object on javascript to echo this "object" on base url

i want to echo this array data ,i save on obj.format . but i cant echo this obj.format to url . script like this
$(".monitor").click(function() {
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url: 'get_data',
method: 'post',
dataType: 'json',
data: {
id_puskesmas: id_puskesmas
},
success: function(response) {
$.each(response, function(i, obj) {
$("#list-format").append("<li>" + obj.format + "</li>");
});
$("#title-modal").html(nama_puskesmas);
$("#exampleModalCenter").modal('show');
$("#button-submit").html(`Lihat data`)
$("#button-submit2").html(`Kirim Pesan`)
}
})
})
in this script we have obj.format .
$.each(response, function(i, obj) {
$("#list-format").append("" + obj.format + "");
});
i will echo this data to this link href (on last words before id="submit_modal"):
$("#button-submit2").html(Kirim Pesan)
this is obj format . i need moving it to #button_submit2

PHP not catching data from Ajax Jquery

Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});

javascript no response codeigniter

I have this drop-down dependent on the choices of the other two dropdown,
I already debugged it and the only error i see is, it never get success
here is my javascript
jQuery(document).ready(function(){
$("#GRADE").change(function() {
var TRANCHE = {"TRANCHE" : $('#TRANCHE').val()};
var GRADE = {"GRADE" : $('#GRADE').val()};
console.log(TRANCHE);
console.log(GRADE);
$.ajax({
type: "POST",
dataType: "json",
data: {
TRANCHE : "TRANCHE",
GRADE : "GRADE"
},
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown2/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
});
});
and here is my controller
public function dependent_dropdown2()
{
if(isset($_POST['TRANCHE']))
{
$data = $_POST['TRANCHE'];
$data1 = $_POST['GRADE'];
$this->output
->set_content_type("application/json")
->set_output(json_encode($this->EmployeeSalary_Model->getType2($data, $data1)));
}
}
why is it that it doesnt trigger the succes function?
It might be that the controller is not returning anything to the browser.
Try it without using the output class directly.
public function dependent_dropdown2()
{
if(isset($_POST['TRANCHE']))
{
$data = $_POST['TRANCHE'];
$data1 = $_POST['GRADE'];
echo json_encode($this->EmployeeSalary_Model->getType2($data, $data1));
}
}
It looks like the data structure being provided to $.ajax is off too.
jQuery(document).ready(function () {
$("#GRADE").change(function () {
var posting = {TRANCHE: $('#TRANCHE').val(), GRADE: $('#GRADE').val()};
$.ajax({
type: "POST",
dataType: "json",
data: posting,
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown2/",
success: function (data) {
console.log(data);
var select = $('#SAL_ID');
select.html('');
$.each(data, function (i, option) {
select.append("<option value='" + option.ID + "'>" + option.AMOUNT + "</option>");
});
}
});
});
});
There is a little typo in your ajax call.
I think you have to pass the variables (TRANCHE,GRADE) in the data object of ajax instead you passed strings("TRANCHE","GRADE").
Here is the code
jQuery(document).ready(function(){
$("#GRADE").change(function() {
var TRANCHE = {"TRANCHE" : $('#TRANCHE').val()};
var GRADE = {"GRADE" : $('#GRADE').val()};
console.log(TRANCHE);
console.log(GRADE);
$.ajax({
type: "POST",
dataType: "json",
data: {
TRANCHE : TRANCHE, //pass the variable
GRADE : GRADE
},
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown2/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
});
});
And rest of things looks good. you can debug the post request by just printing it like
public function dependent_dropdown2()
{
if(isset($_POST['TRANCHE']))
{
$data = $_POST['TRANCHE'];
$data1 = $_POST['GRADE'];
print_r($data1);
print_r($data2);
}
}
Try, by removing object from the varibles,
jQuery(document).ready(function(){
$("#GRADE").change(function() {
var TRANCHE = $('#TRANCHE').val();
var GRADE = $('#GRADE').val();
console.log(TRANCHE);
console.log(GRADE);
$.ajax({
type: "POST",
dataType: "json",
data: {
TRANCHE : "TRANCHE",
GRADE : "GRADE"
},
url: "<?php base_url(); ?>EmployeeSalary/dependent_dropdown2/",
success: function(data){
var select = $('#SAL_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.ID+"'>"+option.AMOUNT+"</option>");
});
}
});
});
});
----------------------Added return code-------------------
In return method use
public function dependent_dropdown2_asd()
{
if(isset($_POST['TRANCHE']))
{
$TRANCHE = $_POST['TRANCHE'];
$GRADE = $_POST['GRADE'];
$data=array('Responce'=>200);
header('Content-Type: application/json');
echo json_encode($data);
}
}

What is the proper or best way to get data from ajax?

I have this javascript code with ajax.
$('#btnCart').click(function() {
var pName = document.getElementById('prodName').value;
$.ajax({
url: 'index.php',
data: 'prdName='+pName,
success: function(data) {
$('#prod').html(data);
}
});
});
I want to get the value of pName to be returned on my php. Here's my code on my index.php side:
<?php
$prodName = $_GET['prdName'];
echo $prodName;
?>
But it returns Unidentified index: prdName.
How can I get the value from ajax to my php? Please help...
if(isset($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo $prodName;
}
You should send the data as:
data: {prdName: pName},
add this to your PHP code:
if(!empty($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo cartTable($prodName);
}
also some corrections in js:
$('#btnCart').click(function() {
var pName = $('#prodName').val();
$.ajax({
url: 'index.php',
data: {prdName:pName},
success: function(data) {
$('#prod').html(data);
}
});
});
In index.php Get the prdName value from $_POST[] global array.
to send data to index.php file add type type:'POST' in ajax code
$.ajax({
type:'POST',
url: 'index.php',
data: {'prdName': pName},
success: function(data) {
$('#prod').html(data);
}
});
or you can use $.post() method in jQuery
$.post(
'index.php',
{'prdName='+pName},
function(data) {
$('#prod').html(data);
}
});
in index.php
if(isset($_POST['prdName']){
$prodName = $_POST['prdName'];
echo $prodName;
}

Categories