Php does not echo the data from a jQuery Ajax submit - php

I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:
Here is the php code:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
Here is the jQuery code:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.
Why doesn't php gets my data and echo it?

You need to get the returned data by the php and do something with it. See the added line of code below.
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});

You have to use the success callback function to process the response from the POST to your Php page.
As stated in this thread
Your code could look similar to the following:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery
Hope this helps you

The correct way:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Related

display the array values-ajax

I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

delete data in sql using ajax and php in XDK

i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.

Serialized AJAX $_POST is not empty but single $_REQUEST is empty

I'm making an AJAX Call like this:
$( "#submit_jobs_preview" ).click(function(e) {
var postData = $('#new_job_form').serialize();
var formURL = "ajax.xxx.php";
$.ajax({
type: 'POST',
url: formURL,
data: {submit_jobs_preview: postData },
success: function(data){
alert(data);
}
});
e.preventDefault(); //STOP default actio
});
In php i echo:
echo $_POST['submit_jobs_preview'];
This $_POST shows all values i put in my form correctly like this:
new_job_city=Berlin&new_job_name=Manager etc.
But if i want a single $_REQUEST from this $_POST like this:
if($_POST['submit_jobs_preview']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
the alert is empty.
Why is that?
UPDATE
Full return of data:
XHR Loaded (autocomplete.php - 200 OK - 105.99994659423828ms - 354B) VM2106:3
new_job_city=Halle&new_job_job=Flugbegleiter&new_job_other_job=&job_zielgruppe=Auszubildende&new_job_phone=4921663965439&new_job_email=kleefeld%40dsc-medien.de&new_job_detailhead=F%C3%BCr+unser+zentrales+Marketing+mit+Sitz+in+der+Hauptverwaltung+in+der+City+von+D%C3%BCsseldorf+suchen+wir+zum+n%C3%A4chstm%C3%B6glichen+Termin+eine%2Fn&new_job_time=Vollzeit&teilzeit_std=&new_job_tasks=&new_job_profile=&new_job_advantage=&new_job_creatorId=1&new_job_creationDate=1390569795&new_job_scope=Airport+Service&new_job_niederlassung=7&new_job_active=0
You don't need to use {submit_jobs_preview: postData } if it is not necessary. I will give you another hint. Use following ajax;
$( "#submit_jobs_preview" ).click(function(e) {
var postData = $('#new_job_form').serialize();
var formURL = "ajax.xxx.php";
$.ajax({
type: 'POST',
url: formURL,
data: postData,
success: function(data){
alert(data);
}
});
e.preventDefault(); //STOP default actio
});
and on php side;
if($_POST['new_job_city']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
In this case you can use field names directly.
Another hint:
You can put a hidden value on your form like,
<input type="hidden" name="submit_jobs_preview" value="true"/>
and js side will be same as above in my answer, and in php side you can check like;
if($_POST['submit_jobs_preview']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
As you can see, you can send your post value as hidden field and make your check
$_POST['submit_jobs_preview'] holds a string and nothing else so you just can't access it that way. Use parse_str() to unserialize $_POST['submit_jobs_preview']. That way you can access its properties.
$_POST['submit_jobs_preview']['new_job_city']

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories