Updating MySQL Database with ajax - javascript

I'm trying to send a JS array to a .php file on the click of a button, and run the php file's code on the click, using the array that was sent.
I have a button:
<button id="submit" class="button1" >Submit<span></span></button>
Which I try to run this JS ajax with:
$('#submit').click(function() {
$.ajax({
method: "POST",
url: "submit.php",
data: selectedImageArray
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In my submit.php file, I connect to the database, then have this:
$array = $_POST['selectedImageArray'];
$sql = $dbh->prepare("INSERT INTO pending_trades (steam_id, trade_items, is_giving, is_receiving, has_started) VALUES (:steamid, :itemlist, '1', '0', '0')");
$sql->bindParam(':steamid', $steamprofile['steamid']);
$sql->bindParam(':itemlist', $array);
$sql->execute();
}
When I click the "submit" button, I get the message saying "Data saved", but nothing is happening with my database. Should clicking the button run the submit.php code?

$('#submit').click(function(){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}, // this is supposed to be JSON
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
And
$_POST['selectedImageArray'] // see the quotes

You have a syntax error with your JS. Also, since #submit is an ID, qualifying it with button is unnecessary.
Your code should read:
$('#submit').click(function() {
$.ajax({
method: "POST",
url: "submit.php",
data: selectedImageArray
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Edit 1:
I see that you have incorporated the above code into your JS. Now on to your problem on the server side (PHP/SQL).
Firstly, why are you decoding $_POST[selectedImageArray] then re-encoding it? Doesn't make sense to me.
Secondly, what is the value of $steamprofile['steamid']?
Thirdly, what is the schema of your SQL table? Are you sure you're not violating any unique / not null / fk constraint?
Do yourself a favour, and use a debugging/logging solution on the server-side. It can be as simple as printing debug lines into a log file so you can inspect later on to find out what is happening.
What I'd do:
check value of $_POST[selectedImageArray]. It should be a string.
check the value for $array. It should be an array.
read the error logs to see what else it says.
$sql->execute(); returns a bool (TRUE on success). Use it in your script to return either success or failure message.
Log down the value of $sql->errorCode(); on failure.
With all the above, you should have enough to troubleshoot what went wrong there.

I suppose that steam_id is a primary key with auto increment, so if you are trying to insert a row to database with the same value for steam_id, then it is a possibility that your data cannot be added.
To debug in a better way, try to generate the query in the server and echo it. Then try to run the same query in your MySQL console to find the response.

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.

send an array per ajax to an python-server-script

I want to send all my names,values and labels of my form-elements when I klick on a button, I didnt make a submit-button, beause the I got them in a wrong order, so I make this in JavaScript:
$('#mybutton').click(function() {
m.modal('show');
var all=[];
$('textarea, select, input').each(function(index){
var label= $(this).parent().find('label').html();
var value= $(this).val();
var name= $(this).attr('name');
all.push([name,value,label]);
})
$.ajax({
dataType: "text",
url: "befund",
data: {
wert : all
},
success: function(data){
$('#mymodal').find('.modal-body').html(data);
}
})
});
in the python server-script (bottle) I try this:
#app.route('/web/befund')
def modalcontent() -> str:
x = request.query.wert[0][1]
print (x)
return('test')
the problem is that I see in the browser, that the right array is send but when I try to see one element of the array with "request.query.wert[0][1]" I only get a http-error 500 (internerl server error). Can anybody help me please?
You can use POST for this (and should, if this is sensitive data and your connection is secure).
However, you need to turn the data into a JSON string, then decode it on the server.
data: {
wert: JSON.stringify(all)
},
On the server:
wert = json.loads(request.params.wert);
print wert[0][1]
I think the wert it is the object on the server side. Try accesing data by `x=request.query.wert[0]
or
x=request.query['wert'][0]
Im not using python now, but it seems like right

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

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