FUELPHP Ajax request without jquery - php

I have looked everywhere, I found, that FUELPHP not handle Ajax requests, native and easily, as does RubyOnRails for example.
There must be done manually through jquery, unless I'm missing something I see is this: you have to use preventDefault () for the submit event of the form to create a post, product or whatever, and use the $ function post () to send the relevant parameters, which I think is ridiculous for a framework that claims to be based on the best ideas from other frameworks.
Please tell me if I'm wrong, I like FUELPHP, and I'm thinking about choosing it as PHP framework, but I want to be clear about this.

why not you can handle ajax in fuelphp like this.
.01. create ajax request in your view or public/assets/ create javascript file,
<script> $('.login').on('click',function(){
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
alert("loading");
}, false);
return xhr;
},
url: "<?php echo \Uri::create('auth/login'); ?>",
type: "POST",
dataType: 'json'
data: {'username':$('#username').val(), 'password':$('#password').val()},
success: function (data) {
alert(data.status);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
});
</script>
.02. after that you can handle post data in classes/controller/ create auth.php and login method like this,
<?php
class Controller_Auth extends \Controller_Template {
function action_login() {
if (\Input::is_ajax()) {
if (\Input::param('username') and \Input::param('password')) {
$username = \Input::param('username');
$password = md5(\Input::param('password'));
//check password and username or anything
$msg = 'fail';
return json_encode(array('status' => $msg));
}
}
...
}
}
?>
you can handle data like this. i think you got something. and this is helpful.

Related

How to prevent page reload while bookmarking it?

I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).

How to POST to Slim framework with AJAX?

I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db.
so I have this route:
//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');
which is resolved by this controller
public function postYell($request, $response)
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user'],
]);
return $response->withRedirect($_SERVER['HTTP_REFERER']);
}
I tried something like this:
$(".postYell").submit(function(){
$.ajax(
{
url: "/yell",
type: 'POST',
data: {
"_method": 'POST',
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction
// Make sure you specify a valid callable with two ':'
$app->post('/yell', 'UserController::postYell')->setName('yell');
And then in your controller, don't redirect when it is through XHR:
public function postYell(Request $request, Response $response) : Response
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user']
]);
if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
return $response;
} else {
return $response->withRedirect($request->getHeader('Referer'));
}
}
Then follow up with the configuration in your AJAX request to send the correct data value (jQuery.ajax automatically adds the X-Requested-With: XMLHttpRequest as documented here under "headers")
$('form.postYell').submit(function (e) {
// prevent the page from submitting like normal
e.preventDefault();
$.ajax({
url: '/yell',
type: 'POST',
data: $(this).serialize(),
success: function () {
console.log('it worked!');
},
error: function () {
console.log('it failed!');
}
});
});
As per Slim3 documentation
if ($request->isXhr()) {
return $response;
}
is a great way to ascertain if the request was from a JQuery AJAX call
vote up

prestashop ajax controller call

I am trying to call controller in module using Ajax in prestashop 1.5, and I'm having hard time doing this.
I've created controller in module under the path:
$refresh_url = ($this->_path)."front/blockdiscoversellers.php";
and made instructions for button in js like:
var refresh = {
call: function() {
var $refresh = $("#manufacturer-refresh");
$refresh.click(function(e) {
refresh.ajax();
e.preventDefault();
});
},
ajax: function() {
var url = $("#manufacturer-refresh").data("url");
$.ajax({
url: url,
type: 'get',
data: {
controller : 'BlockDiscoverSellers',
ajax : true
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
};
and the body of controller looks like :
class BlockDiscoverSellers {
public function __construct()
{
die(var_dump($this->refreshManufacturers()));
}
public function refreshManufacturers()
{
$result = array("test" => "TESTER");
return Tools::jsonEncode($result);
}
}
I'm getting success in Ajax call but it looks like class and constructor are not initiated, so I am quite stuck with this problem.
It appears that prestashop when you use ajax call uses only structural type of programming. That means in ajax call there can be no class of any sort bootstrap will never initiate it even with controller parameter, and you have to die at the end of file ...

Control Not going to the Controller

i am using codeigniter. I have set a form validation via jquery and after validation the data /control is not moving on to the Controller.
Here is my jquery code
var data1 = {
username:$("#username").val(),
password:$("#password").val()
}
$.ajax({
type:'POST',
url:base_url+"site/chk_info",
data:data1,
success: function (response){
alert (response);
},
error:function (){
alert ("Sorry we are getting problems plz try again latter");
}
}); // end ajax
Here is my controller method.
public function chk_info(){
return true;
}
The problem is in jquery the controll in not entering into the success function it always getting into the error function.
chk_info() is only returning true IF PHP was listening and acting upon it.
You should be echo-ing true like this instead:
public function chk_info(){
echo 'true';
}
try this i think its url problem
$.ajax({
type:'POST',
url:'<?php echo base_url() ?>site/chk_info',
data:data1,
success: function (response){
alert (response);
},
error:function (){
alert ("Sorry we are getting problems plz try again latter");
}
});

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

Categories