passing with AJAX to php include - php

I need to get the following code to pass the $Bus_Account_ID and the $Usr_ID to the include file rating2.php
$Bus_Account_ID=733;
$Usr_ID=3;
I am not familar with AJAX so learning here.
I believe that this is the line passing to the include but I don't know what is happening with "attrVal"
data: 'postID='+attrVal+'&ratingPoints='+val,
$(function() {
var value = "<?php echo $total_points ?>";
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: value,
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating2.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
$('#avgrat').text(data.total_points);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
postid shows in only 3 place in the above and here
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
This is what is being called on the include file
$postID = $_POST['postID']; /* BUSINESS ID */
How to I call the $Bus_Account_ID and the $Usr_ID?

You have the problem with passing the data here.., You need to maintain the format like this: data: { name: "John", location: "Boston" }
$.ajax({
type: 'POST',
url: 'rating2.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
So change the data by,
data: { postID: attrVal, ratingPoints: val, Usr_ID : "<?php echo $Usr_ID;?>", Bus_Account_ID : "<?php echo $Bus_Account_ID;?>" }

Related

getting the value of ajax and incrementing/concatting it to other value codeigniter

i have a problem in my ajax. Here is my serious problem. When i go to my view, sometimes it displays 1-0 and thats what i want, but sometimes it only displays -0. What i did is , i am getting an ID from the database and put it in a label, after i put it in a label, i get it again and concat with other ID that is came from my database again. Here is my code:
my ajax:
$(document).ready(function() {
get_clinicID();
});
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
})
}
function get_clinicID() {
$("#clinicID").empty();
$.ajax({
url: siteurl+"myclinic/get_clinicID",
type: "GET",
dataType: "JSON",
success: function(data) {
$('#clinicID').text(data[0]['clinic_id']);
}
});
}
My view:
<div class="col-title">
<h4> Your Clinic ID: <label id="clinicID"></label></h4>
<br>
<h5 id="checkupID">Check-up ID: <label id="checkID"></label> </h5>
</div><!-- col-title -->
The Problem: If i go refresh/reload the page the output of my concat from the code below becomes -0, the actual output that i want is 1-0, sometimes it outputs 1-0, but sometimes its not. Is it delayed from ajax? or something wrong in my code below :
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
try like this near :
text(value.toString()+"-"+init);

Ajax sends data , but returns nothing

I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});

How to update quantity in session array on the go?

I want to capture value keyed in textbox for quantity in the shopping cart while they type. I used jquery's key up for this.Then I want to save the new value in the session for quantity. I'm getting the value but unable to save it. It returns null after refreshing the page.
Html
<input type="text" size="4" class="qty" value="<?php echo $v['quantity'];?>" id="<?php echo $k;?>"/>
Ajax
$("input[class=qty]").keyup(function()
{
var data;
var newVal = $(this).val();
var id = this.id;
console.log(id+" "+newVal);
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php?id="+id+"&&value"+newVal, //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});
});
updateCart.php
<?php
session_start();
$id = $_GET['id'];//say 2
$new_value =$_GET['value'];//say 16
foreach($_SESSION['cart'] as $k=>$v)
{
$k;
$v["id"];
$v["quantity"];
if($id == $k)
{
//assign new value to the quantity
$_SESSION['cart'][$id]['quantity']=$new_value;
//print_r($_SESSION['cart'][1]['quantity']);
}
}
//echo json_encode($new_value);
//var_dump($_SESSION['cart']);
this can display session['cart'] with updated value if I test in
this page ..but when passed to originated page via ajax, returns null.
echo $_SESSION['cart'][$id]['quantity'];
?>
You left out the = between &value and + newVal. But I recommend you let jQuery do this automatically by using the data: option.
data = { id: id, value: newVal };
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});

How to send json to php via ajax?

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

$.ajax post empty data to server with jsonp

this below code could'nt send data to other server. i want to send "aaa-bbb-ccc" with $.ajax. but after post back userCode thats post empty data from $_POST. sorry for my english
jquery code :
<script type="text/javascript">
$(function(){
$.ajax({
url: "http://www.site.com/index.php",
type: "POST",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
}).done(function(data){
alert(data.message);
});
});
</script>
server index.php :
<?php
include_once ('./AFactory.class.php');
$database= new AFactory;
$db=new AFactory();
$link=$db->getDBO();
if ( $_POST['userCode'] == '')
{
$data['success']=false;
$data['message']='ERROR ...';
}
else {
$query=array('id'=>NULL,'userCode'=>$_POST['userCode']);
$sql=$db->insertQuery('`alachiq_takhmis`.`users`',$query);
if ( mysql_query($sql) )
{
$data['success']=true;
$data['message']=$_POST['userCode'];
}
else
{
$data['success']=false;
$data['message']=$_POST['userCode'];
}
}
echo $_GET['callback'] . '('. json_encode($data) . ')';
?>
post back:
({"success":false,"message":'ERROR ...'})
whats my code problem?
JSONP works by injecting a <script> element with a src attribute into a document.
That can only ever make a GET request.
$.ajax({
url: "http://www.site.com/index.php",
type: "GET",
dataType: "jsonp",
data: {userCode: "aaa-bbb-ccc"}
});

Categories