Problems accessing data from jQuery “serialize()” form to PHP backend - php

I’m trying to pass values from a dynamic form to PHP, using jQuery serialize(), but I am only receiving part of the string:
The form is created by a MySQL query:
echo '<form role="form" id="reserva_tour" action="shop_wopt.php" method="POST">';
$db->Consultar("SELECT * FROM tour_options WHERE tourID = '$tour_id' order by tourID");
while($row = $db->ObtenerArray()) {
$regis = $row['recid'];
$name = $row['name'];
$radl = $row['adl_rate'];
print "<a href='#' class='tit_tour btn btn-success'>$name - $$ratebase</a>";
print "<input type='text' name='open_adl[$regis]' id='adl$regis' class='adl' />";
}
print "Tour Calc ";
print "</form>";
The jQuery:
$(".calcTourOpt").click(function()
{
var adl = $('.adl').serialize().replace(/%5B/g, '[').replace(/%5D/g, ']');
console.log(adl);
$.ajax({
url: "calctour_opt.php",
data:"adl=" + adl + "",
type: "POST",
dataType: "json",
cache: false,
success: function(data){
console.log(data)
}
});
});
This is calctour_opt.php:
$adl = $_POST['adl'];
$values = array();
parse_str($adl);
$total = $open_adl[4];
echo json_encode($total);
This is happening:
After serializing the class "adl" (before the ajax call, in the console.log), the string looks like this: open_adl[4]=2&open_adl[5]=3 and is correct!
In my php file if I declare $total = $open_adl[4]; works fine, it shows me the result: 2.
But if I change to: $total = $open_adl[5]; does not work, it shows me NULL, instead of 3.
Can anybody tell me what is wrong?

You should change $.ajax data param from string to json string like this
// FROM
$.ajax({
url: "calctour_opt.php",
data:"adl=" + adl + "", //<- Wrong
type: "POST",
...
// TO
$.ajax({
url: "calctour_opt.php",
data: {adl: adl}, //<- Correct
check documentation here about data param for ajax - http://api.jquery.com/jquery.ajax/

Related

Select multiple rows into array and send them via AJAX

I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

how come i can't populate textarea with <br>, by the way im using ajax

this is the ajax im using,
$.ajax({
type: "POST",
url: "../../Ajax/<?php echo $exercise_num ?>",
data: "user_input=" + user_input,
success: function(resp){
//output
$("#message").text(resp);
}
});
}
and when i try to populate $("#message").text(resp) with
public function pb3()
{
$num1 = 10;
$num2 = 7;
echo "$num1 + $num2 = "; echo $num1 + $num2;echo "<br>hi";
}
my html code:
Message: <font id="message"></font>
the output:
Message: 10 + 7 = 17<br> hi;
or is there any way to use br in the textarea of font?
You can't have html inside a textarea. It won't be interpreted properly, and it should be escaped to prevent injection. You want to use a newline:
echo "\n\nhi";
Try this :
$("#message").text(resp.replace("<br>", "\n"));
ref : http://www.w3schools.com/jsref/jsref_replace.asp
you can replace <br> with \n ,
main thing is you cannot put html tags on textarea value
$.ajax({
type: "POST",
url: "../../Ajax/<?php echo $exercise_num ?>",
data: "user_input=" + user_input,
success: function(resp){
//output
$("#message").text(resp.split("<br>").join("\n"));
}
});
}

is php json_encode & AJAX breaking my array?

I'm grabbing some database entries, creating a 2D array and then passing them to js with AJAX. But when I loop through the array in javascript, it's an "undefined" mess. The console log for dbArray works fine, so I know the PHP/AJAX is working. Not sure what I am doing wrong with the loop...
PHP ('load-words.php):
$query = mysql_query("
SELECT * FROM words
ORDER BY RAND()
LIMIT 50
") or die(mysql_error());
$dbArray = array();
while ($row = mysql_fetch_assoc($query)) {
$word_phrase = stripslashes($row['word_phrase']);
$description = stripslashes($row['description']);
// construct a 2D array containing each word and description
$dbArray[] = array($word_phrase,$description);
};
echo json_encode($dbArray);
Javascript:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) {
console.log(dbArray);
var items = "<ul>";
for (var i in dbArray) {
items += "<li><a href='#'><b>" + dbArray[i][0] + ' : ' + dbArray[i][1] + "</a></li>";
}
items += "</ul>";
div = $('#dbArray');
div.html(items);
}
});
I guess this is failing because jQuery is interpreting the AJAX response as a string, since your PHP is not outputting a JSON header and your AJAX is not stipulating JSON. This is easily tested:
$.ajax({
url: 'func/load-words.php',
success: function(dbArray) { alert(typeof dbArray); /* "string"? */ }
});
Try
$.ajax({
url: 'func/load-words.php',
dataType: 'json', //<-- now we explicitly expect JSON
success: function(dbArray) { alert(typeof dbArray); /* "object"? */ }
});

PHP Arrays - jQuery referencing issue

I have the following php:
1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));
I also have the following:
2) $row = mysql_fetch_assoc($result);
echo(json_encode($row));
Now consider the following jQuery:
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
})
This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...
How can I make $row in the php compatible with the data.message in the jQuery?
try:
$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
echo(json_encode($data));
message = row:
$data = array();
$data["message"] = mysql_fetch_assoc($result);
echo(json_encode($data));
or two line solution (inspired by val):
$row = mysql_fetch_assoc($result);
echo(json_encode(array("message" => $row)));
Try
$row = mysql_fetch_assoc($result);
echo(json_encode(array('message'=>'I am the message','result'=>$row));
Then to answer your second question on the comments something similar to this could show the information ....
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
var html = '';
for(var i = 0; i<data.result.length;i++){
html +='<div>'+data.result[i].fname+'</div>';
}
$('#result').html(html);
}
})
ofcourse you need to edit it abit where applicable .
i believe you don't have $row['message'] from mysql_fetch_assoc.
you have to explicitely define the message key on the array before json_encode.
$row = mysql_fetch_assoc($result);
$row['message'] = 'Hello '.$row['username'];
echo(json_encode($row));

Categories