Passing variables to PHP script via AJAX - javascript

I am truing to pass variables to a PHP script using onclick but obviously I am doing something wrong.
So..I have in my main page somewhere:
<img src="myImage.jpg" id="cart_icon" onclick="addcart('100')">
and the addcart function:
function addcart(id){
$.ajax({
url: "add_item.php",
method: "POST",
data: {prod_id : id}
});
}
The add_item.php looks like this (just a simple example):
if (!isset($_SESSION)) session_start();
if (isset($_POST['prod_id'])){$_SESSION['item_id']=$_POST['prod_id'];}else($_SESSION['item_id']='Not Set');
When I check the value of the SESSION['item_id'] I am getting 'Not set' instead of '100'
Any thoughts? This is just a simple example. The actual code is more complex. Thanks

Firstly, your AJAX call looks incorrect because the method of the call needs to be defined via type and not method.
Read the documentation of $.ajax.
The correct call should be:
function addcart(id){
$.ajax({
url: "add_item.php",
type: "POST", // notice the change over here
data: {prod_id : id}
});
}

Related

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});

Posting variable from JavaScript to PHP?

I have been trying to post a JS variable into PHP with using the $.ajax function. It didn't work though. The situation is like this: There is a page with a submit button, if I the button is clicked it loads a JS function which has confirm() in it. If I click OK (if confirm is true) it should execute the post action on another php page.
function sure () {
var conf = confirm(text here);
$.ajax({
url: 'action.php',
type: Post
data: {istrue: conf};
})
. }
It's jQuery related than JavaScript.
There is not type param in $.ajax. You have to use method param instead.
$.ajax({
method: "POST",
url: 'action.php',
data: {istrue: conf}
})

Value attribute of html element is undefined

Why is name undefined?
$('#langs li').click(function(){
var name = $(this).attr('value');
$.ajax({
type: "POST",
url:'test.php',
data: 'name='+name,
success:function(raspuns){
//$('#content1').html(raspuns);
var ras = raspuns;
$.ajax({
type: "POST",
url: "index.php",
data: 'ras='+ras;
)};
}
});
});
You can check a few things:
make sure you have data before sending. you have value attribute on li? or if you want to get li contents, use html() or txt(). But probably you want to get input field value inside li?. then use $(this).find("input").val() if you have just one input inside.
Then others to check:
1) Visit http://example.com/test.php to make sure it echoes the response correctly. You may have error in php or the link may not be accessible.
2) Your url is like this: http://example.com/test.php ? It is also fine if you have a virtual host in your local machine like http://example.local/test.php. But it will not work if you have something like
http://localhost/mysite/test.php
unless you correct your path in ajax call to a full link.
3) Make sure your javascript doesnt fail before sending. I mean, are you able to do alert(name) ? You can also use beforeSend() above success to check if you are ending data correctly.
4) Make sure you are not trying to make a cross domain ajax request as you can't do so with POST.
5) May try using "/test.php" instead of "test.php" although it wouldn't be the problem, I think.
You can also use console to see what is going on.
If what you mean is that raspuns seems to be undefined, maybe it's because you did not echo your response from test.php?
test.php
...
echo 'this is my response';
AJAX call
$.ajax({
...
success: function(raspuns) {
// raspuns == 'this is my response'
}
});
And also, if you're passing POST data, I think it would be better if you pass a JSON object, like so:
$.ajax({
url: 'test.php',
type: 'POST',
data: {name: name},
...
});
li elements don't support a value attribute. Perhaps you're looking for an input or the contents of li via .html().
See in this demo that name is undefined: http://jsbin.com/IzOXiJOZ/2/edit

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

AJAX call with jQuery and get result

jQuery.ajax({
type: "POST",
url: "index.php?page=Chat",
data: { action: "sendMessage" },
}).done(function(msg) {
jQuery("#main").append(msg);
});
and my PHP code simple returns a string
return 'myString';
Unfortunately myString is not added to the #main-container. What is wrong with this code?
The OP tried to treat php pages as functions but php pages cannot return value like functions.
Therefore the solution of this question is to print $mystring in php page instead of returning it.

Categories