Using only one js file for multiple php ajax calls - javascript

First of all, my intention is to have 1 js file where there are multiple ajax calls. I want these ajax calls, which are php files, to have the same js file inside of it but not doing another request, which makes it to run slow after any click.
Some of my main php file:
<head>
<script src="<?php echo $_SESSION['url'] ?>js/direcinfo.js"></script>
</head>
<body>
<div class="direcciones">
<a href="javascript:void(0)" id="c_menu_direcciones" class="c-menu c_menu_direcciones">
<p>
Direcciones
</p>
</a>
</div>
<div id="cuenta_menu_direcciones" class="c-menu-content">
<h1>Direcciones de correo</h1>
<div id="expand_wrapper_dir">
</div>
</div>
</body>
Js file (direcinfo.js):
$('#c_menu_direcciones').click(function(){
$.ajax({
dataType: "html",
type: "POST",
url: "direcalias.php",
success: function(cntnt){
$("#expand_wrapper_dir").html(cntnt);
}
});
return false;
});
$(".alias-dir-a").click(function(){
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});
Ajax loaded file (direcalias.php)
<?php
session_start();
header("Content-Type: text/html; charset=ISO-8859-1");
include_once 'connection.php';
$conn = bbddconnect();
$email=$_SESSION['useremail'];
$query = "SELECT CODIDIR,ALIAS"
. " FROM CLIENTE C,DIRECCION D"
. " WHERE EMAIL LIKE '$email' AND C.CODICNT = D.CODICNT;";
$result3 = mysqli_query($conn,$query)or die(mysqli_error());
$recount = mysqli_num_rows($result3);
echo '<div class="menu-alias madir">';
for($i=0;$i<$recount;$i++)
{
$row = mysqli_fetch_array($result3);
echo '<div class="alias adir ali-'.$i.'">
'.$row['ALIAS'].'
</div>';
}
echo '<div class="alias adir ali-nuevo">
+
</div>
</div>
<div id="direc-content"></div>';
//echo '<script>'.
// 'var url = "'.$_SESSION['url'].'js/direcinfo.js";'.
// '$.getScript(url);'.
// '</script>';
?>
The problem I have is that when the direcalias.php file is called I need to call the js file again (edited part) because if I don't, it does not recognize when I click on $(".alias-dir-a").click(function()). Is what I want to do possible?

It beacuse you call .alias-dir-a before it create. you can use on method
$(document).on("click", ".alias-dir-a", function() {
var useremail=$("#useremail").val();
var alias=$(this).html();
if(alias==="+")
{
$.ajax({
dataType: "html",
type: "POST",
url: "direcnew.php",
data: "email="+useremail,
success: function(cntnt){
$("#direc-content").html(cntnt);
}
});
return false;
}
});

Related

PHP not returning Ajax Call

I'm trying to send over the data from my textarea using an ajax call to my PHP file, but we aren't getting any response back from the PHP file.
<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>
<script>
$('#submit').click(function (e) {
e.preventDefault();
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php',
data: {area: info}
});
});
</script>
<?php
if (!empty($_POST['area'])) {
$success = json_encode('succes');
return $succes;
};
?>
-- # Answer # --
I thought I had already tried an echo in this piece of code, but I think I just missed the output on the webpage and thought it wasn't working.
<?php
if (!empty($_POST['area'])) {
echo "success";
};
?>
Thanks Mickael for the answer!
I completely forgot to add an echo to my code.
<?php
if (!empty($_POST['area'])) {
$succes = json_encode('succes');
echo $succes();
};
?>
Your ajax post :
$('#submit').click(function (e) {
e.preventDefault();
// information to be sent to the server
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php?return=1',
data: {area: info},
dataType:'json',
success:function(r){
console.log(r);
}
});
});
and your php response will be like
Php file:
<?php
if ( $_GET['return'] == 1 && isset($_GET['return']) ) {
echo json_encode('succes');
exit;
};
?>

codeigniter get ajax post files

am trying to upload multiple files using ajax in codeigniter. my ajax post is working fine but i don't know how to get the post files in my controller.
I tried this way but its not working. please help. Thank you.
HTML
<form method="post" name="upload_files" action="<?php echo base_url(); ?>home/upload_files" id="form_files" enctype="multipart/form-data">
<h4 style="float: left">Add files. (file types .png, .jpeg, .dwg, .pdf, jpg) max: 10Mb <span style="color:red;" id ="err_type"> * </span></h4>
<div class=from-section>
<div class="row">
<div class="span4" id="image" >
<div class="cart-total" id="clone_image" data-provides="fileupload">
<div class="form-group has-success has-feedback">
<input class="form-control" type="file" name="files[]" accept="image/*" />
</div>
</div>
</div><!-- /.span4 -->
</div><!-- /.row -->
</div>
<div class="cart-total">
<a id="another_image" class="btn btn-default" style="height: 45px;padding: 12px 12px; margin-right: 10px; ">+ Add More Files</a>
<a id="submit_files" class="rx-bottom" >Submit Files</a>
</div>
</form>
AjAX
<script type="text/javascript">
$('#submit_files').click(function() {
var formData = new FormData($('#form_files')[0]);
$.ajax({
url: "<?php echo base_url('home/upload_files/'); ?>",
type: "POST",
data: formData,
mimeType: "multipart/form-data",
processData: false,
contentType: false,
success: function(res) {
console.log("success");
},
error: function(res) {
console.log("error");
}
});
});
</script>
My console is logging success message
CONTROLLER
public function upload_files(){
$order_id = 123;
if(!$order_id){
redirect('home/instant_quote', 'refresh');
}else{
$this->load->library('upload');
//$files = $this->input->post();
$files = $_FILES;
if($files){
for( $i = 1; $i < 20; $i++) {
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|pdf|dwg|zip';
$config['max_size'] = '11000';
$config['file_name'] = 'order_'.$order_id.'_'.$i;
$config['overwrite'] = false;
$this->upload->initialize($config);
$this->upload->do_upload('files'.$i);
$image_data = array('upload_data' => $this->upload->data());
if($image_data["upload_data"]["file_size"]){
$inserted['order'] = $i ;
$inserted['name'] = $image_data["upload_data"]["file_name"];
$inserted['extension'] = $image_data["upload_data"]["file_ext"];
$inserted['type'] = $image_data["upload_data"]["file_type"];
$inserted['size'] = $image_data["upload_data"]["file_size"];
$prop = $this->home->insert_files($inserted);
}
}
}else{
$this->load->view('comman/header.php');
$this->load->view('home/add_files.php');
$this->load->view('comman/footer.php');
}
}
}
This is what i see when i log the form data
You can use this in your controller:
function upload(){
if(!empty($_FILES)){
$type= $_FILES["files0"]["type"]; //files0 is your input file name
$size= $_FILES["files0"]["size"];
$file_name = $_FILES["files0"]["name"];
$source = $_FILES['files0']['tmp_name'];
$dir = "./uploads/";
$file = $dir . $file_name;
if(!file_exists ($file ))
{
move_uploaded_file($source,$file );
exit("File has been uploaded");
}
else
{
echo "File exist";
}
}
$this->load->view('v_test');
}
And for your ajax jquery:
//add this to your head html
<script>
var base_url = "<?php echo base_url(); ?>";
</script>
and, this is your ajax call :
$("#submit_files").click(function() {
var formData = new FormData($("#form_files")[0]);
$.ajax({
url: base_url + "home/upload_files",
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Please test with single file first, and if it worked. Try to dynamically upload multiple files. Hope this help you out. :D

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

Facing on Make Like Unlike Button in php , mysql using ajax calling

I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value
Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;

Ajax call with javascript not working

I want to try to get some value from page cart.php from and ajax call, but its not working.
Ajax code is below:
function temp_sell(id) {
//var p_id=document.getElementById('temp').value;
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: "value=" + p_id,
success: function (message) {
alert(message);
$("#your_cart").html(message);
}
});
}
temp_sell.php is below where I want to show some products details
<?php
include("connection.php");
echo $p_id = $_POST['value'];
$qty=1;
$query="SELECT * FROM product WHERE id='$p_id'";
$result=mysql_query($query);
while($data=mysql_fetch_array($result))
{
?>
<form>
<table>
<tr>
<img src="<?php echo "img/".$data['image'];?>"/>
<strong><?php echo $data['pro_name'];?></strong>
<strong><?php echo $data['price'];?></strong>
<input type="text" value="<?php echo $qty;?>"/>
</tr>
</table>
</form>
<?php
}
?>
p_id is undefined, you have commented the p_id value or change temp_sell(p_id).
function temp_sell(p_id)
instead of
function temp_sell(id)
Reference comments : Ajax call with javascript not working
Do this :
function temp_sell(id){
var p_id=document.getElementById('temp').value; // <--- uncomment this line
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: {value:p_id}, // <--- change this
success: function(message){
alert(message);
$("#your_cart").html(message);
}
});
}

Categories