How to post values through Ajax in php? - php

<?php
session_start();
?>
<?php
$con=mysqli_connect("localhost","root","") or die(mysqli_error());
mysqli_select_db($con, "sada_r_t_m");
$result=mysqli_query($con, "SELECT * FROM products ");
echo "<h2 fontsize = '26' color = 'yellow' align = 'center'>Flipkart</h2>";
echo "<table border = '5' cellpadding = '12' align = 'center' background-color = '#84ed86' color = '#761a9b' >";
echo "<tr>";
echo "<th>SNO</th>";
echo "<th>Product Name</th>";
echo "<th>Price</th>";
echo "<th>Cart</th>";
echo "</tr>";
while($data = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<th>".$data['id']."</th>";
echo "<th>".$data['name']."</th>";
echo "<th>".$data['price']."</th>";
echo "<th><a href='#' Onclick='add(".$data['id'].")'>Add to Cart</a></th>";
echo "</tr>";
}
echo "</table>";
?>
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
//contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
</script>
I passed the values through ajax in php. I wrote only in single php page.
How to pass values through ajax in php. While passing values,i am getting below error
Uncaught ReferenceError: $ is not defined
How to achieved this error i am new to php.

Please add jquery library file for use $. Please put this code in your file at top.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
OR
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

Your JavaScript Change this type. Error alert show what error Occurred
Add Jquery library file at head tag
<script type="text/javascript">
function add(id){
alert(id);
$.ajax({
url: '../ajax.php',
type: 'POST',
data: { action: "add",id: id, val:1} ,
success: function (response) {
try{
alert(response.status);
}
catch(e){
alert("Error"+e);
}
},
error: function (e) {
alert("error"+e); or alert("error"+JSON.stringify(e));
}
});
}
</script>
You use try and catch . this show where error show
this code useful for you

I cannot comment yet, so I posted here. There's a good example on another answer on how to properly do ajax post requests:
http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php
Also, this is a good tutorial that will set you on the right track:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
http://hayageek.com/jquery-ajax-post/
Also, try to change ../ajax.php to the full url.

Related

How to refresh map only on click category?

Can some help me to solve this problem
I have a map on my website and i want to refresh map only on clicking on category my this is my product
<?php
/* $message = "in home";
echo "<script type='text/javascript'>alert('$message');</script>";*/
foreach($categories as $category){
echo '<li><img src="'.base_url('uploads/'.$category->image).'" alt="'.$category->cat_name.'" width="30" height="30"/></br><span>'.$category->cat_name.'</span></li>';
}
?>
</ul>
</div>
</div>
<script>
function changeData(category){
var urlCI = '.base_url('main/home/' .$category->adv_category).';
$.ajax({
type: "POST",
url: urlCI,
data:{'categoryReq':category},
success: function(response) {
if(response!=''){
$('map_marker').html(response);
}else{
return false;
}
}
});
}
</script>
my controller code is if you need other code please ask i will give. I give this just for refrence, thank you
public function home($cat=NULL)
{
//$cat=10;
//echo debug_backtrace()[1]['function'];
if($_POST)
{
print_result($_POST);
}
$sql="SELECT * FROM (`ad_category`) WHERE `status`=1 AND `del_status`=0";
$this->data['categories']=$this->db->query($sql)->result();
if($cat)
{
//$message = $cat;
//echo "<script type='text/javascript'>alert('$message');</script>";
//$this->data['middle_view']='home_again';
$this->data['ads']=$this->advt_m->get_advts($cat);
$this->input->post('map_marker',$this->data);
$this->data['subview']='home';
$this->load->view('__layout_main',$this->data);
}
else
{
/*$message = "Here 2";
echo "<script type='text/javascript'>alert('$message');</script>";
*/
$this->data['subview']='home';
//$this->data['middle_view']='home';
$this->data['ads']=NULL;
$this->load->view('__layout_main',$this->data);
}
var urlCI = '.base_url('main/home/' .$category->adv_category).';
probably should be
var urlCI = '<?php echo base_url("main/home/$category->adv_category"); ?>';
Split the Map div and its javascripts into another view.
Create function with all necessary functionalities for map. Add and load the it through Ajax call.
Ajax success:
success:function(response){
$('div').html(response);
//response will be the function which holds the $this->load->view('map');
}
map.php
<div id="map">
YOUR MAP GOES HERE
</div>
<script>
MAP SCRIPT
</script>
main.php (Your frontend)
<div id="map_here">
</div>
<script>
$.ajax({
type:"POST",
//Send some values
data:{
somevalue:'somedata',
category:"mine"
},
url:"<?php echo base_url();?>mycontroller/mapfunc",
success:function(response){
$('#map_here').html(response);
}
})
</script>
myconroller:
function mapfunc(){
//Using this value you can change the script
$data['category'] = $_POST('category');
$data['location'] = $_POST('somevalue');
//Process the works
$this->load->view('map',$data);
//On Ajax call this page can be loaded
}
Each ajax call it will reload the div.
any doubts just comment it...

How to build like counter using jquery?

I'm looking to make a like counter as like in facebook. I will load various posts from database with message id. i want to make like(here it is "pray") counter and it should do behind the page using jquery and ajax. I cant get specific message id(mid). here the code is
jQuery:
$(document).ready(function () {
$("div.pray").click( function()
{
var mid=$(this).val();
$.ajax(
{
type:"POST",
url:"increment.php",
data:'mid='+mid,
success:function ()
{
$("div.pray").text("Prayed");
}
});
});
PHP:
session_start();
if(isset($_SESSION['usrid']))
{
$usr = $_SESSION['usrid'];
include('dbcon.php');
$cot = "select * from posts where userid=$usr LIMIT 10";// order by eventDate DESC, eventHour DESC" LIMIT0,10";
$ex = mysql_query($cot,$con);
while($cont=mysql_fetch_array($ex))
{
$date = date_create($cont['date']);
$mid=$cont['mid'];
echo "<div id='posts'>";
echo $cont['message'];
echo $photo;
echo "<div class='pray'>";
echo "<input type='hidden' class='mid' value='$mid'>";
echo "<a href='#'>Pray</a></div>";
echo "Prayed(".$cont['prayers'].") &nbsp &nbsp";
echo date_format($date, 'd-m-Y H:i:s');
echo "<hr>";
echo "</div>";
}
}
else
{
echo "Login to see";
}
?>
i want to replace only the message which i clicked as pray and also it should load current number of prayed.
put your javascript AFTER your php script and check. If that fails, change your .click() handler to,
$(document).on('click', 'div.pray', function(){
var mid=$(this).children('.mid').val();
$.ajax(
{
type:"POST",
url:"increment.php",
data:'mid='+mid,
success:function ()
{
$("div.pray").text("Prayed");
}
});
//rest of your code
})
Notice, I've changed the first line from
var mid=$(this).val();
To
var mid=$(this).children('.mid').val();
As, $(this) will select the div.pray and not the input.mid element.
In the html code try something like this:
echo "<a href='increment.php?mid=$mid'>Pray</a></div>";
In javascript:
$(document).on('click', 'div.pray', function(e){
e.preventDefault();
var $target = $(e.target).closest('a');
$.ajax({
type:"POST",
url: $target.attr('href'),
success:function (data){
$target.closest("div.pray").html(data);
}
});
});
In the ajax response the html code should go into the div.pray

Updating Database from Javascript by calling PHP script

Ive been trying to get this for age
I am building a website which has an activity wall. I have the whole thing working except the like and unlike buttons. I have them currently just showing a text box I like or I don't like
<a href='#' onclick='like()'>Like</a>
or
<a href='#' onclick='unlike()'>Unlike</a>
Now these call these scripts
<script>
function like()
{
alert("I like");
document.getElementById("p1").innerHTML="<a href='#' onclick='unlike();'>Unlike</a> | 1 Life<hr/>";
}
function unlike()
{
alert("Dont like anymore");
document.getElementById("p1").innerHTML="<a href='#' onclick='like();'>Like</a> | 0 Lifes<hr/>";
}
</script>
I have a php script that connects to the database and adds or removes the like which I know works. I don't need to return anything to the javascript but how do I call that php script giving the postID and username??
Ok so using this I have modified it a little. But it still doesnt work :S
==LikeUnlink.php==
<?php
include 'phpScripts/OpenConnection.php';
$mode = $_GET['mode'];
$username = $_GET['username'];
$postID = $_GET['LikeID'];
echo $username."<br/>";
echo $mode."<br/>";
echo $postID."<br/>";
if($mode == 0)
{
$query = "INSERT INTO tbl1Ups (Username, ActivityID) VALUES ('$username', $postID)";
}
else
{
$query = "DELETE FROM `tbl1Ups` WHERE Username='$username' AND ActivityID=$postID";
}
$result = mysql_query($query) or die(mysql_error());
==MembersHome.php==
<script type="text/javascript">
function process(LikeId, Username, currentLikes, likeUnlike)
{
//your validation code
$.ajax(
{
type: 'GET',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId, username:Username, mode:likeUnlike},
success: function(data)
{
alert('It Works');
}
} );
}
</script>
==Like link==
<a href='Javascript:void(0)' onclick='process(".$row['ID'].", \"".$username."\", ".$likes.", 0);'>$linkText</a>
try this
<script type="text/javascript">
function process(LikeId) {
//your validation code
$.ajax( {
type: 'POST',
url: LikeUnlike.php, //file where like unlike status change in database
data:{like:LikeId},
success: function(data) {
//code you want to do after successfull process
}
} );
}
</script>
make changes in html
<a href='Javascript:void(0)' onclick='process(1)'>Like</a>
<a href='Javascript:void(0)' onclick='process(0)'>Unlike</a>

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

Stuck with Codeigniter and jQuery.ajax

So... thanks to one of stackoverflow users I tried to implement this fancy feature into my existing Codeigniter application...
In my View I have this:
<script type="text/javascript">
$(function() {
$(".submit_op").click(function() {
var dataString = $("#op_form").serialize();
var url = "<?php echo site_url('submit/insert_data'); ?>";
$.ajax({
type: "POST",
url: url+"/"+dataString,
data: dataString,
cache: false,
success: function(html){
//$("div#op").prepend(html); //PROBLEM HERE???
$("div#op").prepend("<div>TEST</div>");
$("div#op div:first").fadeIn("slow");
//$("#debug").append("<font color=green><b>OK!</b></font> : " + dataString + "<br/>");
},
error: function(html){
//$("#debug").append("<font color=red><b>ER!</b></font> : " + dataString + "<br/>");
}
});
return false;
});
});
</script>
<div id="debug"></div>
<?php
//here goes some data from db... newly added div should go in top of other divs
foreach ($some_data_sent_from_controller as $var) {
echo "<div id=\"op\">";
echo "<table width=\"100%\" border=\"0\">";
//showing data
echo "</table>";
echo "</div>";
}
echo "<form action=\"#\" id=\"op_form\">";
//some clickable stuff...
echo br().form_submit('submit', 'OK', 'class="submit_op"');
echo "</form>";
In my Controller I have a function which handles data sent from View:
function insert_data($input) {
$this->load->model('blah_model');
//processing serialized data and sending it to corresponding tables via Model
$this->blah_model->add_to_table($some_data);
$this->blah_model->add_to_another_table($some_other_data);
}
And the Model is not a biggy :)
function add_to_table($data){
//processing data...
$insert = $this->db->insert('my_table', array('array_which_contains_actual_data'));
if ($insert == TRUE) {
return TRUE;
} else {
return FALSE;
}
}
//etc.
As far as I can tell, my problem is not in my M-V-C pattern, since every time I submit a form the data is correctly inserted in all possible tables in my relational db... But the newly added row just won't show up unless I refresh a page.
I think that I'm doing something wrong inside of my jQuery.ajax lines... If I run my script with this line $("div#op").prepend("<div>TEST</div>"); and when I submit a form, I get desired result - text TEST shows up on top of my page every time I submit... But if I change that line to $("div#op").prepend(html); nothing show up until refreshing...
What am I doing wrong here??
Thanks a lot for any help!
wow, this was probably pretty lame from me... But in the end I figured out that I have to echo out my result in controller, not return it... So when I change the function in my controller into
function insert_data($input) {
$str = "<div>KILLROY WAS HERE!</div>";
echo $str; // <----- !!!!!!
}
I can see a message on my page...
Now to other things... Thanks for self-brainstorming :)

Categories