Call PHP function from Ajax - javascript

I'm new to AJAX, and can't get a php function to run.
The AJAX post request is working as it should, here's the code:
function thumbs(i) {
$('.thumbs-up' + String(i)).click(function(){
$(this).addClass('up');
$.ajax({
type:"POST",
url:"item.php",
data:'act=up&function' + String(i) + '=true&user=' + email,
success: function(){
}
});
});
for (var i = 1; i <= count; i++) {
thumbs(i);
}
The above works, I receive all the correct values.
Then the PHP code that should run is here:
for ($i = 1; $i <= $count; $i++) {
if ($_POST['function' . $i] == 'true') {
//code that should run but does not
}
}
The count variable is the same. Is there anything wrong here?

You're using get parameters instead of sending post parameters. See the example in the docs
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});

Related

display the value of a php session in a html input tag using javascript

I'm working on a site and I can't figure out why I can't display the value of the php session in the input tag on the html page.
This is my javascript code:
var qty = $.ajax({
url: 'winkelwagen.php',
data: {add: id, volume: "magnum"},
type: 'get'
});
$['input[name="item-qty-' + id + '"]'].val = toString(qty);
and the php function it is referring to:
if(isset($_GET['add'])) {
$query = query("SELECT * FROM products WHERE id = " . $_GET['add'] . " ");
validate($query);
while($row = mysqli_fetch_assoc($query)) {
if(isset($_GET['volume'])) {
if($_GET['volume'] == "magnum") {
if($row['category'] == 'Champagne') {
$_SESSION['product_' . $_GET['add'] . '_magnum'] += 1;
} else {
$_SESSION['product_' . $_GET['add'] . '_magnum'] += 6;
}
return $_SESSION['product_' . $_GET['add'] . '_magnum'];
} else {
if($row['category'] == 'Champagne') {
$_SESSION['product_' . $_GET['add']] += 1;
} else {
$_SESSION['product_' . $_GET['add']] += 6;
}
return $_SESSION['product_' . $_GET['add']];
}
}
}
}
and this is the html code:
<button class="cart-btn-remove" onclick="manageProducts('remove',0,{$id})"><ion-icon name="remove"></ion-icon></button>
<input type="text" name="item-qty-{$id}" value="{$amount}">
<button class="cart-btn-add" onclick="manageProducts('add',0,{$id})"><ion-icon name="add"></ion-icon></button>
(this comes from an php loop to print the items in the shopping-cart)
I hope you can help me.
$.ajax doesn't return the server response. It's asychronous and you need to use a callback function to process the response.
$.ajax({
url: "winkelwagen.php",
data: { add: id, volume: "magnum" },
type: "get",
success: function(qty) {
$('input[name="item-qty-' + id + '"]').val(qty);
}
});
Did you close the brackets here?
data: {add: id, volume: "
Oh, and you should probably escape those variables so people don't
do winkelwagen.php?add=;DROP DATABASE products;
oh, and what #Barmar said too...
The ajax doesn't store/return the response in the qty variable automatically, rather you have to attach a callback to handle it.
You have to do something like this to achieve the desired output:
$.ajax({
url: 'winkelwagen.php',
data: {
add: id,
volume: "magnum",
type: 'get'
}).done(function(qty) {
$['input[name="item-qty-' + id + '"]'].val(JSON.stringify(qty));
}).fail(function() {
alert("error");
});

AJAX inside $.when giving fist character of the return string

I'm calling an AJAX using a $.when to wait till that ajax completes and return to process the next ajax inside.
This is where $.when calling happens:
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1[0])); //this is in the attached screen shot
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
Above code is calling below ajax method function:
function getCreditorID(){
id = "";
var creditorcodex = document.getElementById('creditorcode').value;
// console.log("getCreditorID input: " + creditorcodex);
var urlx = "functions/getCreditorID.php";
return $.ajax({
type: 'POST',
url: urlx,
data: {
creditorcode: creditorcodex,
},
success: function(data) {
console.log("Result : "+data); //this is in the attached screen
}
});
}
Above function calling getCreditorID.php to get data:
getCreditorID.php:
<?php
include '../config/dbConn.php';
$creditorcode = $_POST["creditorcode"];
// $creditorcode = $_GET["creditorcode"];
$result="";
$sql = "SELECT intCustomerID FROM lms.tblcustomers WHERE varCustomerName='".$creditorcode."';";
mysql_select_db('$dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
$result=-999;
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$result=$row["intCustomerID"];
}
echo $result;
mysql_close($conn);
?>
Problem is:
If return from getCreditorID.php is '44' then console.log("Result : "+data); inside getCreditorID() function will output in console as 'Result : 44' and this is working fine. But the same function is getting returned in loadAllData() function and using the value returned for next ajax. Here if we print the return value using console.log("cx id is : " + parseFloat(a1[0])); output is '4' which should be '44'. Which means it's only giving the first character as output and ignoring the rest.
Screenshot of running console:
Please find a way out.
In your function loadAllData(), use a1 instead of a1[0] and update your code accordingly
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1)); // did correction here
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

cant pass the value from data using ajax

this is very frustrating, 2 hours passed and still can't get it working.
I just want to test on how to pass a value to my method using ajax.
Code:
Javascript
$('#form-payment').submit(function () {
var request = $.ajax({
url: "<?php echo site_url(array('home', 'update_credit_card')); ?>",
type: "POST",
data: 'someNumber=12'
});
request.done(function(data) {
console.log('boom' + data);
});
request.fail(function(jqXHR, textStatus) {
console.log('error' + textStatus);
//print_r(jqXHR);
});
});
PHP
function update_credit_card()
{
var_dump($_POST['someNumber']);//returns NULL value
$somenumber = $_POST['someNumber'];
if ($somenumber == '12') {
print "Number is 12";
} else {
print "Number is not 12";
}
}
The code is very simple but for the life of me can't get it to work. T_T.
Badly need help.
You can also use like this.
var values={};
values['arg1'] = 1;
values['arg2'] = 2;
$.ajax({
type:'POST',
url:'....',
data: values,
success:function(){}
});

Categories

Resources