Reputation: 33
I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:
<div class="img">
<a href="ss.php">
<img id="theme_bg" src="images/themes/theme1.jpg">
</a></div>
$(document).ready(function($){
$('.img').on('click','img',function(){
var imgsrc = $(this).attr('src');
alert(imgsrc); //this is returning the img src correctly
$.ajax({
type: "POST",
url: 'ss.php',
dataType: 'json',
data: {imgpath:imgsrc },
success: function(response) {
content.html(response); // i tried alert here but it shows nothing
}
});
});});
receiving PHP file code is:
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..
updated Screen shots of code both files
updated screen shots of output
Upvotes: 0
Views: 597
Reputation: 4007
Why you wrote ss.php
in anchor you dont need that that's why it redirecting ss.php
on click and getting error undefined index.
Your html code should be like this:
<form id="myForm" method="post" action="ss.php">
<div class="img">
<img id="theme_bg" src="images/themes/theme1.jpg">
<input name="imgpath" id="imgpath" type="hidden"/>
</div>
</form>
Jquery code:
$(document).ready(function ($) {
$('.img').on('click', 'img', function () {
var imgsrc = $(this).attr('src');
$("#imgpath").val(imgsrc); //this is returning the img src correctly
$("#myForm").submit();
});
});
ss.php
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
Upvotes: 0
Reputation: 1069
You have dataType set to json
so PHP should php <?php echo json_encode([$imagepath])
The better solution would be dataType: text instead of JSON
Note that in $.ajax the dataType is for response not request
Check $.ajax manual http://api.jquery.com/jquery.ajax/
Upvotes: 1
Reputation: 117
Try this one. Add this one to document.ready function
$(".img").click(function() { $.ajax({ type: "POST", url: "ss.php", data: {imgpath:imgsrc}, dataType: "text", cache:false, success: function(data){ alert(data); } });// you have missed this bracket return false; });
Upvotes: 0