sending form data to server by ajax - php

I am new with ajax and want to make a to-do-list.
for add-form submit method() ,I have an if-else .the else works and give me alert in its situation but if doesnt work I think it's about my post method.
by the way it's my jquery code :
$('#add_task').submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var title = $('#task_title').val();
if(title){
//ajax post the form
$.post("/add", {title: title}).done(function(data) {
$('#add_task').hide("slow");
$("#task_list").append(data);
});
}
else{
alert("Please give a title to task");
}
});
and when I click on my add btn the console output shows me a 404 not found error and refer to this line of my jquery main file that I download from http://code.jquery.com/jquery-latest.min.js: it is :
f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&& (e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();
it's my controller :
public function postAdd() {
if(Request::ajax()){
$todo = new Todo();
$todo->title = Input::get("title");
$todo->save();
$last_todo = $todo->id;
$todos = Todo::whereId($last_todo)->get();
return View::make("ajaxData")
->with("todos", $todos);
}
}
and my route:
Route::controller('/', 'TodoController');
thanks for time

Change "submit button" to simple button and change as below.
$('#add_task').click(function() {
var titleField = $('#task_title');
if(titleField.length > 0){
$.post("/add", {title: titleField.val()}).done(function(data) {
$('#add_task').hide();
$("#task_list").append(data);
});
} else {
alert("Please give a title to task");
}
return false;
});

I think you have an problem with routing in Laravel. This routing should work:
Route::post('add/',array('uses' => 'TodoController#add'));

404 HTTP Status errors in AJAX are only related to the URL you are sending your data. Change /add with something your backend can handle, like a simple PHP file, because /add means you need some htaccess/nginx rewrites to be done.
Anyway, it's a simple tutorial, and I'll downvote you for copying code claiming to be yours from: packtpub
You should do a simple ajax request like this:
$.ajax({ url : 'ajax.php', data: {title:title}, type: 'POST', success:
function(response) {
// exec success code
}
});
Never do internet tutorials if you have no idea about programming because you'll never get them to work. It's just a simple php file that you need to code, and change it's url from that tutorial in your Route:: controller, though, that tutorial is way too complex for a to-do list.

I fixed it just by changing:
$.post("/add", {title: title})
to:
$.post("http://localhost/Blueprints/to-doListWithAjax/public/index.php/add", {title: title})
it didnt found localhost://add so I gave it complete addrerss
.
THANKS ALL FOR REPLIES

Related

Laravel 5.2 return with errors - how to tell which form is submitted

I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!

Parameters of ajax request don't change

I' m using cms ModX and want to send Ajax request to server using post method. The problem is that the post data of the second, the third and so one requests doesn't change and remains the same as in the first request.
To clarify the situation I provide the following example.
The javascript is the following:
var reqCount = 0;
$(document).ready(function () {
$(window).scroll(function() {
var dataToPost = {'reqCount' :reqCount};
$.ajax({
url: 'http://example.com/ajaxTest',
method: 'POST',
data: dataToPost,
dataType:"json",
success: function(data){
ajaxCountFromServer = data['ajaxCount'];
reqCount=reqCount+1;
}
});
}
}
Also I created resource with address http://example.com/ajaxTest in Modx with the code, running the snippet:
[[getAJAX]]
getAJAX snippet is the following:
<?php
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$reqCount = $_REQUEST['reqCount'];
$json_obj = array("ajaxCount" =>$reqCount);
return json_encode($json_obj);
}
?>
So, after the first scroll reqCount=0, it's passed to server and after the server responses(success callback) ajaxCountFromServer=0 and reqCount=1. There all works well.
However, after the second scroll reqCount=1 and after the server response ajaxCountFromServer=0,but it should be 1.
How to fix it?
The solution is quite simple. In the page customizing of the resource http://example.com/ajaxTest, where snippet getAJAX is called, I just unchecked the checkbox "Cacheable".
The correct way to do it is
[[!getAJAX]]
The snippet is not cached now

Return a view via ajax in laravel

I want to display a view to the user whenever user clicks on a button using ajax.
This is my code.
// BASE = localhost/project/public/
$('#button').click(function() {
$.ajax({
url: BASE + "user/settings",
type: 'GET'
})
.done(function( data ) {
console.log( data );
});
});
And my routes.php
Route::get('user/settings', 'UserController#getSettings');
And UserController.php
public function getSettings(){
return View::make('user.settings');
}
But output is this error:
{"error":{"type":"ErrorException","message":"Undefined offset: 0","file":"H:\\dev \\xampp\\htdocs\\lchat\\vendor\\laravel\\framework\\src\\Illuminate\\Support \\Collection.php","line":470}}
EDIT: error was in view. I fixed it.
Problem2: The page which is loading via ajax, itself contains another ajax post request. but it's not sending data via ajax anymore. refreshes the page to send data.
The jquery code:
$('#settings :submit').click(function(e){
e.preventDefault();
$.post(BASE + 'settings/save', {
'userName' : $('#userName').val()
}, function(data) {
return 'OK';
});
});
Problem solved: I used .on to bind event:
$(document).on('click', '#settings :submit', function(e){ ... } );
It's working...
Thank everyone.
Well, for starters, you have an error in your view. The error you're getting is in reference to an array you're trying to access that doesn't actually have the key you're trying to use ($arr[0]).
Once you fix the errors with the view itself, it should work fine. The JavaScript will get the data as HTML, and you can just insert it into wherever you want it to show up.
Use string method before view file
return (String) view('Company.allUserAjax');

CodeIgniter AJAX: POST not working, GET works fine

Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!

PHP and JQuery Button trigger not working

Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.

Categories