Pass string from php to js function - javascript

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.

Related

How do I return a variable from Javascript to PHP for using it for a query "onchange"?

JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});

Passing data with POST with AJAX

I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.

JQuery AJAX function not receiving PHP-returned text

I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.

Post return values with AJAX?

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
}

Sends AJAX, PHP query and return JSON and AJAX do not understand with "dataType: 'json'"

I'm new here and jQuery development, I have a question, Why can not I use the dataType:'json' nor $.parseJSON to handle a return of a query from PHP to AJAX (jQuery).
reader.js
$(function(){
//Modal form which encapsulates the loading of information occurs
var modal = $('.modal');
//Encapsulates the existing list or the list elements, each element has an "edit" button
var lista = $('.lista');
lista.on('click','.actionedit',function(){
var id = $(this).attr('href');
var li = lista.find('li[class*="j_'+id+'"]');
$.ajax({
url: 'php/controller.php',
data: 'acao=consulta&editid='+id,
type: 'POST',
//contentType: 'application/json; charset=utf-8;',
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert('Erro: "'+ xhr.status + '"\nMensagem: " ' + thrownError +'"');
},
beforeSend: function(){
li.css("background","#0F6") },
success: function( carga ){
//alert( carga );
alert( carga.nome );
//modal.fadeIn("slow");
//modal.find('form span[class="filebar"]').text(carga.file);
//modal.find('form input[name="titulo"]').val(carga.title);
//modal.find('form textarea').append(carga.description;
},
complete: function(){ loader.fadeOut("slow"); },
});
return false;
});
});
controller.php
<?php
require_once("conexao.php");
switch($_POST['acao']){
case 'consulta':
//Validates query, that returns a json string...
$editid = $_POST['editid'];
$qr = "SELECT * FROM mod6_uploads WHERE id = '$editid'";
$ex = mysql_query($qr);
$st = mysql_fetch_array($ex);
//Return array in json format string for testing...
$u['file'] = 'File';
$u['title'] = 'File title';
$u['description'] = 'File Description';
echo json_encode($u);
break;
default:
echo 'Error querying';
}
Thus, the alert returns me the following message:
Error: "200"
Message: "SyntaxError: JSON.parse: unexpected character"
If I comment the dataType: "json", it returns me the following warning: undefined
And if I change the alert to "alert (carga.nome)" to "alert (load)", it returns me the following:
{"name": "File", "title": "File Title", "description": "File Description"}
Also, as I said earlier, if I use the $.ParseJSON or JSON.parse not have any return, or the error or the success.
Anyone out there have come across something like this?
If anyone could help me I would be very grateful!
I'd change this line:
data: 'acao=consulta&editid='+id,
By this:
data: {acao: 'consulta', editid: id},
As your id comes from an href, it would be better if it's automatically escaped.
Also, instead of this:
echo 'Error querying';
something like:
echo json_encode(array('Error querying'));
so it doesn't give JSON parse errors (return as javascript array of errors).
Also, ensure your mod6_uploads table has a nome field.
I see the rest is fine.
Cheers
PS: I suggest you to use a dev tool for debugging. One very easy is chrome's, just press F12, click the network tab and then run your ajax request.
If you use dataType:'json', success callback will only trigger if the server response is a valid JSON.
So if error callback is triggering, your response is 'populated' with extra data that makes JSON invalid.
In this case try to comment dataType:'json' and write in your success callback:
alert(carga)
or
console.log(carga)
This will output the server response and you will be able to see what's wrong with it.
Also if you deside to use JSON, try to use JSON everywhere in that file and avoid such code:
echo 'Error querying';
Otherwise you may get unexpected result

Categories

Resources