PHP function on JS Click? - javascript

I have a button that will copy a link to the clipboard but it has been shortened using bit.ly. At the minute I have it so that it creates the bit.ly link on page load which seems a bit messy so I just wondered how I can make it only do it when it copies to the clipboard?
var client = new ZeroClipboard( document.getElementById("copy-link"), {
moviePath: "ZeroClipboard.swf"
} );
client.on( "load", function(client) {
// alert( "movie is loaded" );
client.on( "complete", function(client, args) {
// `this` is the element that was clicked
$.gritter.add({
// (string | mandatory) the heading of the notification
title: 'Link Copied',
// (string | mandatory) the text inside the notification
text: 'Link has been copied to your clipboard'
});
$('[data-toggle="dropdown"]').parent().removeClass('open');
} );
} );
This is my PHP
<?php
$url = Router::url(null, true);
if ($this->UserAuth->isLogged()) {
$url .= '?shareref=' . $var['User']['id'] . '';
}
$shortlink = bitly_v3_shorten($url, 'bit.ly');
?>

JQuery Ajax will be your best option: http://api.jquery.com/jquery.ajax/ - Create it so that it runs the PHP when you click the button.

Javascript can be like this
// Java script
jQuery("copyButton").click(function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : 'urlshortener.php',
success: function(response) {
if(response.type == "success") {
var shorturl = response.short;
}
}
});
});
PHP looks like this, maybe its good to be protect it by XHTTP referees etc..
// PHP
$url = Router::url(null, true);
if ($this->UserAuth->isLogged()) {
$url .= '?shareref=' . $var['User']['id'] . '';
}
$shortlink = bitly_v3_shorten($url, 'bit.ly');
$result['type']= "success";
$result['short'] = $url;
$result = json_encode($result);
echo $result;
die();

Related

Submit form with AJAX and PHP without page reload

I have "add to favorite" feature in my wordpress project, I am using <form> to submit the feature. Each time I click on add to fav button it works, but the page is always reloaded which is annoying so I decided to use AJAX, but I can not connect it with my PHP file.
This is PHP file, where I wrote function for the feature
if (! function_exists('favorite_button_icon')) {
function favorite_button_icon() {
echo apply_filters( 'favorite_button_icon', get_the_favorite_button_icon() );
}
}
if (! function_exists('get_the_favorite_button_icon')) {
function get_the_favorite_button_icon() {
$output = '';
$action = $currentPath; // window.location.href
$name = is_favorite() ? 'remove_favorite' : 'add_favorite';
$class = 'favorite-button-pro' . ( is_favorite() ? ' favorite' : '' );
$icon = is_favorite() ? 'Added' : 'Add';
$output .= '<form method="post" id="favorite_user_post"
class="favorite_user_post" action="'. $action .'">';
$output .= '<button id="submit-favorite" type="submit" name="'. $name .'"
value="'. get_the_ID() .'" class="'. $class .'">';
$output .= $icon;
$output .= '</button></form>';
return apply_filters( 'get_the_favorite_button_icon', $output );
}
}
And I am just calling that function in html
<div class="add-to-favorites-option" >
<?php favorite_button_icon() ?>
</div>
Everything above works, but as I said, page is being reloaded.
This is my attempt to use AJAX
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
var url = form.attr('action');
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});
I get absolutely no fire on submit, am I missing something?
You need to use the wp_ajax_ hook: https://developer.wordpress.org/reference/hooks/wp_ajax_action/
Simple example below:
You PHP code to process the ajax request:
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
// code that captures your ajax POST request
wp_die(); // this is required to terminate immediately and return a proper response
}
Your Ajax call:
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
// note the added "my_action" to tell the server what function to fire (my be a better way to append this to your form data)
var url = form.attr('action') + "&=my_action";
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});

Sending image file to php through ajax formData

The following is my code.I am unable to send the image file to the php page.I'm using formData and i'm not clear about the concept of it.How do i send it to php page and how do i retrieve The image in php page?
JAVASCRIPT CODE
function UpdateUserDetails() {
var title = $("#title1").val();
var store = $(".search-box").val();
var category= $("#category").val();
var descp=$("#descp1").val();
var url=$("#url1").val();
var id = $("#hidden_user_id").val();
var form = $('#image1')[0];
var formData = new FormData(form);
$.post("update.php", {
id: id,
title:title,
store:store,
category:category,
descp:descp,
data:formData,
url:url
},
function (data, status) {
$("#update_user_modal").modal("hide");
readRecords();
}
);
}
update.php
<?php
include("db_connection.php");
if(isset($_POST))
{
$id = $_POST['id'];
$title=$_POST['title'];
$desc=$_POST['descp'];
$pname=$_POST['store'];
$category=$_POST['category'];
$url=$_POST['url'];
$path = $_FILES['tmp_name'];
$name = $_FILES['name'];
$size = $_FILES['size'];
$type = $_FILES['type'];
$content = file_get_contents($path);
$content = base64_encode($content);
$sql1 = "update products set title='$title',url='$url',store='$pname', product_catagory='$category', image='$content',size='$size',type='$type',descp='$desc' where id=".$id."";
if(mysql_query($sql1))
{
echo"updated";
}
else
echo "Not Updated";
}
?>
Try this:
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
It works for me.

pass data from java script to php file in codeigniter

I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps

PHP Ajax returning HTML twice

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)

Passing variables from PHP to AJAX success function

My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},

Categories

Resources