$.ajax query not posting to PHP - php

I've spent the better part of today trying to send a jQuery variable to my PHP file and use it in a SQL search. My first issue is that can't even get the variable into PHP properly. I am also getting an error about some of my SQL code which I've included as well.
What I want: the variable in jQuery called name sent to the PHP file where it is used in an SQL Query to find the real name of musicians. the real name would then be sent back to the HTML file where it is displayed on the webpage. MyPHPAdmin and my database has already been setup.
jQuery:
$('li').click(function () {
var name = $(this).text();
$('#prf').attr("class",name);
$('#pic').attr("class",name);
$('#info').attr("class",name);
JSON.stringify (name);
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
})
PHP:
$rname = $_POST['name'];
var_dump($rname);
try {
$db = new PDO('mysql:dbname=dbname;host=myhost;charset=utf8', 'user', 'pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
var_dump($rname);
echo 'Success';
$result=$stmt->fetchAll();
print "<pre>";
print_r($result);
print "</pre>";
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
OUTPUT:
NULL NULL
I've read the documentation on $.ajax() and still can't figure out what I'm doing wrong. I appreciate any help on this, it's been giving one hell of time.

To evaluate the output of the PHP script from the AJAX request add a return handler to your request:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
}).always(function( html ) {
console.log(html); // this will show the content of the php script in the developer console of your browser
});
The function defined in .always() is called every time an AJAX request finishes. When you made sure that your code works you can change it to .done(), which is only called when the AJAX call is successfull. You can also add a .failure() function to handle errors gracefully.
Also note this from the documentation:
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use.
I'd suggest to use the $.post function instead:
$.post("ajax-name.php", {name: name}, function( html ) {
$('#outputdiv').html(html);
// this will replace the content of a <div id="outputdiv"></div> with the output of the AJAX request
});

Try this:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name},
success : function(html) {
// html code, do something with it here
}
});
then
$rname = $_POST['name'];
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
You get your result with
$stmt->fetchAll();
You don't retrieve PDO driver results with mysqli

alert variable name in javascript and make sure it is not null.you may use exit;
echo $_POST['name'] in the php file.receive the processed data in javascript with the success:function(result) and alert it.
store every data in a single variable in the php file. and finally echo them.

Related

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Sending array from PHP script

Here's the values I am sending to the PHP script from the Javascript:
$('.verdi_knapp').click(function() {
$(this).siblings().removeClass("aktiv_verdi"); // ta vekk aktiv på de andre alternativene
$(this).addClass("aktiv_verdi"); // sett denne til aktiv
var min_id = $(this).attr('id').split("_")[1];
var aktuelle_verdier = []
$('.aktiv_verdi').each(function() {
aktuelle_verdier.push($(this).attr('id').split("_")[1]);
})
console.log("disse verdiene skal vi spørre etter", aktuelle_verdier)
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
This is the PHP script which queries a set of values from an SQL database and prints them to the console in the javascript:
$ids = $_GET['aktuelle_verdier'];
$value = implode(", ", $ids);
$antall = count($_GET);
$sql = "SELECT `art_id`
FROM `art_has_verdi`
WHERE `verdi_id` IN (".$value.")
GROUP BY `art_id` HAVING COUNT(*)=".$antall.";";
$result = mysqli_query($conn, $sql);
$arter_igjen = array();
while($row = mysqli_fetch_array($result)){
array_push($arter_igjen, $row['art_id']);
}
echo json_encode($arter_igjen);
What I am trying to find out next is how to send this array: $arter_igjen, which contains a set of IDs, to another page where I can run a query to the database for all the data containing these IDs and print them out in a list.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
Please check data Paramter in ajax call. You forgot to pass key in JSON.
If I understand you right you like after ajax return you clone the window and in new one window you will make some new searches, but on the current one will be generate a log. In cas I'm understand you right, then why don't try to generate form on fly by with returned data end post it to the _blank window.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
// Here you have to generate the form on fly
// Include hidden fields, containing your result data
// and finally send form with action some new.php on blank_ target
console.log(result);
}});
If the other page contains code like in this one (not in a class or function), you can just include it (include_once "..."), but it is not recommended that you just keep scripts like that.
Instead, encapsulate your code (put it within functions and classes). This will allow you to freely insert your scripts (include_once "...") and call these functions or create classes that will work.
Also, try to avoid too many http requests. If that list of ids won't be needed, do all of the work in the php scripts and return the needed result.
There are a few issues with your code. If you are just starting with PHP I would suggest you read:
PDO: Creating a connection
PDO with prepared statements (prevents SQL injections)
User-defined functions (I don't have enough reputation to put the link. Search: "w3schools php 5 functions")

Jquery $ajax POST data and get a response mysqli_insert_id

I am posting data to a PHP page using the $.ajax in Jquery. So far all this is working fine.
Here is how all this looks in my index.html.
function send() {
$( "#send" ).show( "slow" );
var page = Page;
var title = $("#title").text();
var title_2 = $("#title_2").val();
$.ajax({
url: "save.php",
method: "POST",
data: { MyPage : page, My_Title1 : title, My_Title2 : title_2 },
dataType: 'json',
success: function(data) {
alert(data);
var result = jQuery.parseJSON(data);
alert(result.last_id);
},
error: function(output) {
alert("not working whole process");
}
});
This to sum up what I am doing, is sending some data, Html and contents in div's, to a sql database.
What I would like to do now is that once this data is posted to the save.php file, I get a response from the php sending me the ID of the page I have saved all this in. So I am using mysqli_insert_id($con); to acheive this.
Set it it looks like this.
$last_id = mysqli_insert_id($con);
When I execute all this, the Post works fine and I end up with what I want.
{"last id":265} at the end of my post.
$data['last id'] = $last_id;
echo json_encode($data);
How do I get this value back to my index.html so that I can place it inside a input. The success is not working out.
//Reply to Steves answer
# Steve. Thank you for answering. Your answer is exactly what is happening. I am sending a whole bunch of html to my save.php file so it can save it to a sql table.
Something looking like this.
Write to MySQL OK!<br>INSERT INTO Project(ID_User,Name_Project,Page_Project,Date_Project) VALUES ( 110, '\"Project name here\"', '<div class=\"file_save_container\"> <------------- HERE THERE IS A WHOLE BUNCH OF HTML ------------> </div>\n\n\n', '2015-03-19 13:10:23');<br>
This is all saving properly to my sql table. What I would like to achieve here is that when the ajax is sent to my save.php I get a response sending me the id of the newly created Project so that I can then place the response "the id" inside a . Right now mysqli_insert_id is placing this at the end of my post.
<br>{"this_id":"311"}
This is what I would like to get back as a response to my index.html file and not have it at the end of my post.
Try to set header('Content-Type: application/json'); in save.php
Write $data['last_id'] instead of $data['last id'] to match your JS.

aJAX call to PHP file

I have a need to use the $.ajax method to call a PHP file. I have to pass in a driver id to the PHP file, which then retrieves the id, executes a query to get the driver's name and return that name back to the form so I can autopopulate the appropriate textbox. Here is the ajax method:
var id=$('#DriverID').val();
$.ajax({
url: 'drivername.php',
data: {driverid: id},
type: 'POST',
success: function(data) {
$.('#DriverName').val(data);
}
});
Here's the PHP:
$driverid=$_POST['driverid'];
$host="Host to database";
$user="user"
$password="password";
$db="database";
$driver="";
$query="SELECT driver_name FROM drivers WHERE driver_id=$driverid";
$cn=mysqli_connect($host, $user, $password, $db);
$result=mysqli_query($cn, $query);
while($data=mysqli_fetch_array($result))
{
$driver=$data['driver_name'];
}
echo $driver;
How do I configure the PHP file to return the driver's name, and also, is the ajax method syntax correct?
It looks like your PHP script is already returning the "driver's name" variable that you're setting up with your SQL. If your return value was larger or more complex (e.g., multiple values, an array/object/etc), you could JSON encode it and use jQuery to JSON decode it. To update CSS id "DriverName" with the return data, I think you just have an extraneous ".":
success: function(data) {
$('#DriverName').val(data);
}
This question is quite similar: jQuery ajax - update div

POST data through AJAX and set as variable

I am not very familiar with javascript especialy when it comes to functions and ajax. I am trying to get some data from another php page and have it put into a div. When I ever i load the page nothing comes up.
My ultimate goal is to get the data into a php or javascript but first need to figure out how to get / receive data.
here is the php code of feedupdate.php
<?php
require "dbc.php";
$function = $_POST['function'];
switch($function)
case('initiate'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$mostrecent= mysql_fetch_array($request);
$mostrecentid = $mostrecent['id']
echo json_encode($mostrecentid);
break;
case('update'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
echo json_encode($updateid);
break;
?>
here is the ajax
<div id="datacheck"></div>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST'
url: 'feedupdate.php'
data: {'function': 'initiate',},
datatype: "json"
success: function(msg) {
$('#datacheck').html(msg);
}
});
}); // document ready
There is a typo in the ajax jquery code
success: fuction(msg) {...
it should be spelled "function".This typo might be the problem , plus there should be switch case for
getState
in your php code.
You are passing getState in data from JavaScript while in PHP you do not have a similar case to match in switch statement. Instead of getState pass update or initiate.
If you just want to check either AJAX call is working or not write
echo "something message"; exit();
In your AJAX you are passing data back to the PHP script:
data: {'function': 'getState'},
But in your php script you don't have a case statement that matches getState you only have initiate and update. So you can either write code to support getState or you can pass in either initiate or update to the data parameter.
Also watch out for trailing comma's. They won't work in IE. You should remove the comma after 'getState' on the data line.
You are also missing a comma after type, url, and datatype
$(document).ready(function() {
$.ajax({
type: 'POST', // add comma
url: 'feedupdate.php', //add comma
data: {'function': 'initiate'}, // remove comma
dataType: "json", // add comma
success: function(msg) {
$('#datacheck').html(msg);
}
});
});
Alos you can look at using the shorthand method $.post docs

Categories