$jquery.post() PHP and Mysql - javascript

So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?

"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];

try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>

Related

Select query using javascript paraments

I am trying to do a select query using a javascript parameter ($userCard) obtained in the same function ( Code Below ). But an undefined variable error is given, how can pass the parameter in the query ?
<script>
function count() {
$card = "V010";
$userCard = document.getElementById('visitorID');
if($userCard.value.length == 4){
<?php
$connection = connectToSql();
$query = "SELECT * FROM visitorsystem.visitor WHERE cardNo = '$userCard' ";
$result = mysqli_query($connection,$query)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($result) >0)
{
echo "Card in Use";
}
?>
}
}
</script>
If I read your question correctly, you are wildly miss reading the usage of PHP and Javascript.
Javascript is a client language, while PHP is executed on the server.
To pass a js argument to a PHP page you have to use a form on your html and retrieve it using $_POST or $_GET variable in PHP
I recommend you go check this Difference between Javascript and PHP
You have the operations of client and server mixed up.
PHP can echo variables to static assets like .html or .js because the PHP compiler runs from the server before the file gets sent to the client.
Once the PHP was compiled and sent to the client, the only way to communicate back to the server is to:
Make an AJAX request
Refresh the page

How to use php inside of javascript?

I am using javascript to retrieve a bunch of values from the Riot API, however I want to store them in my own database using php. For example, I'm trying to store the gameID and this is what I'm trying right now.
<?php
$insrt = "INSERT INTO game (gameId)
VALUES (".<script>b.gameId</script>.")";
mysqli_query($dbc, $insrt);
?>
I'm pretty sure that I'm not even close to correct but I'm not sure how to do this.
You need to take a different approach. You can make an ajax call to a php script to do this for you. But the initiator will be javascript from the client side. Using jQuery(let me know if you can't), you can do
$.ajax({url: "insert_game_id.php", data: {gameId :b.gameId} });
and your php script
<?php
$gameId = $_POST['gameId'];
$insrt = "INSERT INTO game (gameId)
VALUES ($gameId)";
mysqli_query($dbc, $insrt);
?>
See jQuery Ajax POST example with PHP

How I Can move variable from JavaScript into a php Query?

Here is my Code I want to move my Variable of "Hellow"
from JavaScript
to PHP Query at:
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");.
Kindly any help?
<script type='text/javascript'>
var Variable = "Hellow";
document.write("<?php
$db = mysql_connect("localhost","root","");
mysql_select_db("Dictionary",$db);
?>");
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");
document.write("<?php
while($row = mysql_fetch_array($result))
{
echo $row['Urdu'] ;
}
mysql_close($db);
?>");
</script>
You can't/should not do what you propose. JS is executed client side, while PHP is a server side language, and even if it is possible to send a file to the server and execute it, it would come with a host of security issues.
What you could do however is to make a get/ajax request that sends your variable to a php script, but remember to clean up the variable before using it in any mysql query.
What you are trying to do won't work because the PHP processing happens earlier in the stack than the Javascript. You will need to use ajax to send data back to the server once the page has loaded.
jQuery can make this pretty easy for you. Look up $.ajax methods for jquery.

How to get multiple responses to a single ajax request in php

I am making a web app, where I want to provide a search function. I am sending the searched name with an ajax request, and i want to pull the records of that particular person. But since there are many details that are to be displayed, I am finding it difficult to get the response. (I am not able to get more than one response at a time)
I want to know, if there is a way to get multiple responses for a single request, or a way to send all my variables in the target PHP file to the requesting javascript file as an array or something.
Thank you. If this question is asked before, please provide the link.
Use JSON as the datatype to communicate between PHP(Backend) and Javascript(Frontend). Example:
PHP
<?
$person = array("name"=>"Jon Skeet","Reputation"=>"Infinitely Increasing");
header("Content-Type: application/json");
echo json_encode($person);
?>
Javascript/jQuery
$.ajax({
url: "your_script.php",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts Jon Skeet
});
Add everything you want to an array, then call json_encode on it.
$data = array();
$data[] = $person1;
$data[] = $person2;
echo json_encode($data);

php post not working using header and ajax

i am sending a post request using jquery $.post to another domain. every thing works fine but i am not getting the posted data in the requested page please check my code
jquery code
var data = {mydata: 'testing'};
$.post("http://anyurl/file.php",data,function(info){
alert(info);
});
and here is php code
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
$data = $_POST[“mydata”]; // assigning data to variable
echo $data; // sending back to jquery
?>
it does not return the data please check anyone.
Thanks in advance
Use proper quotes and use isset() to check the data set or not like,
<?php
header('Access-Control-Allow-Origin: *'); // this is to allow another domain
print_r($_POST);// to check the post data
$data = isset($_POST['mydata']) ? $_POST['mydata'] : "No Data";
echo $data; // sending back to jquery
?>
Try to get the POST variable with single quotes and better to put exit after echoing it like
$data = $_POST['mydata'];
echo $data;
exit;
And make sure that it is posting to the given URL or not through console.
OK,It walk well when I test it.In order to reappear the error you've got,I'm trying to set the file.php into a BOM-UTF8 file and it got error in the end.So,please check your file.php if it got a BOM before header().
Another suggess,you can use firebug to test your ajax post process.The link in the console will show you the ajax process,such as what you've post and what is feedback.Just use console.log() instead of alert().

Categories