Handle with ajax request after click link - javascript

i have link in my page
+1111
i want to save every click in database
i made this ajax code :
<script type="text/javascript">
$('#tel').on('click', function() {
var location = $(this).attr('href');
var action = 'script.php';
$.ajax({
method: 'POST',
url: action,
data: '',
dataType: 'json',
success: function (data) {
window.location = location;
},
error: function(data){
return false;
}
});
});
</script>
now what must i do, what is the code i have to put in script.php

First you need send some data to script.php, for example
url: action,
data: {location: location},
dataType: 'json',
next in script.php you can read this data
$_POST['location']
create sql query and save data in DB.

send href as json
<script type="text/javascript">
$('#tel').on('click', function() {
var location = $(this).attr('href');
var action = 'script.php';
$.ajax({
method: 'POST',
url: action,
data: {"href":location}, // this line update
dataType: 'json',
success: function (data) {
console.log(data['state]); // this line add for debug server side
window.location = location;
},
error: function(data){
return false;
}
});
});
</script>
and update script.php like below:
<?php
if($_POST['href']){
//connect to database
//update table
echo json_encode(array('state'=>'ok'));
}else{
echo json_encode(array('state'=>'error'));
} ?>

Related

How do I alert the variable using url segment with ajax?

I am using HVC codeigniter.
I wanted to alert the value of variable.
Here's the code on my view.
$("#user_table tr").click(function(){
$userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history/$userid",
success: function(data){
alert(data);
}
});
});
Here's the code on my controller.
function log_history($userid) {
echo $userid;
}
You need to edit your code as follows
var userid = $(this).closest('tr').children('td:first').text();
url: "manageUser_controller/log_history/'+userid,
try to send as data like this
$("#user_table tr").click(function(){
var userid = $(this).closest('tr').children('td:first').text();
$.ajax ({
type: "POST",
url: "manageUser_controller/log_history",
data:{userid : userid},
success: function(data){
alert(data);
}
});
});
and get it on controller using input post like this
function log_history()
{
$user_id = $this->input->post('userid',true);
echo $userid;
}
it's also be filter by true.

Getting multimple results from Ajax post

Maybe this is a duplicate but I can not understand why mo code does not work. I am trying to get multiple results via Ajax/php.
This is from my php file:
$result11 = 'test1'
$result22 = 'test2';
echo json_encode(array("data1" => $result11, "data2" => $result22));
Ajax call:
$(document.body).on('submit','#sendmessage',function() {
$.ajax({
type: "POST",
url: "/send.php",
data: {par:par,kid:kid,ha:ha,sform:sform,editors:editors},
cache: false,
dataType:'json',
success: function(datax) {
alert(datax.data1);
}
});
return false;
});
Problem:
When I submit a form, the page refreshes instead of sending ajax request.
At the same time this works but I can't get multiple results from Php file:
$(document.body).on('submit','#sendmessagex',function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
Add a preventDefault() call to your script
$(document.body).on('submit','#sendmessagex',function(event) {
//----------------------------------------------------^^^^^
event.preventDefault();
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
You have to use preventDefault() ofcourse to prevent page refresh. Then you can use the second code without datatype json. But in that case at first you have to parse the json like this way:
success: function(data){
var datax = JSON.parse(data);
//now you have object and can access like this: datax.data1, datax.data2
}
Incase you want to use first code, in php you have to set php header to define it as proper json output.
header('Content-Type: application/json');

Passing GET parameter with ajax

I have a link that I want to use with ajax. Here is the link:
<a class="export_csv" href="ajax/createCSV.php?saleid=4"><img src="/img/record.csv.png"></a>
The ajax works fine but I can't pass through the GET variable. Here is the jquery:
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: $(e).data['saleid'],
success: function(results){
console.log('it worked');
}
});
});
Here is the target php page:
<?php
include('./includes/global.php');
//$cl = new Client();
//$cl->createCSV();
echo "This Works ";
$test = $_GET['saleid'];
echo $test;
echo "did work for me";
?>
try like this ,send data to php page using data option
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: "saleid=4",
success: function(results){
console.log('it worked');
}
});
})
or
$('.export_csv').on('click', function(e){
urls=$(this).attr('href');
e.preventDefault();
$.ajax({
url:urls,
type: 'GET',
success: function(results){
console.log('it worked');
}
});
}
You need to pass the data as JSON format like
data:{saleid:$(e).data['saleid']}
But actually dont know what is $(e).data['saleid']
$('#myDomSelectorId').data['saleid'] need to be JSON formated like this :
data : { saleid : $('#myDomSelectorId').data['saleid'] }
Or directly data : "saleid="+$('#myDomSelectorId').data['saleid']
Full example :
$('.export_csv').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'ajax/createCVS.php',
type: 'GET',
data: { saleid : $('#myDomSelectorId').data['saleid'] },
success: function(results){
console.log('it worked');
}
});
});

ajax send form request to the same page to run SQL/PHP queries

<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "menu.php?addnotification=yes",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
$('.overlay').fadeOut();
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
i am trying to run this ajax code to POST data to menu.php page from a submitted form
on menu.php i have
if($_GET["addnotification"] == 'yes') {
//do stuff here
echo 'form submitted';
}
but i cannot see the text form submitted
UPDATE
i have changed to this code:
<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
and put the SQL queries on a different page, but now the please_wait_box shows and does not hide, the queries are not running at all
In your url you've got no blank, but in your php document there is a blank.
menu.php?addnotification=yes
vs
$_GET["add notification"]
You are sending a POST request and then reading the $_GET response, try changing the
type: "POST",
for
type: "GET",
in your ajax call.
and also read addnotification and not add notification (probably a typo)
Check your this part of code:
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
You are searching for success in res whereas i think your res will be a string "form submitted". You can try calling alert(res); or console.log(res) to see what is being returned in your response.
Additional debugging process:
change your code for ajax to below:
var request = $.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString
});
request.done(function( msg ) {
$("#please_wait_box").hide();
$("#message").html(msg);
$('#message').fadeIn('slow');
if(msg.indexOf("success")!=-1)
{
window.location.href = msg.substr(8);
}
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Javascript. Run a AJAX flow after current AJAX stops

So I have a simple javascript that loads more comments from a database when the user clicks More.
Now I would like to extend this script so that it first populates the SQL database before it starts letting users view the comments. And I feel that I'm on the right track but I can't get it to work.
First the code that does WORK.
$(function() {
$('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
Now I feel that this should be possible to expand like this.
$(function() {
$.ajax({
type: "POST",
url: "/populate_sql.php",
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
sucess: $('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
});
Where am I loosing it?
You can use this function. I used it before and it works great. after first callback receives then it send second request.
(function($)
{
var ajaxQueue = $({});
$.ajaxQueue = function(ajaxOpts)
{
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next)
{
ajaxOpts.complete = function()
{
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
})(jQuery);
use it like the normal ajax. sample:
$.ajaxQueue({ url: 'x.php', data:{x:x,y:y}, type: 'POST',
success: function(respond)
{
.....
}
});
so you can check if there was a callback from first ajax then send second request.
hope it helps you.
Thanks for the answer. It was not exactly what I needed but it gave me an idea and the solution that works for me was 2 javascripts working together. I'm leaving the code here if someone needs something similar.
<script type="text/javascript">
jQuery(function($){
var pid = '<?php echo $ids['0']; ?>';
$.ajax({
type: "POST",
url: "/prepare_sql.php",
data: "pid="+ pid,
beforeSend: function() {
$('div#updates').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html) {
$("div#updates").replaceWith(html);
}
});
});
</script>
<script type="text/javascript">
$('.load_more').live("click",function() {
var photoid = document.getElementById('photoid').value;
var lastid = document.getElementById('lastid').value;
if(lastid!='end'){
$.ajax({
type: "POST",
url: "/more_comments_ajax.php",
data: {
photoid : photoid,
lastid : lastid
},
beforeSend: function() {
$('a.load_more').html('<img src="/images/loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("div#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
</script>

Categories

Resources