Can't get jQuery var to PHP - javascript

I am trying to get a jQuery var into PHP so I can use it with mysql. I have searched everywhere but nothing seemed to solve it.
I have the following jQuery code:
$('.eventRow').click(function(){
var eventID = this.id;
$.ajax(
{
url: "index.php",
type: "POST",
data: { phpEventId: eventID},
success: function (result) {
console.log('success');
}
});
$('#hiddenBox').html(eventID);
console.log(eventID);
});
If I run this, the ID is shown in both #hiddenBox and in the console.log. The console also says "Succes" from the Ajax.
I am trying to get it in the php file:
$value = $_POST['phpEventId'];
echo "<div class = 'showNumber'>"."Nummer: ".$value."</div>";
It just says: Nummer:
It also gives no error whatsoever.
Thanks for your help!

Try
var eventID = $(this).attr('id');
Where this id comes from in your code ?

Passing it as JSON often gets the results I'm looking for. The server will interpret the JSON object as POST variables:
$.ajax({
url: "index.php",
type: "POST",
data: JSON.stringify({phpEventId: eventID}),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
}
});

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);
}
});

AJAX data not passing to PHP

I am having trouble passing AJAX data to PHP. I am experienced with PHP but new to JavaScript.
HTML / JavaScript
<input type="text" id="commodity_code"><button id="button"> = </button>
<script id="source" language="javascript" type="text/javascript">
$('#button').click(function()
{
var commodity_code = $('#commodity_code').val();
$.ajax({
url: 'get_code.php',
data: "commodity_code: commodity_code",
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
});
</script>
PHP
$commodity_code = $_POST['commodity_code'];
$result = mysql_query("SELECT description FROM oc_commodity_codes WHERE code = '$commodity_code'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I know the general AJAX fetch and PHP code is working as I can manually create the $commodity_code variable and the script works fine. I think my issue lies somewhere in passing the AJAX data to my PHP script.
You forgot to add the method: 'POST' in your AJAX Call. And you have some issues with your call. Check below:
$.ajax({
url: 'get_code.php',
method: "POST", // Change here.
data: {commodity_code: commodity_code}, // Change here.
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
Or to make it simple, use the shorthand function:
$.post('get_code.php', {commodity_code: commodity_code}, function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
});
error in this line data: "commodity_code: commodity_code", .. you can simple pass the commodity_code variable..
$.ajax({
url: 'get_code.php',
method: "POST",
data: commodity_code,
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});

GET var from php to use in javascript function

i want to get a var from a php script and use it in a function .. so if i call the var simply with $.get (and document.write) i got an result but how can i integrate this into a function ?
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php', function(verdienst_php) {
//document.write(verdienst_php);
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
only put the function into the $.get part didnt work
if i didnt use $.get and write in datastring like
verdienst: 1000
it works
any suggestions ?
kind regards Dave
Assuming you are returning exactly what you want from the server, store it in a variable and reference the variable in the other Ajax call.
var verdienst_php;
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php',
function(response) {
verdienst_php = response;
});
function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
If you want the GET call to happen when the click happens, than you just need to put the post code inside of the GET success callback.
You have to make an extra ajax call to get php variable, you can do it this way :-
function sendview () {
var datastring = {uid : uid_clear, verdienst : getPHPVar('verdienst_php')};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}
function getPHPVar(varname){
var returnValue = null;
$.ajax({
url: 'yourphpurl.php',
async: false,
type: 'post',
data:{
task:'getvar',
varname: varname
},
success: function(response){
returnValue = response;
}
});
return returnValue;
}
and in PHP it will look like:
<?php
if($_POST['task'] == 'getvar'){
echo $$_POST['varname'];
}
Also, I think it's actually not needed cause you are getting php variable using ajax, and again using it in another ajax call. so Why don't you just do it in php ?

using javascript onload() and ajax to retrieve php array

I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.

Pass Array and String from Javascript to PHP with AJAX

I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!
try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.
When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2
Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

Categories