How to pass value using javascript success function in old CI - javascript

i'm working with an old codeigniter. i'm calling a onchange function. i want to get data from controller and show it to a input filed which is an array.
view page code:
<select name='feed_id[]' style='width:95px;'onchange="getfeedstock(0,this.value)"><?=$this->mod_feed->get_feeds()?></select>
<span><input type='text' name='stock[]' readonly value='' class='num_txt stock<?=$inc?>' /></span>
javascript:
<script >
function getfeedstock(i,obj){
//alert(obj);
$.ajax({
url:base_url+'feed_sale/get_feed_stock',
type:'post',
data:{
feed_id:feed_id
},
success:function(data){
//alert(data);
//var stock=5;
//$('.stock').val(stock);
},
error:function(error,msg){
alert(error+msg);
}
});
}
</script>

Use Output class of Codeigniter
https://www.codeigniter.com/userguide2/libraries/output.html
it will set page header to JSON type. And pass array using json_encode();
all array of PHP will get in JSON object format in success callback of Ajax
success: function(data) {
alert(data.msg); // showing [Object][object]
//all array visible in console log Ctrl+Shift+I (in chrome)
console.log(data);
}

Related

post values using ajax but js don't get the updated values

I ran simple ajax too post values in the same page which I saves into session variables, which works fine but whenever i print those session variables in console it don't shows the latest values.
<script>
$(function(){
function showValues() {
jQuery.ajax({
type: "POST",
data: $( "form" ).serialize(),
success: function(data){
var x = <?php echo json_encode($_SESSION['q10']); ?>;
console.log(x);
}
});
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
});
</script>
Above script serialize the values from radio, checkbox and select inputs later i saved those on the following variables
<?php
if(isset($_POST['q10']))
{
if($_POST['q10'] == 2){
$_SESSION['q10']=1;
}else{
$_SESSION['q10']=0;
}
}
Initially I set $_SESSION['q10'] = 0 and console shows this value but whenever i changed the value it shows the previous value. It didn't update
P.s I get the changed values after refreshing the page. shouldn't i get the updated values in the console
<nav class="segmented l3_seg">
<input type="radio" name="q10" value="1" id="10a">
<label for="10a">Richtig</label>
<input type="radio" name="q10" value="2" id="10b">
<label for="10b">Falsch</label>
</nav>
Many comments and article you will found regarding php is running in server side and Javascript is running in client side. PHP run one time and rendered data to browser one time if you want to reconnect with server/php again you need to use ajax that you are doing.
In short , you need to use js variable which containing ajax returned response.
Return response from php
if(isset($_POST['q10']))
{
....
return $_SESSION['q10'];
}
And display in console as
success: function(data){
console.log(data);
}
Read about ajax dataType

convert form data using serializeArray() and sending php via .Ajax

This is my first post. I have searched for other solutions and what I've found only deals with components of this question. Basically this is what I'd like to do:
Capture form data (tested, working);
Convert form data using serializeArray() or serialize() (tested both options, working and outputs to console correctly);
Send this information to the server through Ajax (not working); and
PHP saves array as a CSV (not yet started).
Bellow is the code I'm using. But first, here are some alternatives I've tried. Usually I get this: array(0) { }
'dataType' as Json - returns error;
'GET', 'POST' and 'REQUEST' - PHP shows empty array;
use form.serialize() - PHP shows empty array;
use form.serializeArray() - PHP shows empty array; and
var_dump($_POST), var_dump($_GET), var_dump($_REQUEST).
var serialisedForm = $(form).serializeArray();
var serialisedData = JSON.stringify(serialisedForm);
console.log(serialisedData); //working
console.log(serialisedForm); //working
$.ajax({
type: "POST",
url: "datacapture.php",
data: {
serialisedForm, //tested using serialisedData as well
},
success: function() {
window.open('datacapture.php');
},
error: function() {
alert("the form data has not been sent to the server");
}
})
and here is the datacapture.php script I'm using to test the information flow.
<?php
var_dump($_POST);
?>
EDIT - and here is a sample form item, reading .text and .name from my settings.json file:
<tbody>
{
this.props.settings.schemes[0].questions.map((q, i)=> {
return <tr><td>{q.text}</td><td><div class="YesNo"><input type="radio" required name={q.name} value="yes">Yes</input><input type="radio" required name={q.name} value="no">No</input></div></td></tr>
})
}
</tbody>
just change 1seralisedForm1 to 1seralisedData1 it will return an json object to php which can be seen by doing:
echo json_decode($_POST);

update value after Ajax call PHP

I want to update TextBox value on basis of selectChange
HTML:
<select name="abc" id="def">
<option value="1">1st Record</option>
<option value="2">2nd Record</option>
<option value="3">3rd Record</option>
</select>
<input value="" name="final_value" id="final_value" />
JS:
$("#selectboxid").change(function() {
$.ajax({ url: "test.php", data:"value="+$("#def").val() , success: function(){
$("#final_value").val(data);
}});
});
PHP:
<?php
function abc($data){
// Database operations
echo json_encode($response);
}
abc($_GET);
?>
With this approach value is updating very nicely But i have below points:
above approach prints values and one can see in Network Tab. Is it a nice way to do it?
I also tried using return $response in PHP function but then response is null and console.log(data) in ajax shows null array.
So, how to update Input value after Ajax without echoing. I do not want that user shall see any type of response even in Network Tab.
I have seen various websites which does the same and not showing any values in Network tab.
** Is there any different approach to do this?
You can alternatively try like this
All HTTP requests can possible to watch on their own network. You can restrict this
$(document).ready(function(){
var params = {};
params['value'] = $("#def").val();
$.post('test.php', params, function(response){
console.log(response);
alert(response);
});
});
I've not tested this, but immediatly I've spotted a couple of things:
$("#selectboxid").change(function() {
// .val is a function
$.ajax({ url: "test.php", data:"value"+$("def").val() , success: function(data) { //Your success callback needs to take an argument
//data will be either a string or a JSON object, so depending on what you want from it, you'll probably not be able to just pass it to the val() function
$("#final_value").val(data);
}});
});
Not 100% complete I'm sure, but hopefully will give you a good starting point
It should be like this
$("#selectboxid").change(function() {
$.ajax({
url: "test.php",
data:{
"value": $("def").val()
},
success: function(){
$("#final_value").val(data);
}
});
});

Toggle div depending on controller variable value

EDITED
I have a "Save Changes" button that I want to click and toggle a div with the message "Changes saved". I do it like this:
HTML:
<input type="submit" id="savebtn" name="save" value="Save Changes"/>
<input type="hidden" id="res" name="res" value="#ViewBag.result"/>
<div class="success">Changes saved</div>
JQuery
$('#saveButton').click(function () {
var aux = res.value.toString();
if ($('#res').val() == "OK")
$(".success").show();
alert(aux);
});
However, I need the button to actually save the changes and, if the operation was successful, then show the message div. So, in my cshtml file I have a result variable that contains the success or failure of the operation.
CSHTML:
ViewBag.result = result;
Now, I need to show that message div depending on the result variable: I need to somehow make it a parameter for the JQuery function. I'm passing it in a ViewBag.
NOTE: when the page loads, the viewbag is empty. It only gets its value after the button click. And after that, the viewbag is filled and I wanted it to be used in the jQuery function but I'm not getting any luck.
Pass that result in a viewbag,
Acces that viewbag value in jquery and show/hide your div accordingly
Assuming you can store the result in input hidden field, use below query to access result and initially success div is hidden :
<input type="hidden" id="result" value"success"/>
jQuery :
$(function(){
if($('#result').val()=="success")
$(".success").show();
});
you can check it in a simple if condition
if($('#result').val()=="success")
$(".success").toggle();
or You can use Ajax method
function Save() {
$.ajax({
url: "Your Url", // Current Page, Method
data: Your data // better if you parameter map as JSON
type: "POST",
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 100000, // AJAX timeout
success: function (result) {
$(".success").toggle();
},
error: function (xhr, status) {
alert("An error occurred while processing");
}
});
}
Now call this save() in your button click

How to return back json data from script page?

I had a json file results.json Which shown below. And I had a html file contain some script. This is for retrieve data data. When I am enter into the html page which call a script function get_machFollow(que_script) this function is for receive json file data. The function is works fine and which alert correct output, But after this function return some data to my HTML page.
My JSON file
{"mach_fol_4": {"match_l":
["7","8","99"],"attempts":"0","feedback_true":"You are right!",
"feedback_false":"Sorry! wrong answer."}}
This is my script function. This function is works fine but I can't alert the return value from HTML page. That shows undefined.
function get_machFollow(que_script)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
return return_var;
});
}
This is my html file
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(document).ready(function(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
alert(mach_follow_js);//Wrong output
});
</head>
<body>
<p>Hello world</p>
</body>
</html>
are you intending return return_var; to be inside the get_machFollow scope, because right now its inside the jquery function scope and will not return value to the main page
Here below JSON data fetched by AJAX. It passing JSON Data Object in Alert.
You can use it as you want. also can Iterate data using for loop or $.each function.
$(document).ready(function(){
var mach_follow_js;
// mach_follow_js=get_machFollow('mach_fol_4');
//JSON Data Fetched by AJAX
$.ajax('results.json',{
type:'GET',
dataType: "json",
jsonCallback: 'successCallback',
async: true,
beforeSend: function () {
//if you want to show loader
},
complete: function () {
//hide loader after download data
},
success: function (resultJSON) {
mach_follow_js = resultJSON; // assigning to Global variable ProductResult
alert(mach_follow_js);
console.log(mach_follow_js);
},
error: function (request, error) {
alert('Network error has occurred please try again!');//error
}
})
});
There are multiple ways by which you can do it. One of them is pass a callback handler to your method which will be called when you get the response. Try this:
function get_machFollow(que_script, sCallback)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
sCallback.call(null /* context */, return_var);
});
}
$(document).ready(function(){
var mach_follow_js;
get_machFollow('mach_fol_4', function(output) {
alert(output);
match_follow_js = output;
});
});
Use ajax callback function $.getJSON() is actually an ajax function. So you need to apply callback to perform this action.

Categories