Passing value using Ajax to my PHP - laravel-4

My ajax code didn't work, i am trying to pass the colorit value from my script to my controller(php), but the ajax didnt work. the alert box with out put 'success!' didn't pop out and also the alert(colorit). but if i comment the ajax code, the alert(colorit) pops. is there any wrong in my ajax code? please help. tnx. sorry im new to this.
script
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: {'colorit':colorit},
success:function(data){
alert('success!');
}
});
});
html
<select id="colorselector_1" class="colorselector_1">
<option value="#A0522D" data-color="#A0522D">sienna</option>
<option value="#CD5C5C" data-color="#CD5C5C" selected="selected">indianred</option>
</select>
route
Route::get('addItemColor','CakeController#addItemColor');
controller
public function addItemColor(){
.......}

May I just suggest something?
First of all, this is why you have vars like "error" in place. So the first thing you should do is change your code accordingly:
$( ".colorselector_1" ).change(function() {
var colorit = document.getElementById("colorselector_1").value;
alert(colorit);
$.ajax({
url: '/addItemColor',
type: 'GET',
data: 'colorit':colorit,
success:function(data){
alert('success!')},
error:function(data){
console.log(data);
alert('error');
}
});
});
Another thing to remember is that you have the Network panel in developer tools where you can see all of the calls that were made and whether they had successful responses or not, such as in Chrome when you go to More tools -> Developer tools. These two will help you find the answer of "whether there is something" for yourself, like if there's a wrong URL or something.

Make sure you point to the right url in your $.ajax function.

Related

wordpress: AJAX: 400 bad request with admin-ajax.php

I have searched and red a lot of this issue.
However, I do not know, why this few simple lines produce a
"POST http://example.com/wp-admin/admin-ajax.php 400 (Bad Request)"
What I basically want (later on) is: If you press a button, a counter will be updated and write a value into my mySQL. But before I can think about a mySQL query, I stumble over this 400 Error.
What I have (really basic, no validations, etc.):
html
<button id="vote" type="button">Click Me</button>
jQuery
<script type="text/javascript">
//var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; // get ajaxurl
jQuery('#vote').click(function() {
jQuery.ajax({
url: 'http://example.com/wp-admin/admin-ajax.php', //just hard coded to see if I have a problem with my ajaxurl
type : 'post',
data: {
'action' : 'ibvote'
},
success: function( data) {
alert( data);}
});
});
</script>
php
add_action("wp_ajax_ibvote", "ibvote");
add_action("wp_ajax_nopriv_ibvote", "ibvote");
function ibvote(){
echo "DONE";
wp_die();
}
Any help would be great.
Thank you.
Thank you #all.
I use the "Code Snippets" plugin and I activated "only run on site frontend". Today with more coffee I switched to run snippet everywhere and: voila! Working like a charm.
#Bhautik: Again thank you for your time and answer :)

CakePHP Friendsofcake search ajax results

sorry if I am missing something simple here. I am using CakePHP 3 and the Friendsofcake Search plug-in and trying to load my results with AJAX. I am not sure what to set for the URL - my understanding is the FormHelper url and the AJAX url must match for SecurityComponent. However even with that disabled I cannot get the form to submit. Any help is appreciated. The plugin is working fine otherwise and I can submit other forms using AJAX just fine - I suspect I am missing something here (or it's not possible - I am a beginning programmer)
<?php
$formUrl='//'.$_SERVER['HTTP_HOST'].Router::url(['controller'=>'Treasures','action'=>'frontIndex']);
echo $this->Form->create('Treasure',['id'=>'myForm','url'=>$formUrl]);
echo $this->Form->input('q');
... (Form submit, end, etc.)
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"POST",
url:"<?=$formUrl?>"
});
</script>
<div class="ajax-result"></div>
Can someone tell me what I should be setting for the $formUrl? Currently the Controller action I am using this on successfully filters data with the search plugin and I have specialized the view to return AJAX results when requested - but there is obviously something else going on I am missing.
This works if I leave the URL blank and use GET instead of POST - should've thought of that sooner.
echo $this->Form->create('Treasure',['id'=>'myForm']);
...
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"GET"
});
</script>
Works as expected. Hope this helps someone!

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

Using form data to dynamically construct url using ajax

I have the following ajax code that takes in 3 variables and passes them to a php file, and this is all fine and dandy. I want to do a redirect using the value stored in one of these variables. I figured I could just do window.location.href = within the success in the ajax call, but for some reason, it doesn't seem to respond to the click, and simply does nothing.
Here is the ajax function, hope y'all can help!
$("#findItem").click(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.ajax({
type: 'get',
url: 'http://plato.cs.virginia.edu/~aam3xd/cabbage/closestBuildingWeb.php',
data: {
foodItemId: $('#foodItem').val(),
sentLongitude: position.coords.longitude,
sentLatitude: position.coords.latitude
},
success: function(data){
//$('#answer').html(data);
//the following line doesn't seem to be executing....
window.location.href = foodItemId+"/"+sentLatitude+"/"+sentLongitude;
}
});
});
I think you should use your url into that window.location
window.location.href = "www.example.com/"+foodItemId+"/"+sentLatitude+"/"+sentLongitude;

Jquery ajax call not working with relative and absolute urls

This is the code, I don't get any alerts whether, error or success. That ajax call returns a json map, and that map is populated in the select options dynamically.
<body>
<script>
$(document).ready(function() {
var selectValues;
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/",
data: APP_002,
async: false,
success: function(data) {
selectValues = data;
alert("Details saved successfully!!!");
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
</script>
<div>
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
</div>
<div>
<select class="model"></select>
<a id="download-link"> Download </a>
</div>
</body>
Why it can't it send the request to the server, I'm using logs in the server side. No request there.
The page url : http://59.163.254.24:4287/wap/download/
Ajex request Url : http://59.163.254.24:4287/wap/retrieve/hanset/data/
I used both /wap/retrieve/hanset/data/ and http://myhost.com/wap/retrieve/hanset/data/ as the parameter for url in the ajax method, both are not working.
Code on your server (link you provided) is not the same as the one you have posted in your question. Code there has error: SCRIPT1009: Expected '}' meaning that you are missing } from your javascript.
Line:
// bonus: how to access the download link
comments out the rest of javascript as you have not switched it to a new row. This commented js includes some code and closing braces. You should add newline after this comment.
This is why you have javascript error and your browser never calls server.
And your parameter should be 'APP_002', not just APP_002
When you fix this, you will probably be able to make request, but if not, we can check for any other errors when you do this.
I think the problem is you're passing APP_002 using the data parameter, which is equivalent in this case to the querystring. Looking your comments on the OP, you need to actually pass it in directly in the URL so that the request is routed correctly on the server, like this:
$.ajax({
type: "GET",
url: "http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002",
async: false,
// rest of your code...
});
Example:
http://59.163.254.24:4287/wap/retrieve/hanset/data/?APP_002 -> page not found
http://59.163.254.24:4287/wap/retrieve/hanset/data/APP_002 -> JSON response
Actually, there is not a problem with the code you provided.
Here is jsfiddle:
http://jsfiddle.net/fHtcc/1/
However, there must be an issue with APP_002 (if it is not something defined) or Jquery is not included to page.

Resources