PHP + jQuery - undefined index: , but it still posts successfully? - php

When inserting a record to a database, the server returns an 'undefined index: category', error, but still posts the successfully.
$('#button').click(function(){
var newvendor = $('#input_vendor').val();
newplantcode = $('#input_plantcode').val();
newcategory = $('#input_category').val();
$.post("php/addSite.php",
{vendor: newvendor,
plant_code: newplantcode,
category: newcategory}, // <--- Error on this line, for some reason...
function(result){
console.log("server returned : " + result);
[ RELOAD THE PAGE ]
}

You having missing quote in almost all your code:
$('#button').click(function(){
var newvendor = $('#input_vendor').val();
var newplantcode = $('#input_plantcode').val();
var newcategory = $('#input_category').val();
$.post("php/addSite.php",
{vendor: newvendor,
plant_code: newplantcode,
category: newcategory}, // <--- Error on this line, for some reason...
function(result){
console.log("server returned : " + result);
[ RELOAD THE PAGE ]
}
//closing the post function
)
//closing the click event
});
Now try that again

Related

Jquery Ajax call to PHP don't give me any data back with dataType JSON

I'm working everyday with ajax and php at work, so it's nothing new. But now i tried a little project at home and i can't get it to work. I really don't know what i have done wrong. I just select a value from a dropdown and press a Button. The button has a onclick to a function calles "showTable". It selects the value of the dropdown and send it via ajax call to my index.php where i do a simple select to my database and wanna return the results, so i can build a table with it. But my ajax call always go to the error case, even if the result of the select is correct.
If i console.log my error, it just says "parseerror" but the network part always says 200 ok
So, this is my function within my index.html...
<script>
function showTable() {
var coin = $('#selectCoin').val();
$.ajax({
type: 'POST',
url: 'index.php',
dataType: "json",
data: {
act: 'showTable',
'coin' : coin
},
success: function(data) {
alert("ok")
},
error: function(request, error) {
alert("error")
}
});
}
</script>
And this is my php part
if($_POST) {
switch ($_POST["act"]) {
case 'showTable':
$token = $_POST["coin"];
$token_buy = $token.'_buy';
$token_sell = $token.'_sell';
$sql = "SELECT * FROM $token_buy";
$stmt = $PDO->prepare($sql);
$stmt->execute(array());
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
break;
}
}
I tried to update the composer and added the
"ext-json": "*"
Also i tried to remove the dataType Attribute from my ajax call. After that it don't get into the error case, but also i don't get my data from backend.
If i let me show the error with following function
error: function(jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText)
}
It says:
parseerror: SyntaxError: unexpected token "<", "<!DOCTYPE"...is not valid JSON: and continue with the whole html part in the error message

Ajax Internal Error, jqXHR: underfined

Ive butchered my code trying to find this bug. I have a Ajax post function working elsewhere on my code and it works fine.
For some reason this one does not want to cooperate.
Im going to reduce the amount of inputs so the code doesnt look too long.
Here is the php
<?php
// --------Connect to DB --->
include 'connect.php';
$conn = connect ();
//====================================================================>
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
$sql_update_query = "UPDATE Galaxy_jobs SET date ='$this_start_date' WHERE PID = $this_id";
//====================================================================>
mysqli_query ($conn,$sql_update_query);
//close
mysqli_close($conn);
?>
Here is my Ajax call.
function ammend_job()
{
pid = '2'; // test figures
start_date_ammended = '11-11-1111'; // test figures
var Data = {
pid_num : pid,
date_ammend : start_date_ammended,
};
$.ajax({
url:"ammend_job.php",
type: "POST",
dataType: 'text',
data: Data,
success: function(data){
if(data.status == 'success')
alert('Post has been uploaded to Database');
},
error: function(xhr,textStatus,err,jqXHR) {
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
console.log("Jquery error:" + jqXHR)
// alert('There is an error, screenshot this error and send to Admin : TextStatus: ' +textStatus+" - Error: "+errorThrown+" - XMLRequest: "+XMLHttpRequest+"- Response Text"+xhr.responseText);
}
});
}
Here are the error codes :
main.php:102 readyState: 4
main.php:103 responseText:
main.php:104 status: 500
main.php:105 text status: error
main.php:106 error: Internal Server Error
main.php:107 Jquery error:undefined
Any help will be greatly appreciated.
It took a while.
I wouldnt have found it if it wasnt for user : tereško who suggested to look closely at the errorlog on the server.
I found that when I replaced my code in php file
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
with the square brackets
//grab data
$this_id = $_POST['pid_num'];
$this_start_date = $_POST['date_ammend'];
The code didnt throw an error and worked.
I hope somebody else out there finds this post and figures out that this may be 1 reason for their error.

nodejs .map() on loaded content

I have the following sample code (i am completely new to nodejs) , the code is as follow :
var http = require('http');
var fetchurl = 'http://localhost/sampledata.php';
http.get(fetchurl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var Response = body;
Response.map(function(ent,i){console.log(ent.name);});
console.log("Got response: ", Response.toString());
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
The above code loads some data from sampledata.php file which is as follow:
[{ name : 'david' , age : '25' } , { name : 'Henry' , age : '22' },{ name : 'Tom' , age : '15' },{ name : 'salena' , age : '35' }];
The problem is that when i run the top code , i get the error :
Type Error: Object (name: 'david', age:'25') has no method `map`
But the console log displays the data well, also if i use the same data without loading it from URL, it works perfectly fine.
Whats wrong here?
You need to convert the body to JSON first.
I normally have a function like the following to catch any errors:
function tryParseJson(str) {
try {
return JSON.parse(str);
} catch (ex) {
return null;
}
}
and then change your line to this:
var Response = tryParseJson(body);

getting error when i send the textfield value through ajax request to php using sencha touch

my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);

jQuery AJAX Request Doesn't Work on Page Load, However, It Does Work from Debug Console

Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!

Categories