Send js varible to php file with ajax - javascript

I would like to send my variable "var targetId" to my php file.
I try to make ajax request but nothing happens.
My js file :
$( ".project_item" ).click(function(e){
var targ = e.target;
var targetId = targ.dataset.id;
console.log(targetId);
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.ajax({
url: 'function.php',
type: "POST",
data: {idVoulu: targetId},
success: function(data){
alert(data);
console.log(data);
}
});
});`
And my php file to get the data
$idProject = (isset($_POST['idVoulu'])) ? $_POST['idVoulu'] : 0;
if($idProject==0) { echo ' ID not found';}
Can you tell me what's going wrong?

Well I can't Find a problem on your code but you can try this may be this will help you
var mydata = "idVoulu='+targetId+'"; // make a string
$.ajax({
url: 'function.php',
type: "POST",
data: mydata,
success: function(data){
alert(data);
console.log(data);
}
});

So, i made this and it works:
My js:
$( ".project_item" ).click(function(e) {
var targ = e.target;
var targetId = targ.dataset.id;
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.post('../function.php', { id: targetId }, function(response) {
console.log("reponse : ", response)
});
My php :
if (isset($_POST['id'])) {
$newID = $_POST['id'];
$response = 'Format a response here' . $newID;
return print_r($response);
}

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Need to get some value of variable from linked lists

I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);

jQuery Ajax GET request not working correctly

I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});

ajax reporting success but nothing changing on the database

First, thanks for you reading. Here is my code
scripts/complete_backorder.php
<?php
if(!isset($_GET['order_id'])) {
exit();
} else {
$db = new PDO("CONNECTION INFO");
$order = $db->prepare("UPDATE `scs_order` SET `order_complete`= 1 WHERE `order_id` = :var");
$order->bindValue( ':var',$_GET['order_id'] );
if ( $order->execute() ) {
echo "DONE";
};
};
?>
js/tabs.js
/*
[#]===============================================================================[#]
MODAL: "complete_backorder_Modal"
USAGE: modal to confirm whether or not user want to complete a backorder.
[#]===============================================================================[#]
*/
$(function(){
$(" .remove_record ").click(function( event ){
event.preventDefault();
var rows = $(this).parent().parent().parent().parent().find("tr:last").index() + 1;
var order = $(this).attr("href");
var dataString = 'order_id='+order;
$( '#complete_backorder_Modal' ).modal({
keyboard: false,
backdrop: 'static'
});
$( '#complete_backorder_Modal #modal-yes' ).click(function(e){
$.ajax({
type: "POST",
url: "../scripts/complete_backorder.php",
data: dataString,
success: function(data){
alert("Settings has been updated successfully.");
}
});
});
});
});
so i know the php code is working as ive tested it over and over manually. but when i click on the ".remove_record" button the modal shows and i click the yes button in the modal the alert boxes shows up to say it was successful but when i look at the database nothing has changed.
any ideas?
Your SQL is never running becuase there are no $_GET variables, your are using $_POST But even if you did you are not passing through order_id correctly. Change:
var postData = {'order_id ' : order}; // instead of var dataString = 'order_id='+order;
And
$.ajax({
type: "POST",
url: "../scripts/complete_backorder.php",
data: postData, // instead of dataString
success: function(data){
alert("Settings has been updated successfully.");
}
});
In the PHP change:
if(!isset($_POST['order_id'])) { // Insetad of $_GET
And
$order->bindValue( ':var',$_POST['order_id'] );

Categories