I'm head below water on this, using Laravel I have a search page of which ajax calls a url and updates the html for filter by the way of html links which contain get vars ($(this).attr('href'); which contains ?var=test sent via ajax) to return filtered results. As ajax this doesn't update the url I'm using history.replaceState to update that.
Now here's my issue, the links which be shown as buttons (using BS) - so my link href will include the ?thisbuttonvar=whatever BUT if that get var already exists then the link href should not include ?thisbuttonvar=whatever it should remove it
I have created a function to try to handle this as follows (sorry I can't get it to paste properly):
function href_append_query($param) {
parse_str($_SERVER["QUERY_STRING"], $query_array);
if (array_key_exists(current(array_keys($param)), $query_array))
{
$key = current(array_keys($param));
if ($param[$key] == $query_array[$key])
{
unset($query_array[$key]);
}
}
else
{
$query_array = $query_array + $param;
}
$query = http_build_query($query_array);
return '?' . $query; }
The issue with this is when I do a
#foreach ($category->subCategories()->get() as $sub_category)
<li><a class="search-filter" href=<?=href_append_query(['sub_category' => $sub_category->sub_category_url])?>>{!! $sub_category->sub_category !!}</a></li>
It works for the first link, but all the rest of my href's come back the same (as the first one that enters the function)
Can anyone assist in getting this function to work so the foreach link has the appropriate href OR an entirely different "easier" way all together :)
My jQuery if it helps paint a better picture
$(document).on("click", '.search-filter', function(e) {
e.preventDefault();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Searching,</b> please wait...<br />');
query = $(this).attr('href');
history.replaceState(null, null, query);
$.ajax({
type: "GET",
url : query,
success : function(data, status){
$('#job-results').html(data);
$('#spinner-modal').modal('hide');
},
error : function(status){
console.log(status);
},
});
});
Related
I am working on the filter part in search page but the issue is In the main search page all the result looped from the controller, and Now I am using jquery for the filter process, but things are confusing. How to do this in a right way?
So here is the process :
Step 1 : user search something Like "support" and then system go to the searchController file and give the result
return view('/search')->with(["documents" => $results, "filters" => $filters]);
Here $filter indicates the category filters; Like this
Then When User click on any category then it will filter the result but now the issue is I am using jquery and now things getting weird. Can somebody help me on this.
JS Code :
$(document).on("click", ".category_filter1",function() {
var test = new Array();
$("input[name='category_filter']:checked").each(function() {
test.push($(this).val());
});
showValue(test);
});
function showValue(data){
$.ajax({
'url': 'search/filter/'+(data.length > 0 ? data : "all"),
'type': 'GET',
success: function(response){ // What to do if we succeed
if(response.data == "success")
document.getElementById('result').innerHTML = response.categories;
},
error: function(response){
// alert('Error');
}
});
}
and The Controller from where all result came from :
public function filter($data){
$t_data = explode(',' , $data);
$filters = $this->load_filters();
if(count($t_data)>0 && $t_data[0]!== "all"){
$results = DB::table('documents')
->whereIn('category', $t_data)
->paginate(5);
}else{
$results = Document::paginate(5);
}
return redirect('/search')->with(["documents" => $results, "filters" => $filters]); // This part is really confusing
}
So the flow will be like this :
Summarizing from as discussed in comments,
In order to call the controller without refreshing the page you need to use ajax, (use jquery or any other frontend framework). Return your response as json,
return response()->json($your_return_array);
For images store it in public folder, such as public/images/your-image.png.
Then call it using url() method in your blade.
<img src="{{url('/images/your-image.png')}}" alt="Image"/>
I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.
What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:
Here's my PHP:
function tweet($message,$image) {
require_once('codebird.php');
\Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$reply = $cb->media_upload(array(
'media' => $image
));
$mediaID = $reply->media_id_string;
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
$reply = $cb->statuses_update($params);
}
tweet("Tweet tweet","assets/tweet.jpg");
And here's my Javascript/HTML:
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<button class="download-share" onclick="postTweet()">Download and Share</button>
In the button click, you need another function that open the popup along with a tweet button.
Add the click event listener as postTweet to the new tweet button.
I created a sample snippet. Check it below.
To show the real time preview, you need to add the keyup event listener to the textarea which should copy it's value and add it as the innerHTML of the preview pane.
function openTweet(){
document.getElementsByClassName("preview")[0].style.display="";
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
document.getElementById("tweet").addEventListener("keyup",
function(){
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
});
document.getElementsByClassName("download-share")[0].style.display="none";
}
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<div style="display:none;" class="preview"><textarea id="tweet"> </textarea><div id="tweetPr"></div><button onclick="postTweet();">Tweet</button></div>
<button class="download-share" onclick="openTweet()">Download and Share</button>
First things first, you(codebird) are using the twitter API to post to twitter, which makes use of the statuses/update endpoint in the API. This call is a server to server call, ie from the server where your files are hosted to the twitter server.
https://dev.twitter.com/rest/reference/post/statuses/update
There are 2 possibilities i see for you to accomplish what you have in mind
-first would be to use twitters web intent system with which you can send the tweet as a query string which would bring up the popup provided you have included the twitter js files
https://dev.twitter.com/web/tweet-button/web-intent
-second if thats not really your style then you could try something like what #ceejayoz mentioned making a new window created by you recreating the necessary inputs as shown in the picture and follow the same procedure you have now
Now to your question, Since you have an image the web intent option will not work, but if its a link with an image( twitter cards ) then i think the twitter bots should be able to read through the page and show you a preview in the popup provided you have the right meta tags on the linked page
Try use the function window.open
https://www.w3schools.com/jsref/met_win_open.asp
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function() {
success = true
}
});
if(success)
{
window.open('tweet.php', "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400")
}
}
Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
an answer from a previously question I asked here has posed another problem for me, as I am learning more and more about async calls I still can not figure out how to accomplish (as the previous answer showed me) a list which allows me to store and use data from a selected list item.
$('#home').live('pageshow', function(){
// creating object
var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
});
with js fiddle http://jsfiddle.net/amEge/3/
This code works excellent and will allow me to accomplish what I want but fist I need to populate the customerList from a ajax call. But from the "success" function I cannot seem to get the code to work.
$.post(postTo,{id:idVar} , function(data) {
customerList = data;
//alert(customerList);
})
When I move the code inside the ajax function it dose not work. I was just wondering if anyone could help me and maybe show me how to deal with this from asynchronous calls ?
Many Thanks
You need to change your page as below.
// I assume this is your dot net web service url
var webServiceURL = 'customer.asmx/GetCustomer';
// here home is your page's ID
$('#home').live('pageshow', function(){
getCustomerList();
});
function getCustomerList(){
param=JSON.strigify({id:'2'});
callWebService(param, webServiceURL, onGetCustListSuccess, onGetCustListFailed)
}
function onGetCustListFailed(){
alert("service request failed");
}
function onGetCustListSuccess(data, status){
// creating object
// replace previous line with below
// var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
var customerList = JSON.parse(data.d);
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
}
function callWebService(param,url,successFunc,errorFunc){
if(errorFunc=='undefined'){
errorFunc=OnDataError;
}
$.ajax({
type: "POST",
url: url,
data: param,
contentType:"application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc,
beforeSend:function(){$.mobile.loading( 'show' );},
complete:function(){$.mobile.loading( 'hide');}
});
}
Hope this would help you out. If you have problems asks me here.
Correct me if I'm wrong, but I'll hazard a guess that your "live" code looks something like this:
$('#home').live('pageshow', function(){
// creating object
var customerList;
$.post(postTo, {id:idVar}, function(data) {
customerList = data;
//alert(customerList);
});
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// and all the rest...
If so, then your problem is that the code that's depending on your customerList variable being filled in ("all the rest...") runs immediately, rather than waiting for the response from your HTTP request to come back from the Web server. That $.post() doesn't wait around (or "block," as we say in the computer software programming game) while the HTTP transaction makes its way to the Web server and back. Instead, the rest of your code runs immediately, and then later, when that response comes back to the browser, the JavaScript engine dutifully executes your success function (or "closure," as we hm hmm hmmmm).
So what you'll want to do is put all this other code (the stuff that's dependent on customerList) into a separate function, then call that function from within your success closure. You won't even need your customerList variable then; you can just pass the new response data as an argument to your new function.