PHP Get POST Value from Ajax to PHP with 2 condition - javascript

Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.

You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good

Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}

Related

Pass variable string from javascript to php using ajax

How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.

javascript missing a url parameter during redirection

my website has an option of country like for different country the website layout is different. it is running on the basis of sessions if session is not set the user will be redirected to index to select a country then will be redirected from the page where he originally came from. here's the code
my session_check_client.php file that is included in every file except index
<?php
session_start();
if(!isset($_SESSION['country']))
{
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
header("location:index.php?return_uri=$actual_link");
}
?>
now what happens is when i go back to home page i wanna check whether this requested has some return parameter or just user has visited he website for the first time. there are two button for two countries of which i am showing the code.
function canada(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=canada',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
function us(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=us',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
now the problem is when i am alerting the value of $_GET['return_uri'] it is giving me a false value
e.g my return_uri value is http://localhost/interfold/products2.php?category=Aprons&id=57725599688 it actually shows the whole value in return_uri in index page like http://localhost/interfold/products2.php?category=Aprons&id=57725599688 but when is get the url value using javascript it is onlye giving me the value http://localhost/interfold/products2.php?category=Aprons it is missing the $ and afterwards parts!!! any recommendations?
Since you are only using super global variables, you can directly print a JS variable above the function you are describing:
var actual_link = "<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>";
function postCountry( country ){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=' + country,
success: function (data) {
if(actual_link){
//window.location.href=actual_link;
alert(actual_link);
}
else {
window.location.href = "home.php";
}
}
});
}
postCountry('us');
postCountry('canada');

jQuery updates DOM, browser does not

I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

JQuery $.ajax not posting multiple vars

Hi Guys I have the following function that is called on a link:onclick(), but for some reason the $.ajax does nothing at all - have even stripped my php code to only dump the $_POST var but I still get no feedback from the function - all i get is the alert msg - which is also just there for test purposes...
called there:
Save
function saveMyGame(){
var usern = $('#usern').attr('value');
var usrPoints = $('#userPoints').attr('value');
var usrLevel = $('#userlevel').attr('value');
var saveState = this.imgPath;
alert('Saving your game: '+usern+' Points: '+usrPoints+' Level: '+usrLevel+' state phase: '+saveState);
e.preventDefault();
var svGame = {act:'saveGame',user:usern, Points:usrPoints, Level:usrLevel, saveGState:saveState} ;
$.ajax({
url: "game/lib/updateGame.php",
type: "POST",
cache: false,
data: svGame,
dataType: "html",
success: function(svGame) {
$(".traget").html(svGame).fadeIn('slow');
}
});
}
the PHP code is suppose to check act, then verify that all required info is passed, than process the request or display an error msg...
<?php
if(isset($_POST['act']) && $_POST['act'] == 'saveGame') {
//Process save game request
/*if(isset($_POST['user']) && isset($_POST['userPoints']) && isset($_POST['userLevel']) && isset($_POST['saveGState']) ) {
$Game->saveGame();
echo'<br>....'.$_POST['user'];
} else {
echo 'Please provide correct information for saving...';
}
*/
echo var_dump($_POST);
}
Url in your ajax request has relative path url: "game/lib/updateGame.php", without slash in the beginning of the url like url: "/game/lib/updateGame.php",.
So maybe if your page adress differ from root (for example http://yourdomain.com/games/), full path will be http://yourdomain.com/games/game/lib/updateGame.php and therefore the server method is not performed.

Categories