GET parameters from jQuery in PHP file not carrying over? - php

I have some data in an ajax request that I am sending to a php file as an endpoint.
The code is the following:
// some calculations above here, but to keep things minimal assume they produce the following
totalBeforeTip = 38.43;
tipTotal = 5.77;
totalWithTip = 44.48;
saleCount = "3";
console.log("List for the query String: " + totalBeforeTip
+ "\n Tips: " + tipTotal
+ " \n Totals+Tip: "+ totalWithTip
+ "\n Totals Sales: " + saleCount);
// Send get to php with q-string
$.ajax({
url:"summary.php",
type: "get",
data:{
TotalSales: saleCount,
TotalsNoTip:totalBeforeTip,
TotalTip: tipTotal,
TotalWithTip: totalWithTip
},
success: function(resp){
console.log(resp);
window.location.href = "summary.php";
},
error: function(err){
console.log(err);
}
});
And my php is the following:
<main>
<?php
$TotalSales = $_GET["TotalSales"];
$TotalTips = $_GET["TotalTip"];
$TotalBeforeTip = $_GET["TotalsNoTip"];
$TotalWithTip = $_GET["TotalWithTip"];
?>
<div class='container'>
<div class='row'>
<div class='col-md-6'>
<form> <!--Main form for user interaction-->
<div class='form-group bigger-group'>
<label>Sales: </label>
<input readonly value="<?php echo $TotalSales ?>" />
</div>
<div class='form-group'>
<label>Totals Before Tips:</label>
</div>
<div class='form-group'>
<label>Total Tip Cost:</label>
</div>
<div class='form-group'>
<label>Total Cost with Tip:</label>
</div>
</div>
<div class=col-md-6>
<h1>Cost ($)</h1>
<div class='form-group'>
<input readonly value="<?php echo $TotalBeforeTip ?>"/>
</div>
<div class='form-group'>
<input readonly value="<?php echo $TotalTips ?>"/>
</div>
<div class='form-group'>
<input readonly value="<?php echo $TotalWithTip ?>"/>
</div>
</div>
</div>
</main>
When I redirect my fields are blank but in the response in the console log they are filled. I tried to do a page redirect to the resp it doesn't do anything. After poking at it quite a bit I got it to work by adding the following line to success: function(resp){....}.
window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
For some reason this works, and the fields in the php have the proper data but I don't see how? Or why it is that the data I passed in with the .ajax method just evaporated?
I've been struggling with this for two days and it works but I don't understand why at all. Can anyone shed some light?

So with the combination of all the feedback I've received and some more googling I've learned that AJAX is for ACTION not CONTENT and the core purpose of AJAX is to perform background processing without holding main flow on a page. Some good examples are :
Loading new tweets on twitter
Giving a notification if you have a new email in your inbox
Validating form fields on blur
Since in my case I wanted to send the totalBeforeTip, tipTotal, totalWithTip, saleCount to my summary.php to load the content of the input fields based off that data. Using AJAX for it is a bad approach because this should be done in a synchronous process.
I used the following code to accomplish this outside of ajax
window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
All I needed was the queryString.

window.location = "summary.php?TotalSales="+saleCount+"&TotalsNoTip="+totalBeforeTip+"&TotalTip="+tipTotal+"&TotalWithTip="+totalWithTip;
You need to do like these because Ajax get the response on same page and from that page you will be send the response to another page and then you get the response using $_GET['variables'].

Related

After ajax successful... how to recheck php if-else condition without refreshing page

when i click "add to cart" button... ajax successfully add product in database. and as a result he should recheck again php if-else condition. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the php code:
<?php
if(isset($products) && is_array($products) && count($products)){
$i=1;
foreach ($products as $data) { ?>
<div class="col-lg-3 col-md-4 col-sm-6" ">
<div class="tile">
<img class="prod_image" src="<?php echo base_url(); ?>../upload/<?php echo $data['image'] ?>">
<div class="prod_detail">
<p class="prod_name"><?php echo $data['name'] ?></p>
<p class="prod_name"><?php echo $data['weight'] ?></p>
<p class="prod_name"><?php echo $data['price'] ?></p>
<?php
//if product already add in cart
$isincart = get_product_from_cart($data['id']);
if($isincart < 1) { ?>
<button class="btn btn-primary" onclick="addtocart(<?= $data['hid'];?>,<?= $data['weight'];?>,<?= $data['price'];?>)">Add to cart</button>
<?php } if ($isincart > 0){
?>
<div id="prod_quant" class="add_btn_sec">
<form id="myform" method="POST" action="javascript:void(0)">
<input type="submit" onclick="quantitydec(<?= $data['id']; ?>)" value="-" class="qtyminus" field="quantity<?= $data['id']; ?>">
<input type="text" id="quantity<?= $data['id']; ?>" name="quantity<?= $data['id']; ?>" value="<?php echo ($isincart) ; ?>" class="qty">
<input type="submit" onclick="quantityinc(<?= $data['id']; ?>" value="+" class="qtyplus" field="quantity<?= $data['id']; ?>">
</form>
</div>
<?php
}
?>
</div>
</div>
</div>
<?php } $i++; } ?>
and ajax script is here
<script type="text/javascript">
function addtocart(p_id,p_weight,p_price)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('index.php/addtocart/addtocart_ajax');?>",
data: {'id': id, 'name': name, 'p_wight': p_weight, 'p_price': p_price},
dataType: 'JSON',
success: function(response){
/*do something here*/
}
});
}
</script>
Can anyone suggest me how to recheck " if($isincart < 1) " condition without refreshing the page?
First of all,
PHP - is a server side language. PHP codes are interpreted at the server before the html file is sent to the browser. Please note that browser cannot interpret php codes.
Now AJAX - Ajax is a client-side script that communicates to and from a server/database without the need for a complete page refresh. The best definition I’ve read for Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
Now coming to your question, if you want to run a php code after the AJAX success, you would need to send another AJAX request as the success function of the first AJAX request.
Hope this makes sense.

Dynamicly populate field after getting value from dropdown

I have a form that uses a dropdown menu to select an option. After the option is selected I want to get a value form my DB to populate the next field with the correspondent value (in the scenario is to get the square footage of a rental property - but this value can be edited)
This is the field where i have the options:
<div>
<label class="control-label " for="local">Local</label>
<select class="select form-control" id="local" name="local" ><?php echo $lista_fraccoes;?></select>
</div>
after this i have the script to get the data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#local').on('change', function(){
var .local = this.value;
$.ajax({
type: "POST",
url: "area_fraccao.php",
data:'local='+local,
success: function(result){
$("#area").value(result);
}
});
});
</script>
And after this i have the field that i want to populate:
<div class="form-group m-2 ">
<label class="control-label " for="area" type="value">Area</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fas fa-ruler-combined"></i>
</i>
</div>
<input class="form-control" id="area" name="area" placeholder="Em m2" type="value" value=""/>
</div>
In the area_fraccao.php file is where i get the correspondent value:
require_once 'config.php';
require_once 'functions.php';
$local = $_GET['local'];
$query_area = "SELECT * FROM TbFraccao WHERE PkFraccao=" . $local;
$result_area = mysqli_query($link, $query_area);
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
};
The solution I'm Using is presenting the following errors in web inspector
The code I'm using is updated matching the given suggestions.
Looking at your code, The code seems Ok. Please make sure that the query has no error by checking if running query was successful, check there is atleast one result and remove the semi-colon after while closing bracket.
if($result_area = mysqli_query($link, $query_area)){//the query is Ok
if(mysqli_num_rows($result_area)>0){//check there is atleast one result
while ($row_area = mysqli_fetch_assoc($result_area)){
$area = $row_area['FraccaoArea'];
echo $area;
}
}
}
else{//you have an error when writing your query
echo 'Wrong query';
}
if that does not help, the problem might be you did not sanitize the data during saving and there are characters from that data that interferes with the query. Show us how you did filtering before saving the data.
Set value of input elements using value method of jQuery
$("#area").value(result);
html() method is used to set innerHTML of elements

why page request is not going to server when routing views each time in angular js?

I am working in an angular js demo project where i am using UI Router for routing. In my project there are two views named view1 and view2. For navigation i used tab design so that user can navigate from one view to another. In view1 user needs to insert his email address and password and after clicking submit button i store this information in mysql database by using http service of angular. After that when i clicked view2 it shows all user's email address and password and working fine. But if i return to view1 and register another user and go back to view2 then this new user information is not updated and previous data showed. For showing user information from database i used php.
So what i am thinking is that, at first when we clicked view2 , the page request go to the server and user information show in the view2 after coming from server it turns into plain html. After that when we added new data in mysql database and press view2 the request does not go to server as a result i did not get the newly added user information.
I don't know i am right or wrong but i need to solve this problem. Please help me. How can i find updated data from mysql database.
You can check this problem from here
[http://www.iamcreative.comlu.com/angular/][1]
Here is my view1.php Code
<div ng-controller="Controller1">
<form role="form">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<button ng-click="submitForm();"type="submit" class="btn btn-default">Submit</button>
<div class="form-group">
<label id="user-status"></label>
</div>
</form>
</div>
Here is my view2.php code
<?php
include '../server_side/database_lib/DbHelper.php';
$db=new DbHelper();
$result=$db-> selectAllRow(Constants::$TABLE_USER_INFO,Constants::$USER_INFO_ID, 'DESC');
?>
<div class="container" ng-controller="Controller2">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<?php
foreach($result['data'] as $value)
{
echo "<tr>";
echo "<td>".$value["email"]."</td>" ;
echo "<td>".$value["password"]."</td>" ;
echo "<tr/>";
}
?>
</tbody>
</table>
</div>
</div>
Here is my controller code
angular.module('myApp.controllers', []).controller('MainController',function($rootScope,$scope,$location,$state){
$scope.navigate=function(sub)
{
if(sub=="view1")
{
$state.go('view1');
}
else if(sub=="view2"){
$state.go('view2');
}
}
}).controller('Controller1',function($rootScope,$scope,$location,$state,regService){
$scope.submitForm=function(){
var email= document.getElementById("email").value;
var password= document.getElementById("pwd").value;
if(password!="" && email !="")
{
var data={"email":email,"password":password};
var promise = regService.getRegistration(data);
promise.then(
function success(payload) {
var status = payload.data.status;
if(status==2)
{
document.getElementById("user-status").innerHTML=payload.data.msg;
}
else if(status==0)
{
document.getElementById("user-status").innerHTML=payload.data.msg;
}
else if(status==1)
{
document.getElementById("user-status").innerHTML="Registration Successful";
}
},
function error(errorResponse) {
//alert('Error connecting server'+ errorResponse);
alert("Error")
}
);
}
else{
document.getElementById("user-status").innerHTML="*Please insert all the field";
}
}
}).controller('Controller2',function($rootScope,$scope,$location,$state){
});
and index.html code like this
<section>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="tab-bar">
<ul>
<li><a class="tab" ng-click="navigate('view1');" >View 1</a></li>
<li><a class="tab" ng-click="navigate('view2');" >View 2</a></li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div ui-view ></div>
</div>
</div>
</div>
</section>
Please help me what can i do?
This code has so many things which are not the best practices when using Angular.
I would recommend you do some reading on how to use angualr in your project.
I will mention a few things which I can see straight away , but this list is not exhaustive , you need to read up on how angular works and its best practices ..
You are using javascript to manipulate the content in your page , this is generally not a good idea , you should be letting angular handle the manipulations of the DOM as much as possible.
document.getElementById("user-status").innerHTML=payload.data.msg;
You have put server side code in angular ui-templates . This is not how you use templates , By default angular will only load the template ones and cache it , any subsequent requests for the template will be served from the cache. Server side requests should always be in angular services.
This is a minor issue compared to the others but you do not need the ng-controller tags when using UI view , the controller to be triggered should be mentioned in the ui-view configuration , this will cause the backend to be called twice once issue #2 is corrected.
For your specific problem , you will be able to resolve it when you correct issue #2 and move it into angular code instead of template.
However as I mentioned , please read up on how angular should be used and what are the best practices.

Submiting a form from a single page webapp using Ajax Call

Does anyone know about a good tutorial where submiting a form from a sing page is explained? I have a few page views in my html code and one of them is a form with three fields (Name, Email and Message) what I am trying to achieve is to submit the form data via Ajax without using a process.php directly.
This is the Form:
<section class="hidden" id="view-forms">
<header>
<button class="left arrow" data-vin="view-home" data-sd="sr">
<div class="label">All Contacts</div>
</button>
<h1>Message</h1>
<button class="right bold green" data-vin="view-done" data-sd="sl">
<div class="label">Send</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<input placeholder="Name" type="text" />
<input placeholder="Email" type="email" />
<textarea placeholder="Your Message" rows="5"></textarea>
</div>
</div>
</div>
</section>
This is the confirmation page after message has been sent:
<section class="hidden" id="view-done">
<header>
<h1>That's it!</h1>
<button class="right bold" data-vin="view-home" data-sd="popout">
<div class="label">Done</div>
</button>
</header>
<div class="scrollMask"></div>
<div class="scrollWrap">
<div class="scroll">
<div class="content">
<h2>Message sent!</h2>
</div>
</div>
</div>
</section>
Please, let me know if any of you have already implemented something like this. Thank you.
You could submit to the same PHP page. You just need an if statement to separate the code that generates the page from the code that submits your form. That being said, you should probably just create a second PHP script to handle the form submission. If you wanted to implement it using the if statement, I would add a piece of information to your GET/POST request which would be something like:
'formSubmission='+true
Okay, for the more details, look at this tutorial, it goes over the basics. In your case, try this (NOTE: I haven't tested any of this). Also, add an ID to each of the elements (I assumed they would be the same as your current name attributes and that the textarea would have the ID message).
function()submitForm(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var message = document.getElementById('message').value;
var requestData = 'name='+name+'&email='+email+'&message='+message+'&formSubmission='+true;
//I'm assuming that you're using a POST request (this depends on the length of the message
var AJAXObj = new XMLHttpRequest();
//don't forget to replace currentURL.php with the name of the page that will handle the submission
AJAXObj.open('POST', 'currentURL.php', true);
AJAXObj.setRequestHeader('Content-type','application/x-www-form-urlencoded');
AJAXObj.send(requestData);
AJAXObj.onreadystatechange = function (){
var AJAXObj = event.target;
if(AJAXObj.readyState == 4 && AJAXObj.status == 200){
var responseText = AJAXObj.responseText;
//things that you might want to do with your responseText
}
}
}
Now here's the PHP:
if(isset($_POST['formSubmission'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//code that handles the form data that has now been passed to PHP
}
Just a thought, don't submit to the same PHP page that you're currently on. Create a new file and paste the code into that. It'll be cleaner.

Linking page in a div with html forms and php

So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>

Categories