jQuery / Ajax: How to pass JS variable to specific PHP function [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to PHP and never used Ajax before so I hope someone can help me with this.
I have a separate functions.js file that stores all the JS I use for the pages of a website.
So far all the exchange with the db is done with PHP directly on the pages which works fine so far but now I have a scenario where I need to initiate this from the JS file.
My thought was I could create a separate PHP file (ajax.php) that hosts functions just for such purposes and then pass data via Ajax from the JS file to this PHP file.
So far I have the following but since there are multiple functions on the ajax.php file I am not sure how to pass this to the specific function I need.
Also, I am not sure if the Ajax call I have is set up correctly.
Can someone help me with this and maybe also explain your answer in a few words ?
Basically, here I want to pass the JS variable "itemID" to the PHP function fetchTransMain where this should be used for the variable $itemID (the variable $trans is generated in PHP).
Update: I would also need to know how to get the result from the PHP function back in JS. I didn't find an approach for this yet, perhaps with an Ajax GET call ??
What I have in my functions.js file:
var itemID = "someID";
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: itemID,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
...and on my ajax.php file:
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
Many thanks in advance,
Mike

You have to define data as an object:
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: {itemId: itemID},
success: function(data) {
console.log(data);
alert("success");
},
error: function(){
alert("failure");
}
});
And then:
$itemId = $_POST['itemId'];
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}

I strongly suggest you to read some tutorial about ajax and PHP because there are so many aspects involved in this question that we can't explain them all in one answer. Anyway what you want to do is very common, you have a value in your browser that you want to save on your server.
The first part is almost correct:
$.ajax({
url: "ajax.php",
type: "post",
cache: "false",
data: {valueName: itemID},
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
Just pay attantion to the data parameter, you should pass an object there with a name. That name is the name that you'll use on PHP to retrieve the value.
Then on server side:
function fetchTransMain($trans, $itemID){
foreach($trans as $key => $val){
if($val["ID"] == $itemID){
echo $val["trans"];
}
}
}
$valueFromClient = $_POST['valueName'];
fetchTransMain($trans, $valueFromClient);
Here you have to use $_POST since we have choose type: "post" on the client side.
Hope this helps

Related

How to Parse php json_decode data to Jquery Ajax request [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The current problem now is this, the below files are working perfectly well, but when using console.log(data), it prints out the result I wanted very well.
But what I want is to print out the result in a html tag (div) profoundly instead of console.log().
The Php File section
<?php
$transaction_id = $_POST['transaction_id'];//get the Transaction ID from Ajax request..
//get the full transaction details as an json from VoguePay
$json = file_get_contents('https://example.com/?v_transaction_id=' . $transaction_id . '&type=json');
$transaction=json_decode($json, true);
//header('Content-Type: application/json');
echo json_encode($transaction);
The Ajax Section...
//clear the display section
$("#id-input2").html('');
var data="";
//call the Ajax Request..
$.ajax({
url: "php/fetch_transaction_id.php",
type: "POST",
data: {transaction_id:transaction_id},
dataType: "json",
success: function (vp_response) {
$.each(vp_response, function(index, value) {
data=(index + ': ' + value);
console.log(data);
});
$('#searchID').val('Data Recieved!');
},
});
Here is the output for using console.log();:
cur: NGN
transaction_id: 5a3182d82a8c6
email: talk2awe2004#example.com
total_amount: 1016.7000
total: 1000
merchant_ref:
memo: MLM Bank Union Creation
status: Approved
date: 2017-12-13 20:49:26
method: MasterCard & Verve (Naira)
referrer: https://www.mlmbank.net/Leaders/create.html
total_credited_to_merchant: 1001.450000
extra_charges_by_merchant: 16.700000
charges_paid_by_merchant: 15.250000
fund_maturity: 2017-12-15
merchant_id: 3362-0054095
total_paid_by_buyer: 1000
process_duration: 0.000395
I want same using a html tag instead.
You can return your array in JSON format with application/json content-type
<?php
if(isset($_POST['transaction_id'])) {
//get the full transaction details
$json = file_get_contents('https://example.com');
//create new array to store our transaction
$transaction = json_decode($json, true);
// Here you can do something with $transaction
// And return it in JSON format for ajax request
header('Content-Type: application/json');
echo json_encode($transaction);
}
After that you can get this json in ajax like this
<script>
$.get('transaction.php', {transaction_id: 'SOME ID'}, function(data) {
console.log(data);
});
</script>
jQuery will parse data as javascript object because of content-type
If the link you reach out to has raw json, you can simply echo it out :
PHP
if (isset($_POST['transaction_id']))
{
$TransactionId = $_POST['transaction_id'];
echo file_get_contents('https://example.com');
}
You want to add the success event handler in your ajax call and then $.each through your response. :
*Note : Make sure you have dataType: 'json', this tells jquery to parse the json response.
Javascript :
$.ajax({
type: 'POST',
url: '/yourphpfile.php',
data : {
transaction_id: '0'
},
dataType: 'json',
success : function(response) {
$.each(response, function(key, value) {
console.log(value.whatever);
});
}
});
Read more on accessing json values : jQuery Ajax: get specific object value

Deleting comments from database using php

I am making a forum webpage where I'll put delete this buttons under each comment. Now when you press this button, I send the ID of the comment to PHP file using ajax which looks like this:
function Deletethis(index) {
var result = confirm("Want to delete?");
if (result==true) {
$.ajax({
url: "deletepost.php",
type: "POST",
data: index,
success: function(){
location.reload();
}
});
} else return false;
}
Now the problem is I can't receive it from the PHP end. I've used the debugger and saw that the index value is right. My PHP looks like this:
<?php
$con = mysqli_connect("localhost", "root", "123", "test") or die("DIE");
if (isset($_POST['index'])) {
$SoonToBeDeletedComment = $_POST['index'];
};
$index = intval($SoonToBeDeletedComment);
mysqli_query($con, "DELETE FROM commentsbox WHERE commentsbox.`ID` = $index");
echo "Post Deleted...";
mysqli_close($con);
?>
My code doesnt give any errors but it doesn't delete the post either. When I do the same process manually on navicat, it is working so I thought maybe the index is a string and it should be an integer. So I used intval but it didnt solve the problem either. Any ideas to help me improve my code is appreciated. Thanks in advance
In jQuery's .ajax call, the data property needs to be an object, not a string (string only it it's a full GET query string, actually, but it's not what you need here).
So, try this:
$.ajax({
url: "deletepost.php",
type: "POST",
data: {id: index},
success: function(response){
alert(response);
// location.reload();
}
});
And then in PHP, get it as:
$_POST['id']
UPDATE
Sanity checklist:
is your Deletethis function actually receiving the index?
is your ajax calling the right script?
is ajax data property an object, like I explained above?
what is the output of the PHP script?
what are the contents of $_POST?
is the id inside the $_POST array ($_POST['id'])?
does the row with that id exist in the db?
These questions should help you pinpoint the problem more accurately.
You send param to your PHP code without define his name : data: { index: index } // param : value
function Deletethis(index)
{
if ( confirm("Want to delete?") )
{
$.ajax({
url: "deletepost.php",
type: "POST",
data: {
index: index
},
success: function(){
window.location.reload();
}
});
}
}
Check also if your PHP code is working by calling page directly with param.

refreshing php content inside div when input onchange [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a simple <input> and when user writes there something I need to refresh php inside div so it will look like some.php?key=thevaluefrominput. How would I do that? I guess I need to use query but I'm not sure how.
I want something like this when you write something to Type to find tags it changes the the tags bellow.
Thanks for the answers.
This sounds like a job for AngularJS :)
However this is jQuery solution:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape($.trim($('#myinputfield').val())),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
});
});
If you mean that while user types (before submission), div content changes? Then remove
$('form').submit(function (e) {
e.preventDefault();
and instead put
$('#myinputfield').keydown(function () {
There is a setInterval method that I mentioned in comment, so the first chunk of code I posted, replace it with this one:
$(function () {
var old_val = '';
var curr_val = '';
setInterval(function () {
curr_val = $.trim($('#myinputfield').val());
if (old_val != curr_val) {
old_val = curr_val;
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape(curr_val),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
}
}, 2000);
});
It checks if value of the field changed every 2s, please replace amount in ms (2000) if you like.

How to store value passed by ajax to database? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to display data or value return by the ajax function to be store in php variable as mentioned below. Any help?
This is my code
function getUserInfo()
{
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
I want to display in php variable as
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo $name;
echo $pics;
I would use PHP to make the request and store the result in an array, since you need to use the result in php
$acToken='your value';
$result = file_get_content('https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$acToken);
echo '<pre>';
print_r($result);
echo '<pre>';
make sure to assing a value to $acToken;
In your javascript, create ajax post request to your php url:
$.ajax({
type: "POST",
url: "some.php",
data: { uName: "John", imgHolder: "img" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
For more information, you can read jQuery AJAX documentation
try below:
$name=$_POST['uName'];
$pics=$_POST['imgHolder'];
echo json_encode(array('name'=>$name,'pics'=>$pics));
as that help for you

Sending back multiple results from PHP via AJAX

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Categories