Posting JavaScript Value to PHP via Ajax issue - javascript

I need to get a value which is from jQuery to PHP so I can do a search function for my site.
I currently have tried:
<script>
$(document).ready(function () {
$('#search_button').click(function(e){
e.preventDefault();
e.stopPropagation();
carSearch();
});
});
function carSearch()
{
$.ajax({
type: "POST",
url: 'cars.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val()+"mpg");
}
});
}
</script>
This ajax is running when the button is pressed and js value is there as it is displayed in the alert.
However
if(isset($_POST['mpg']))
{
$query = "SELECT * FROM cars WHERE mpg =< ".($_POST['mpg'])."";
echo "<div class='test'></div>";
}
else
{
$query = "SELECT * FROM cars";
}
The isset doesn't trigger, the div is just a big blue box for testing purposes. The ajax is posting to cars.php which is also where the ajax is, so posting to its own file. Which I've not read about being done, but I've posted within the same file before just not with ajax.
I have also tried posting the value from the ajax to another file:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
}
?>
Just to test if it is doing anything and it isn't.
So
data:
{
mpg : $('.mpg').val()
},
Appears to be wrong, though I got this from looking at the many many other questions on here to do with passing js to php. I've tried all the variations for it I've seen on here, and only the above code results in the success function alert triggering.

I see a mistake here
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
The "}" at the end of the line probably throw an error. Is there error in your .php file when the ajax is running ?
To check if there is errors or see what the .php file is returning follow these steps:
Using Chrome right click on your page and choose "Inspect Element"
Click on "Network" in the menu
If not active click on the filter icon (depending on your chrome version)
Click on XHR element of submenu
Refresh your page and your .php file should appear
Click on it and see what the file is returning
(It could also be done in Firefox but not exactly the same titles)
Tell us what you got here.
Also, you should go with the extern file way. Because ajax data returning correspond to the .php file content. If your .php file contains anything else than what you need to return, there is a problem. Example: Any HTML on your .php file will be returning in the ajax data and this is probably far from what you want.

Related

Change PHP session variable from AJAX call

I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}

AJAX returning current page when trying to execute separate PHP query

Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});

Sub Total is not getting the changed value from database to input box

I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Categories