I have one file json.js and one php function in php file .in json.js i want to check value returned by php function if value returned by function is 0 jquery should perform :$(':input').prop('disabled', true); otherwise nothing –
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if($('select[name="'+k+'"]').val(v)){
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
// Here I want to check condition of php function if value returned by fucntion is 0 it should perform :$(':input').prop('disabled', true); otherwise nothing //
});
}, 'json');
}
My php function:
function ronly($id) {
//$id=$_POST['noces'];
$sql = "SELECT COUNT(noces) FROM alterdetail WHERE noces = '$id'";
$sql.=';';
//echo "QUERY <br/>";
//echo $sql;
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($row['COUNT(noces)'] > 0)
{ echo "you can not alter data";
return 0;
}
else
{
echo " data new ";
return 1;
}
}
You can't, as Javascript is client-side executed, and PHP is server-side executed ...
A "solution" would be to assign a Javascript variable into the PHP file that you'll read into the Javascript file, as variable are global.
Use jQuery if possible.
$('#result').load('ajax/test.php', function() {
alert('Function called');
});
Or try JQuery forms. Use a form to submit any data, and it'll give you the response as a text or JSon object.
http://jquery.malsup.com/form/#ajaxSubmit
Here is an example for you:
$('#anyForm').ajaxForm({
url: "process.php?proc=7",
dataType: 'html',
success: function(responseText) {
if(responseText == "0") {
$(':input').prop('disabled', true);
}
}
});
Related
I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
I have been racking my brain for hours now trying to figure out why this is not working. Thanks in advance for anyone who can help.
Basically, I am trying to use json-encoded data from a php/mysql database query to populate the dropdown for the select2 plugin.
the HTML:
<input type="hidden" name="search-area" id="location-search" data-placeholder="Select an area" style="width:100%"/>
The Javascript:
$(document).ready(function() {
$(".select2").select2();
$("#location-search").select2({
ajax: {
url: "location-data.php",
dataType: 'json',
data: function (term) {
return {
q: term
};
},
results: function (data) {
return { results: data.text };
}
}
});
})
The PHP Script 'location-data.php':
<?php
include 'db/db-connect.php';
$query = "SELECT townID, town FROM towns WHERE town LIKE '%a%' ORDER BY town";
$result = $db->query($query);
$numtowns = $result->num_rows;
if($numtowns != 0) {
while($row = $result->fetch_assoc()) {
$answer[] = array("id"=>$row['townID'], "text"=>$row['town']);
}
}
else {
$answer[] = array("id"=>"0", "text"=>"No Results Found...");
}
echo json_encode($answer);
?>
Now i have looked at the location-data.php page in my browser and it is displaying in the correct format, see below.
[{"id":"1","text":"basildon"},{"id":"2","text":"billericay"},{"id":"7","text":"eastwood"},{"id":"12","text":"hanningfield"},{"id":"5","text":"maldon"},{"id":"11","text":"ongar"},{"id":"6","text":"rayleigh"}]
Whenever I attempt to use the select2 box, all it displays is 'searching...' and never displays results.
Thanks again for any help that can be given.
try changing the result function to return data. select2 needs an array of id,text pairs. i suspect you're seeing a javascript error in your browser that data.text doesn't exist.
results: function (data) {
return { results: data };
}
add more:
formatResult: formatValues,
formatSelection: selectValues,
Create function formatresult and selectValues:
function formatValues(data) {
return data.text;
}
function selectValues(data) {
return data.id;
}
I want to integrate a Java script Slot Machine game into my script.
You can see demo here ; http://odhyan.com/slot/
And also git hub is here ; https://github.com/odhyan/slot you can see all JS files here.
I created a Point Coloumn in User Table that people can play the game with this Point.
I think this JS Function in slot.js checking if user won the game or lose.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
} else {
res = "You Lose";
}
$('#result').html(res);
}
So i want to add +100 Point if user won the bet.
I made this PHP codes Uptading points For userid "1".
<?php
mysql_connect ("localhost","username","password") or die (mysql_error());
mysql_select_db('slot_machine');
$pointsql = mysql_query("SELECT * FROM user WHERE userid = 1");
while ($row = mysql_fetch_array($pointsql))
{
$row['point'] +=100;
$addpoint = mysql_query("UPDATE user SET point = '{$row['point']}' WHERE userid = 1");
}
?>
So how can i call or excute this PHP Codes in JavaScript function if user Win?
You'll need to trigger a network request from your javascript code to execute your php script server side. Using jQuery's $.ajax() function is an extremely common way to do this abstracting away various browser differences.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
} else {
res = "You Lose";
}
$('#result').html(res);
}
You can use jQuery's $.post() function to trigger an asynchronous request to your PHP file.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Here's the line you need.
$.post('score.php', {userid: 1}, function(data) {
alert("Score saved.");
});
} else {
res = "You Lose";
}
$('#result').html(res);
}
This will send POST data to score.php, or whichever file you want to send the data to. The PHP file can then access the userid sent to it by checking the value of $_POST['userid'].
As mentioned in the documentation, $.post() is a shortcut for jQuery's $.ajax() function that is simplified and has some of its options pre-set. The third argument in $.post() is a callback function, and the variable data will contain whatever is echoed out or printed from score.php by the time it's done executing. So, you could use alert(data) instead, to see what score.php printed out. This is useful for troubleshooting and error handling.
try this
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
});
hope this will help you use it in your function
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
// if
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
} else {
res = "You Lose";
}
$('#result').html(res);
}
I am using PHP function to display geofences. I want to pass javascript variable to php function in same file without page refresh.
function load(id,type){
if(type===2){
window.location.href="basic.php?idd=" + id; // i want to change code here
<?php
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
PHP function is:
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($result)) {
$d[] = $myrow;
}
return $d; //returns result in array
}
javascript window.location.href passes javascript value to php function but it reloads page also.
If you're using jQuery, you can use $.ajax(). It allows you to send data to your server and do something with the response.
Eg:
$.ajax({
type: 'POST',
data: myvar
success: function(Response) { console.log(Response); }
});
will send myvar to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console.
Have a read of what you can do with jQuery.
You can do this using jQuery. Basically you don't refresh the page, you just do an async query to the server and you get the response. In the following example the response is showed in alert box.
Your "index" file:
function load(id,type)
{
$.post("basic.php", { idd: idd }, function(data){
alert(data);
});
}
and basic.php
<?php
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($rs)) {
$d[] = $myrow;
}
return $d;
}
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.