How to return JS value using AJAX - javascript

I have a code like this
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
.....
.....
if(condition here){}
});
});
});
I need to check a condition according to the value returned from get_projectName.php. Let get_projectName.php have $abc = 1; and according to this value I need to use if condition.

Your jquery condition will be totally depend on the type of data returned from the php function. Let's check for the example:-
Example 1 :-
If your php code is :-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = 1; // as you said
}
echo $data;
?>
Then jquery will be:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- library needed-->
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){ // you need to check that it is working or not because i don't know from where it is coming
var value = $('#myHref').val(); // same as above check yourself.
$.get('get_sales_price.php','',function(data){
if(data ==1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Example 2:-
But if your php code is like below:-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = Array('a'=>1,'b'=>2);
}
echo json_encode($data);
?>
then jquery will be like below:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_sales_price.php','',function(data){
var newdata = $.parseJSON(data);//parse JSON
if(newdata.a ==1 && newdata.b !== 1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Note:- these are simple examples, but conditions will vary in jquery, based on returned response from php. thanks.

Forgot the .done
$.get('get_projectName.php',
{id:value}
).done(function(data) {
console.log(data)
var data2 = JSON.parse(data);
if(data2.abc === 1)
{
//Do something
}else{
//Else Do something
}
});

You can write code as below -
//At javscript end
$.get( "get_projectName.php", function( data ) {
if(data == "1"){
// do your work
}
});
// At php end
<?php
$abc = 1;
echo $abc;
?>
Hope this will help you.

In main-php-file On change of value, Fetch the value pass it a php file sub-php-file via ajax
In sub-php-file, echo the ouput in json format
Retrieve the output and do the calculation
jQuery library, if never included
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
ajax
<script type="text/javascript">
$(document).ready(function(){
$('#myHref').on('change', function(){
var value = $('#myHref').val();
$.ajax({
type: "POST",
url: "get_projectName.php",
data: { id:value },
dataType: "json",
success: function(theResponse) {
var abc = theResponse['abc'];
if (abc == 1) {
//Do something
} else {
//Else Do something
}
}
});
});
});
</script>
get_projectName.php
<?php
$id = isset($_POST['id']) ? $_POST['id'] : '';
$ReturnArray['abc'] = 1;
echo json_encode( $ReturnArray );
?>

Related

Request value with JavaScript and show it on php file

I want to make something like this in order to deliver a JSON:
<?php
header("Content-Type:application/json");
require "data.php";
if(!empty($_GET['name']))
{
$name=$_GET['name'];
$price =$_GET['value'];
if(empty($price))
{
response(200,"Product Not Found",NULL);
}
else
{
response(200,"Product Found",$price);
}
}
else
{
response(400,"Invalid Request",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status_message);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
The "value" on the data.php file is found by a JavaScript like this:
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
</script>
But I don't know how to pass it from the JavaScript variable to the $price variable in this php file... could you help me?
As Andrew suggests in his comment, you can use Ajax to get the data from your PHP-Script:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <!-- add jQuery for easy AJAX functions -->
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
$.get("/path/to/file.php?name=&value="+value, funtion(data) { // get data from PHP-Script
data = JSON.parse(data);
if (data.status_message === "Product Found") // if a product was found, set "price" to the price
var price = data.data
});
</script>

How do I save form data to sql with jquery and php

I have tried number solutions and cannot figure out what I am doing wrong.
I have the following input element:
<input type="checkbox" data-layout="fixed" class="pull-right" value="1">
just before my closing body tag I have the following jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('mysqlfunc.php', { value:value }, function(data){
if(data == 1){
}
});
}
});
</script>
In mysqlfunc.php file I have
<?php
include "../../inc/config.php";
include "../../inc/funcs.php";
#mysql_connect($dbhost,$dbuser,$dbpass);
#mysql_select_db($dbname) or die( "Unable to select database");
include "../../inc/userauth.php";
if ($_POST && isset($_POST['value'])) {
$value = mysql_real_escape_string($_POST['value']);
$sql = "UPDATE members SET fixed = '".$value."' WHERE username='".$_SESSION['uid']."'";
} else {
}
?>
My expectation is when I click the input checkbox, a value "1" is saved into the "members" table in the "fixed" column where the username is equal to the session uid.
I can echo the uid, so that is working. Its not giving any errors, so its connecting to the database it seems. Yet checking the input textbox, does not change the value in the database.
I get no js errors at all, I get no php errors, just not saving.
What am I doing wrong? Example working code if at all possible would be very helpful.
This line in your script is wrong.
var checked = $(this).attr('checked');
change it to
var checked = $(this).is(':checked')
You forget to execute your query use mysql_query
$sql = "UPDATE members SET fixed = '".$value."' WHERE username='".$_SESSION['uid']."'";
mysql_query($sql);
What version of jquery you used ? And check if post request really done or not Try using .prop :
$("input[type='checkbox']").on('click', function(){
var checked = $(this).prop('checked'); //<---- Here
if(checked){ // here returned true or false
var value = $(this).val();
$.post('mysqlfunc.php', { value:value }, function(data){
if(data == 1){
}
});
}
});
or....
$("input[type='checkbox']").on('click', function(){
if( this.checked ){ // <-- just checked directly
var value = $(this).val();
$.post('mysqlfunc.php', { value:value }, function(data){
if(data == 1){
}
});
}
});
And like #Saty said, put mysql_query($sql); to execute those query.
Your JS code will look like.
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).is(':checked');
if(checked){
var value = $(this).val();
$.post('mysqlfunc.php', { value:value }, function(data){
if(data == 1){
}
});
}
});
});
And You missed to execute SQL so, your PHP code will look like.
<?php
include "../../inc/config.php";
include "../../inc/funcs.php";
#mysql_connect($dbhost,$dbuser,$dbpass);
#mysql_select_db($dbname) or die( "Unable to select database");
include "../../inc/userauth.php";
if ($_POST && isset($_POST['value'])) {
$value = mysql_real_escape_string($_POST['value']);
$sql = "UPDATE members SET fixed = '".$value."' WHERE username='".$_SESSION['uid']."'";
mysql_query($sql);
} else {
}
?>

How can we pass values to dialog widget?

function click1(a)
{
var srcdivid =$(a).closest('div').attr('id');
$("#pagetemplate").dialog("open"); return false;
}
Here I get the value srcdivid and i hav to pass this value to above dialogue.how its possible?
My dialogue widget code is following
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'pagetemplate',
'options'=>array(
'title'=>'Page Template',
'autoOpen'=>false,
'modal'=>true,
'width'=>1000,
'height'=>300
),
));?>
<input type="hidden" name="padeidvalue" id="padeidvalue">
<?php if(count($templatemodel) > 0){
for($i=0;$i<count($templatemodel);$i++){
echo "<div class='temp-thumb'><a class='".$templatemodel[$i]['template_image_name']."' onclick='addtemplate(".$templatemodel[$i]['page_template_id'].");' href='#'></a></div>";
}
}else{
echo "<p>Opps!. No Templates Found></p>";
}?>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');?>
Here I call the addtemplate function. Its definition as follows
function addtemplate(params){
var srcdivid ="";
alert(srcdivid);
alert(params);
$.ajax({
url:baseURL+"/index.php/MyAlbums/AddTemplatesToDiv",
type:'POST',
data:{"templateid":params,"divid":"srcdivid" },
success:function(data){
$("#"+srcdivid).html(data.template);
$("#pagetemplate").dialog("close");
$(".imgborderclass").removeClass("imgborderclass");
addClass();
addComm();
},
});
}
I have to get srcdivid in this addtemplate function which i pass from click function. help me please..
Use data() method of jQuery.
function click1(a) {
var srcdivid =$(a).closest('div').attr('id');
$("#pagetemplate").data('srcdivid', srcdivid);
$("#pagetemplate").dialog("open"); return false;
}
function addtemplate(params) {
var srcdivid = $("#pagetemplate").data('srcdivid');
alert(srcdivid);
...
}

Php calling javascript function

I can do that? Im trying to call a javascript function after conditional php "if"
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_get['id']){
echo "<script>functioncall({$_get['id']});</script>";
}
?>
Use $_GET instead of $_get in php condition, I have corrected some of the errors like script tag script type, and PHP $_GET
<script type="text/javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_GET['id'])){
echo "<script>functioncall('{$_GET['id']}');</script>";
}
?>
Or just using JS ?
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
And do like...
var id = getQueryVariable('id');
if(id) {
alert(id);
}
Credit : http://css-tricks.com/snippets/javascript/get-url-variables/
As Quentin said you are exposed to XSS attacks. Don't ever put anything into your page from GET variables (url variables) - 'id' in your case.
Anyways, if you want to call a function based on a php condition, you can do something like this:
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(condition-goes-here){
?>
<script type="text/javascript">
functioncall(<?php echo 'Put in your php data' ?>);
</script>
<?php } ?>
I haven't checked it, hope it should work. If your condition returns false, your function call will not be put into your page.
It's not a good practice though.

Javascript send array to PHP using ajax

I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()

Categories

Resources