Why is my JQuery AJAX function not working properly? - javascript

Trying to insert a car image from one of my databases into my webpage
get_new_car_pictures:
$make = $_REQUEST['make'];
$model = $_REQUEST['model'];
$query = "SELECT * FROM database_new WHERE make = $make AND model = $model";
$car = $db->get_row($query);
$img = $car['img_url'];
echo "<img src=".$img." />";
ajax function:
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: "model=" + params.model + "&make=" + params.make,
success: function(data){
$("#car-image".html(data));
}
}
});
car-image is the div where I want the image to appear
I have tried to follow Ajax tutuorials online but for whatever reason, this is not working...

use concatenation on query and varchar has to be in single quotation
$query = "SELECT * FROM database_new WHERE make = '".$make."' AND model = '".$model."'";
and also fix js
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: {'model':params.model, 'make': params.make},
success: function(data){
$("#car-image").html(data);
}
}
});

For one thing, you've misplaced a parenthesis:
$("#car-image".html(data));
should be
$("#car-image").html(data);

Try adding an error callback to take a closer look at what's going on.
jQuery Ajax error handling, show custom exception messages
Also, I'd recommend setting the image's src attribute with the response instead of setting its HTML.
Let me know what the error says and we can go from there.

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!");
}
});

JSON encode is not working properly in ajax function

I built an event to change product name that mix up with ajax and json encode
<div class="new-product-name"></div>
<div class="new-product-num"></div>
Then the script is
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
$(".new-product-num").html(data.b);
});
});
});
in fetch-product.php
$query = "SELECT * FROM `product_details` WHERE id='". $_POST['keyword']."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
Here product details is fetching correctly , even in $(".new-product-name").html(msg); it showing '{"a":"Product1", "b":"22"}', it is entering in to $.getJSON("fetch-product.php", function(data) { }
But data.a , data.b showing null.
why is data.a , data.b null ?I am spending too much time . Please help to solve this error .
I see no reason to make 2 calls to the PHP script.
If you add the dataType:json parameter jQuery will expect a JSONString back from the PHP and msg will be automatically converted to a javascript object.
$(function(){
$.ajax({
method: "POST",
dataType: "json", // new param
url: "fetch-product.php",
data: {keyword: 12}
})
.done(function(msg){
if ( msg.status == 1 ) {
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
} else {
$(".new-product-name").html(msg.info);
}
});
});
The other issue with your call to $.getJSON("fetch-product.php",..... was that this would issue a GET request, and therefore fill the $_GET array with any parameters. Your PHP code is not looking for parameters passed in the $_GET array!
Your PHP code as it was, was vulnerable to SQL Injection, so I have amended it to use Parameterised & Prepared statements.
You also need to consider the possibility that nothing is found by your query and return something to let the javascript know about that.
$query = "SELECT * FROM `product_details` WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_POST['keyword']);
$result = $stmt->execute();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo json_encode(array( 'status'=> 1,
'a'=>$row["p_name"],
'b'=>$row["num"]);
} else {
echo json_encode(array('status'=>0,
'info'=>'No data found');
}
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
makes a POST to fetch-product and writes the value of msg into the product name element. Except that it should probably be msg.a since your code returns an object with the data inside the a property. You also need to set the dataType:json option so that jQuery knows the returned value from the server is an object and not a string.
However, you then make another request to the same URL, but using a GET request and without passing any parameters. Since your PHP tries to read values from POST requests only, this causes your query to return nothing, and thus your output of $name is empty. You then overwrite your product name element with this empty value.
Why you are making this second request to the same resource, but with the wrong settings, is a complete mystery. It is totally unnecessary. This code should do what you need in a single request:
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12},
dataType: "json"
}).done(function(msg){
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
});
});
P.S. Your SQL is incredibly vulnerable to SQL Injection attacks. You should switch to using parameterised queries and prepared statements. Otherwise someone could send a malicious value in the "keyword" parameter and steal, destroy or otherwise corrupt your data. See http://bobby-tables.com/ for a humorous but very clear example of this sort of problem. Both the PDO and mysqli libraries for PHP provide easy ways to create prepared statements, and there are hundreds of examples of the syntax available online for you to follow.
As #Sirko already said, you are sending two requests:
$(function(){
$.ajax({ // First request, as planned
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
// This will send an additional GET request to fetch-product.php without any parameters
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
});
});
});
Remove the second request or replace the first with the second, if GET method is applicable it should work fine. Because the second request returns null the html of everything with the class .new-product-name will be empty ("").
If You want to make two php calls , then try This:
fetch-product.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$keyword = $_GET['keyword'];
}else{
$keyword = $_POST['keyword'];
}
$query = "SELECT * FROM `product_details` WHERE id='". $keyword."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
?>
Then the Script is
$(function(){
var data = {keyword: 12};
$.ajax({
method: "POST",
url: "fetch-product.php",
data: data
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php",{keyword: 12}).done(function(data1) {
$(".new-product-name").html(data1.a);
});
});
});

Using ajax request variable to populate a dropdown

My limits in javascript are preventing me to solve a problem I am facing at present.
I am doing an ajax request for retrieving some database values.
I receive the data I need alright, but
I am unable to use that value "cityareax" to either populate an existing dropdown or to create a new one.
Here is the code:
<script type="text/javascript">
function autocomp_city() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $("#city_namex").val();
if (keyword.length >= min_length) {
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
} else {
$("#city_list").hide();
}
}
// set_item : this function will be executed when we select an item - a city name
function set_item(cityname, statename, cityarea) {
$("#city_namex").val(cityname);
$("#statex").val(statename);
// hide proposition list
$("#city_list").hide();
$("#cityareax").val(cityarea);
}
</script>
Can somebody help me?
tx Roberto
and thanks for your interest. I found my own solution. The main problem was timing.
I was trying to use data that I received from Ajax in a script that was inactive, having been executed onload.
When I moved my variable processing code in the function that was working AFTER THE AJAX REQUEST, everything went fine. It was about a week that I was running in circles trying to find a solution ...
Roberto
Are you missing a return type?
$.ajax({
url: "city_ajax_refresh.php",
type: "POST",
data: {keyword:keyword},
datatype: "html",
success:function(data){
$("#city_list").show();
$("#city_list").html(data);
}
});
What's the php output?
Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>

PHP/JS Ajax _POST Array not Posting

there's something strange going on in my ajax code. I'm have some difficulty narrowing it down.
JavaScript:
//Discard Displaying Cards
$(".discard").click(function(){
var gameId = 20;
var cardArray = [];
$( ".card" ).each(function() {
var cardId = $(this).attr('id');
cardArray.push(cardId);
});
$.ajax({
type: 'POST',
url: './system/actions/discard.php',
data: "gameId=" + gameId + "&cardArray=" + cardArray,
success: function(data) {
console.log(cardArray);
console.log("Success.");
console.log(data);
}
});
});
The javascript posts to a file discard.php where it is given two parameters: gameId and cardArray. gameId is static right now, but cardArray is made up of the DOM ids of each of the ".card" elements loaded on the page. Each DOM id reflects the card_id in my database.
discard.php
//Classes
include $_SERVER["DOCUMENT_ROOT"] . '/system/classes/cards.php';
header("Content-Type: text/html");
$gameId = empty($_GET['gameId']) ? '' : $_GET['gameId'];
$numbers = empty($_GET['cardArray']) ? '' : $_GET['cardArray'];
$regex = preg_replace('/[^,;a-zA-Z0-9_-]|[,;]$/s', '', $numbers);
$cardArray = explode(",", $regex);
foreach ($cardArray as $cardId) {
discardCards($cardId, $gameId);
};
The discard.php is supposed to read the $_GET headers from the ajax request. But for some reason, it fails. The funny thing is, if I call the page directly with manual GET headers, e.g I browse to:
domain.com/system/actions/discard.php?gameId=20&cardArray=["1","3"]
OR even
domain.com/system/actions/discard.php?gameId=20&cardArray=1,3
The script works fine!
I thought it may have been something with the format ajax is posting in, hence the regex, but alas, it did not work. Because I'm not even sure how to display or view the requested ajax data URL on the page it called on, I'm finding it particularly difficult to debug.
Any suggestions? Thanks in advance.
You are using:
type: 'POST',
But you are receiving it as $_GET, change it to $_POST:
$gameId = empty($_POST['gameId']) ? '' : $_POST['gameId'];
$numbers = empty($_POST['cardArray']) ? '' : $_POST['cardArray'];
Or change the AJAX function to:
type: 'GET',
And also, the data is supposed to be a string. So use serialize():
$(form_id).serialize();
Where form_id is the id of the form.

How to structure jquery ajax to be flexible to in and outputs?

I have a one-page structured website. I am trying to use Ajax to update my data on user demand.
I am trying to figure out how to structure my ajax code, so that it will be flexible to my in and outputs = I want to run different function depending on the clicked link, and I want to return the right output to the right div.
HTML links:
<a href="#page-a" class="dbLink" data-variable="funcA">
<a href="#page-b" class="dbLink" data-variable="funcB">
<div id="page-a">
<div id="a-result"></div>
</div>
<div id="page-b">
<div id="b-result"></div>
</div>
JS, ajax (I am passing a data-variable along the link to controle the action):
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
dataType: 'json',
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
});
});
functions.php:
include 'dbconnect.php';
function funcA($mysqli){
$result = $mysqli->query("select * from database");
$row = mysqli_fetch_assoc($result);
echo $row['column'];
}
function funcB($mysqli){
$result = $mysqli->query("select * from database2");
$row = mysqli_fetch_assoc($result);
return $row['column'];
}
if (isset($_POST['action'])) {
$resp = null;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#page-a";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#page-b";
break;
default:
break;
}
echo json_encode($resp);
}
add another data-* variable set to the id of the place you want to output the data. To control the format of the returned data provide the dataType option in the ajax options, and of course make sure the pointed to url actually outputs that type of data. dataType It will tell jQuery how to parse the incoming data.
var theContainer = $(this).attr("data-container");
...
dataType:"json" //or text, or xml etc etc
success: function(data){
//if data is upposed to be json
//and datType is set to json
//data will be an object, same with xml
//process data how you need to
$("#"+theContainer).html(whateverYouHaveDone);
}
If you need to control the target of the returned data within your php script then turn your returned data into json and send the selector for the target to it
$resp = new stdClass;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#someContainer";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#someContainer";
break;
default:
break;
}
echo json_encode($resp);
Then in your ajax success
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
And of course set dataType:"json"
To return just the mysql row, do the same thing as above but in the ajax success resp.data will be an object. So just access the properties of resp.data with the column names of the row
success: function(resp){
if(resp.data){
//if say you have a column named "username"
var username = resp.data.username;
}
}
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var target = $(this).attr('href');
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(data){
$(target).html(data);
}
});
});
there are many ways to do this.
I see you have understood the custom data-* attributes. I would add one more attribute: data-target=""
<a href="#page-a" class="dbLink" data-variable="funcA" data-target="a-result">
<a href="#page-b" class="dbLink" data-variable="funcB" data-target="b-result">
<div id="page-a">
<div class="a-result"></div>
</div>
<div id="page-b">
<div class="b-result"></div>
</div>
Then inside your JQuery, you do like you do with your data-variable, only that you add the new data-* attribute:
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var theTarget = $( this ).attr("data-target");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(){
/* Here you have to change the data[] to match the JSON return from your PHP-script. You can of course do it without JSON, but I would use http://www.php.net/manual/en/function.json-encode.php on an array from PHP.*/
$("input[class="+ theTarget +"]").html( data["foo"][0]["bar"] );
}
});
});
If you want to play with a real life example, I made this fiddle for another guy on stack overflow a while back: http://jsfiddle.net/Olavxxx/Mu66h/
Put a number in the left box (like 5006), it's postal codes. The target then is the postal adress in the right input box. The concept is very much the same as you are after, with data-targets.

Categories

Resources