I am having trouble with a program that I have written. The idea is that I click a link and the value of the link is picked up in a JavaScript variable. I then do a GET request to send the value to a PHP variable and print it out.
Here is the code:
The HTML
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id='mydiv'>
<a href='/codeigniter/index.php/hashtest/hi'>Link 1</a>
<a href='/codeigniter/index.php/hashtest/hi'>Link 2</a>
</div>
</body>
</html>
The jQuery (in a <script> tag within the above body)
$(function()
{
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(){
var text = $(this).text();
console.log(text);
//$.get("hashtest.php", {qwerty: text});
$.ajax
({
url: "/codeigniter/index.php/hashtest/hi",
data: {
qwerty : text
},
async: "false",
success: function(data){
console.log("success!");
},
error: function(jqXHR, status, error)
{
alert("Status : " + status + " error: " + error);
}
});
});
});
The PHP
class Hashtest extends CI_Controller {
function __construct() {
parent::__construct();
}
public function hi() {
$x = $this->input->get('qwerty');
print $x;
print "";
}
}
The error:
NS_ERROR_NOT_AVAILABLE: prompt aborted by user
At the moment, the JavaScript correctly gets the right link value as the console.log() line outputs the right thing for both links. But it seems the PHP is not receiving this value because nothing is being printed out. I've tried replacing the variable with a hard-coded string but it makes no difference. I can print static PHP from within the method above so I don't think it's an issue where I can't print any PHP at all.
A few points:
I used $.ajax instead of $.get just to see what error message would
appear (ideally I'd want to use $.get though). It seems it's some
sort of uncaught exception based on what I've read about the above
error message and the fact that the alert box that appears doesn't
show an error message, just a status of "error".
I don't expect any value back, the success method is just there to
see if the request is wokring or not (which it currently isn't)
I am assuming that the id of the link is unknown.
The code is all within the same class and the URL that I'm pointing
to in the AJAX request is correct (I got a HTTP 200 code back in my
browser console).
The PHP was written using the CodeIgniter framework.
You need to prevent the default action of following the link:
$(function()
{
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(e){
e.preventDefault(); // <-- THIS IS NEEDED
var text = $(this).text();
console.log(text);
//$.get("hashtest.php", {qwerty: text});
$.ajax
({
url: "/codeigniter/index.php/hashtest/hi",
data: {qwerty : text},
async: "false",
success: function(data){
console.log("success!");
},
error: function(jqXHR, status, error)
{
alert("Status : " + status + " error: " + error);
}
});
});
});
Your code is correct, but your not stopping the event when you click on the link.
Add e.preventDefault();
var mydiv = $('#mydiv');
mydiv.on('click', 'a', function(e){
e.preventDefault();
var text = $(this).text();
</code>
Related
<%= form_for(#mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
<!-- I need to check if #mymodel.match_id matches the value generated by a controller function -->
<%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>
<script type='text/javascript'>
$(function() {
$(document).on("click", "#match_submit", function(event){
$.ajax('my_controller_method', {
type: 'GET',
dataType: 'script',
data: {
mid: $("#").val(), // how do I pass #mymodel.match_id here?
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
</script>
I have a form as shown above.
How do I pass #mymodel.match_id in the ajax call above?
In my controller function, I would like to check if passed match_id is a certain value; if not, I would like to display a modal with an error message and just an Ok button. How can I achieve this?
< > a) Should I return the correct value from controller function and check the same in my javascript code above and show a javascript alert?
< > < > i) If yes, then how can I return a number from a controller function to my JavaScript invoking function?
or
< > b) would I be able to render a bootstrap modal with an Ok button in my controller itself?
UPDATE 1:
I tried this to pass match_id and id from mymodel to the ajax call but it did not work:
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
The alerts to print id and match_id print undefined in the alert messages.
UPDATE 2:
I tried this to return a number from my controller function but this doesn't seem to work either:
def evaluate_match_id
puts params[:debit_id]
puts params[:match_id]
return 1
end
the puts above turn up blank
$(document).on("click", "#match_submit", function(event){
alert ("match id changed!");
alert($("#match_form").data('id'));
alert($("#match_form").data('match_id'));
$.ajax('cpl_evaluate_match_id', {
type: 'GET',
dataType: 'script',
data: {
debit_id: $("#match_form").data('id'),
match_id: $("#match_form").data('match_id')
},
success: function(result){
if(result){ // yes or no? 1 or 0, it's the return coming from your controller
alert('true');
alert(result);
}
else{
alert('error');
alert(result);
}
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
The value of result in the success: block in the JavaScript code above comes up as undefined (my controller function blindly returns the number 1 which I was expecting to be the value of result here). So the if(result) condition fails and the else block gets called instead.
You can use the attr to get the value element in jquery. something like this
$('#match_form').attr('id')
some ideas coming from PHP, no exp from ruby-on-rails.
can you pass the #mymodel.match_id in an 'attribute' of your html?
<form data-match_id='#mymodel.match_id'...
or
<form custom_name='#mymodel.match_id' ...
or similar. then, you can use that on ajax to to call the form's data
via Jquery:
$("#match_form").data('match_id')
or
$("#match_form").attr('custom_name')
on your second question, you should have a success function on your ajax, that will return the contents recieved from your controller.
$.ajax({url: "my_controller_method",
data: {
mid: $("#match_form").data('match_id'),
}
success: function(result){
if(result) // yes or no? 1 or 0, it's the return coming from your controller
alert('true');
else
alert('error');
}});
from your controller, you should display the return value instead of just return. (like when you accessed your controller, it will be a white screen with just the return value like 1 or 0)
Lastly, yes you can, or better if you can create a predefined messages for modal ready on your view, and just invoke which message will show on modal.
UPDATE 1:
to properly get the desired attribute on the form, first you need to get the form element properly, on either adding ID or any other method.
<form id="match_form" data-match_id="your_value_here">
from here, you can get the data attribrute 'match_id' using this jquery syntax
var match_id = $("#match_form").data('match_id');
console.log(match_id);
you can try this code on your browser's console (F12 on modern browsers Chrome/Firefox), and it should output your_value_here
on Update 2, you might need to output it, try displaying the number '1' on your controller, then try the ajax, the result will be the number '1'.
hope this answers your question.
Unable to pass a string from a php page to another page's js function.
It is to display message after checked the adding item is existing in an array or not. I've tried either adding quotes or not in the alert statement
1. with quotes in alert statement, javascript didn't convert the statement but just display it directly.
2. without quotes in alert statement, Chrome says it's an error if without quotes.
add_product.php (js function):
function add_to_cart(){
jQuery('#modal_errors').html("");
var error='';
var available =$("#size option:selected").data("available");
var quantity = jQuery('#quantityInput').val();
{document.getElementById("available").value = available;
var data = jQuery('#add_product_form').serialize();
jQuery.ajax({
url : 'cart.php',
method : 'post',
data : data,
success: function(){
alert("<?php echo $respMsg; ?>");
location.reload();},
error : function(){alert("something wrong");}
});
return;
}
cart.php:
if ($duplicate==false){
$respMsg="The item is in cart now.";
} else {
$respMsg="You have added the item twice.";
}
I expect a js msgbox popup to show either one of the php messages, but the actual output is either telling syntax error or displays the code string.
If you want to print your response, then you can't say alert("<?php echo $respMsg; ?>");
What you have to do is actually get the data in the callback and alert that data.
success: function(data){
alert(data);
location.reload();
},
First, you need to use a function into cart.php returning the $respMsg result, then use data response from de jQuery.ajax function to alert the message:
jQuery.ajax({
url : 'cart.php',
method : 'post',
data : data,
success: function(data){
alert("Message: " + data);
location.reload();
},
error : function(){
alert("something wrong");
}
});
More information about data response and success response, into jQuery manual
EDIT:
Also you need to delete the curly brace here:
{document.getElementById("available").value = available;
It may cause JS syntax error.
I am completely stuck since two hours and definitely need your help. Disclaimer: I am not a coder - just a guy who is trying to mock up an idea.
So my page is actually working fine but I thought about moving content from a modal-popup to an actual sub-page. Meaning: If a user clicks on a button, some data points from the current page are being collected and passed to another view which shall be rendered using the data points as input.
EDIT: For clarification: The button is on /results.php where data is generated dynamically. The method should take some data points from here and generate a new view and render it at /buy.php or maybe at /buy/custom.php
My thoughts:
Normal redirect without parameters: Internal Link
Updating page-content without redirect but with parameters: Ajax
So combining my thoughts -> use ajax and return a new fresh view.
What I tried:
$("body").on("click", ".fa-shopping-cart", function() {
var $para1 = $(this).attr("data1");
var $para2 = $(this).attr("data2");
var $para3 = $(this).attr("data3");
var $para4 = $(this).attr("data4");
$.ajax({
url: "buy",
data: {
a: $para1,
b: $para2,
c: $para3,
d: $para4
},
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
type: "post",
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});});
Routing:
Route::post('/buy', 'PageRouting#buy');
Controller:
public function buy()
{
$para1= $_POST['a'];
$para2 = $_POST['b'];
$para3 = $_POST['c'];
$para4 = $_POST['d'];
// some magic to output $data
return view('pages.buy', compact("data"));
}
buy.blade.php exists and displays $data with help of an foreach-loop.
So, when I first clicked the button the obvious happend:
The view ('pages.buy') is logged / displayed in my console in plain html and not rendered in the browser.
Now I am sitting here since two hours and I have no clue whatsoever. I read some blog post saying that you cannot redirect within an ajax-call. Unfortunately the post did not gave any hint on how to do it instead.
Can someone help me?
All best
If you want to replace entire document with the response you have to use document.write but it's not the best thing to do. Why don't you use normal form submit if you need to return a view?
success: function(response){
document.write(response);
},
P.S. if you want also to change the url, use the history manipulation functions.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
in your buy method -
public function buy ()
{
....//some stuff to get $data
$html = view('pages.buy', compact("data"))->render();
return response()->json([
'success' => true,
'html' => $html
])
}
in your ajax success function
success: function(response){
if(response.success)
{
$('#elementId').html(reponse.html) // or whatever you need
}
},
I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}
Folks I am working on the Editinplace functionality and while running I get this error on the chrome console Uncaught SyntaxError: Unexpected token < I am doing this with the node.js snippet as follows
case '/':
res.writeHead(302,{'location':'http://localhost/editinplace/index.html'});
res.end();
break;
case '/save':
console.log("called");
console.log("Inside called");
res.write('_testcb(\'{"message": "Hello world!"}\')');
res.writeHead(302,{'location':'http://localhost/editinplace/save.html'});
res.end();
break;
The code for the index.html is as follows
<script type="text/javascript">
$(document).ready(function(){
setClickable();
});
function setClickable() {
$('#editInPlace').click(function() {
var textarea = '<div><textarea rows="10" cols="60">'+$(this).html()+'</textarea>';
var button = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL"class="cancelButton" /></div></div>';
var revert = $(this).html();
$(this).after(textarea+button).remove();
$('.saveButton').click(function(){saveChanges(this, false);});
$('.cancelButton').click(function(){saveChanges(this, revert);});
})
.mouseover(function() {
$(this).addClass("editable");
})
.mouseout(function() {
$(this).removeClass("editable");
});
};//end of function setClickable
function saveChanges(obj, cancel) {
if(!cancel) {
var t = $(obj).parent().siblings(0).val();
var data=t;
$.ajax({
url: 'http://localhost:9090/save',
type:"GET",
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: true,
timeout: 1000,
data:{data:JSON.stringify(data)},
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}
else {
var t = cancel;
}
$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove() ;
}
</script>
</head>
<body>
<div id="editInPlace">Nilesh</div>
</body>
The save.html is a simple text enclosed in <pre>tags.And the error is shown to be in save.html line 1.Thankx for your efforts.
OK, so here's what happens:
browser loads index.html
user edits the field and clicks save
saveChanges makes an AJAX GET request to /save
Your server code sends an HTTP response with a 302 status code and a jsonp body
I think that the browser is transparently handling the 302 status code and ignoring the body
Thus your jquery code is expecting your javascript from the response body of /save, but it's really getting the HTML from /save.html. That's where the syntax error happens, when jquery tries to evaluate that HTML as javascript because you told it the dataType was jsonp.
See also this question about browsers handling redirects automatically
The solution is you need to send a 200 response code so jquery can do the jsonp thing and then after that you can change window.location to /save.html if you like.