Query in Jquery IF statement - php

I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?

At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="

Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.

Related

How do I display different table from database on one page using scroll function

Right now, I am working on a project where I need to display data from different tables on one page, one after another using scroll function
For this task I am using ajax, php, mysql.
So here is what I have managed so far:
PHP code:
<?php
$conn = mysqli_connect("127.0.0.1", "Got", "nokia", "myddb");
$feedb = mysqli_query($conn,"SELECT * FROM feedb");
$feedb_count=mysqli_num_rows($feedb);
$photo = mysqli_query($conn,"SELECT * FROM photob");
$photo_count=mysqli_num_rows($photo);
$limito=$_POST["limit"];
$pagefeed=$_POST["start"];
$pagephoto=$_POST["startphoto"];
$pagetexto=$_POST["start3"];
$tumb=$_POST["change"];
if($tumb==0)
{
$query = "SELECT * FROM feedb ORDER BY cid DESC LIMIT $pagefeed , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<img class=\"imago\"src=\"img/$row[cphoto].jpg\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>"."Page".$pagefeed."Func".$tumb;
}
}
if($tumb==1)
//echo "<br>"."Page".$pagefeed."Func".$tumb;
{
$query = "SELECT * FROM textb ORDER BY cid DESC LIMIT $pagephoto , $limito ";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo "
<div class=\"block\">
<span class=\"namo\">$row[cname]</span><br>
<span class=\"texto\">$row[ctext]</span>
</div>";
}
}
Javascript code:
<script>
$(document).ready(function(){
var limit = 7;
var start = 35;
var start2 = 0;
var start3 = 0;
var action = 'inactive';
var change = 0;
var ncount =0;
if(active='inactive'){
action='active';
load_country_data();
}
function load_country_data()
{
$.ajax({
url:"resout.php",
method:"POST",
data:{limit:limit,start:start,change:change,startphoto:start2},
cache:false,
success:function(dataz)
{
$('#load_data').append(dataz);
if(dataz == '')
{
action = 'inactive';
change++;
if(change==2){action = 'active'; $('#load_data_message').html('Больше нету данных'); }
}
else
{
$('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
action = "inactive";
}
}
});
}
$(window).scroll(function(){
if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==0)
{
action = 'active';
start=start+limit; setTimeout(function(){load_country_data();}, 300);
}
else if(($(window).scrollTop() + $(window).height())==$(document).height() && action == 'inactive' && change==1)
{
action = 'active';
setTimeout(function(){load_country_data();}, 300);
start2=((ncount-1)*limit);ncount++;
}
});
});
</script>
but after displaying one base, when it start to dislay second it has an error
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
right after error it displays the second base properly.
I think this problem is because of a method that I chose for displaying second base "star2= (ncount-1)*limit ;ncount++", but I didn't see a different solution.
How can I fix this problem or how can I display different
table in different way?

Getting Ajax reponse as null in php

I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);

jquery ajax not calling php class correctly

I am trying to make a ajax call to do a database update in my php class. However, it seems the class is being called but the parameters are not passed for some reason.
Here is my jquery:
$(".sendRSVP").click(function(e){
e.preventDefault();
var nameArray = [];
//var uniqueCode = parseInt($(this).find('.theCheckbox').attr('id'));
//var response = ($(this).find('.theCheckbox').is(":checked")) ? '1' : '0';
//the parameters passed should be uniqueCode and response which both gave legit values
if($("#displayContacts").is(":visible")){
$.get("submitRSVP.php", {rs: '1', resp: '12345'})
.done(function(rtn){
console.log(rtn); //error is returned
})
}
});
Here is my php code:
<?php
require 'dbh.php';
$rsvp = $REQUEST["rs"];
$response = $REQUEST["resp"];
session_start();
if(session_start()) $invitationCode = $_SESSION['login_user'];
$hint = "here1";
try{
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '$response' WHERE `GuestWithPlusOnes`.`UniqueID`= '$rsvp'";
$updateStmt = $conn->prepare($updateQuery);
$updateStmt->execute();
if ($updateStmt->rowCount() > 0) {
$hint = 'success';
}else {
$hint = 'error';
}
$_SESSION['login_user'] = $rsvp;
$updateStmt = null;
}
catch(Exception $e){
$hint = $e;
}
echo $hint;
?>
I definitely have a record in my table with that uniqueId because when I change the query to:
$updateQuery = "UPDATE `db686470460`.`GuestWithPlusOnes` SET `Confirmed`= '1' WHERE `GuestWithPlusOnes`.`UniqueID`= '12345'";
that updates as normal. Is there something else I could be missing?

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

How do I get javascript to read the output of a php file

First off hello, I am new here.
My problem is that I have a php file pulling info from a database. I will post the code below.
What I need is for my JavaScript to take the output and load it into a list that generates some flash cards.
code sample `$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
$query1 = "SELECT * FROM category_tb WHERE cat_name = '$category'";
$result1 = mysql_query($query1) or die ("Error in query: $query1. " . mysql_error());
while ($row = mysql_fetch_array($result1))
{
$cat_num = $row[1];
}
// This establishes a link to MySQL
$query = "SELECT * FROM english_lang, finnish_lang ".
"WHERE english_lang.lang_id = finnish_lang.lang_id AND english_lang.cat_id = $cat_num";
$rt = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
while($nt=mysql_fetch_array($rt)){
echo "{\"english\": \"$nt[1]\", \"finnish\": \"$nt[6]\" , \"asked\": states.notAsked},";
}
`
So this basicly gets some data and formats it to be used by the javascript.
if you want to look at the output of this to get a better idea the go here
http://languagelearner.byethost2.com/vocabulary2.php
select 1 of the first 2 categories as they are the only ones with data right
now.
the javascript is this:
code sample `
var string1;
var string2;
var number;
var states = {"oneVisible": 0, "bothVisible": 1, "notAsked": 2, "asked": 3}
var state = states.bothVisible;
var numberOfWordsAsked = 0;
var words = {"list": [
]
}
function displayWords(){
if (state == states.bothVisible) {
if (numberOfWordsAsked < words.list.length) {
state = states.oneVisible;
number = Math.floor(Math.random() * words.list.length);
while (words.list[number].asked == states.asked) {
number = Math.floor(Math.random() * words.list.length);
}
string1 = words.list[number].english;
string2 = words.list[number].finnish;
document.getElementById("fin").style.display = 'none';
document.getElementById("eng").innerHTML = words.list[number].english;
document.getElementById("fin").innerHTML = words.list[number].finnish;
document.getElementById("b").value = "Show word";
document.getElementById("correct").style.display = 'none';
}
else {
document.getElementById("eng").innerHTML = "You know all the words in this category, congratulations!";
document.getElementById("fin").style.display = 'none';
document.getElementById("b").style.display = 'none';
document.getElementById("correct").style.display = 'none';
}
}
else {
document.getElementById("fin").style.display = 'inline';
state = states.bothVisible;
document.getElementById("b").value = "Wrong";
document.getElementById("correct").style.display = 'inline';
}
}
function setCorrect(){
words.list[number].asked = states.asked;
numberOfWordsAsked += 1;
displayWords();
}
//-->
</script>
`
so the output needs to go in here.
var words = {"list": [
]
Any help would be appreciated. I did not write the javascript, a friend did.
He used static info in the list.
Try AJAX. Check out http://www.w3schools.com/PHP/php_ajax_database.asp
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
alert(ajax.responseText);
}
};
ajax.open("GET", "ajax.php", true);
ajax.send(null);
outputs "hello world" when used in the same directory as a php file ajax.php:
<php
echo 'hello Word!';
?>
To put php data structures into something javascript can parse, use json_encode. That should be enough to help you on your way.

Categories