What is wrong with my AJAX jQuery function? - php

I have a function that does a simple call to a PHP file with a simple INSERT statement in it. When I click the corresponding button, the function does not even send the AJAX request or return false.
$(function() {
$('#add_employee_submit').click(function() {
var fname = $('#eie_fname').text();
var lname = $('#eie_lname').text();
var doNo = $('#eie_doNo').val();
var emergency = 0;
if($('#eie_emergency').is(':checked')) {
emergency = 1;
}
$.ajax({
type: "POST",
url: "scripts/employee_information_entry.php",
data: "fname="+fname+"&lname="+lname+"&dono="+doNo+"&emergency="+emergency,
success: function() {
showMessage('employee_added');
}
});
return false;
});
});
Am I missing something obvious here?
EDIT:
Instead of wasting more time trying to figure out what was wrong I went with #ThiefMaster's advice and used jquery.malsup.com/form. This is working correctly and is a lot let work.
Thanks for everyone's help. :)

The success function should have a response parameter i.e. your code would be like:
$.ajax({
type: "POST",
url: "scripts/employee_information_entry.php",
data: "fname="+fname+"&lname="+lname+"&dono="+doNo+"&emergency="+emergency,
success: function(response) {
showMessage('employee_added');
}
});
Also check if the various id's are present there or not.
The best method to check is to use firebug/developer console to check what parameters are being sent and what are being received.

Related

Serialize() form in an existing ajax function

Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Sending back multiple results from PHP via AJAX

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

jQuery .ajax() Method

I am new to the jQuery AJAX ajax() Method. I have successfully created the function AddATeacher() which gets called because all the alert messages do popup. However the ajax() Method inside the function does not work. I know this because the addATeacherInsert.php does not load.
I got it to work under firefox, but not on chrome. However it only works in firefox when I have the alert message at the end of the code: alert ("Exiting myJQFunctions...");, otherwise it stops working all together. I would like it to work when I comment out the alert message at the end of the file. How can I solve this?
function AddATeachers()
{
var tFirstName = $('#teachers_first_name').attr('value');
var tLastName = $('#teachers_surname').attr('value');
alert ("Entering myJQFunctions...");
alert ("Teachers first name is: " + tFirstName);
$.ajax({
type: "GET",
url: "../pgs/addATeacherInsert.php",
data: "tFirstName="+ tFirstName +"&tLastName="+ tLastName,
success: function(html){$("#Ajax_response").html(html);}
});
// works well under firefox but shows alert
// doesnt work at all if commented out.
alert ("Exiting myJQFunctions...");
}
Ajax functions ends only after it gets response from server.
function AddATeachers()
{
var tFirstName = $('#teachers_first_name').attr('value');
var tLastName = $('#teachers_surname').attr('value');
alert ("Entering myJQFunctions...");
alert ("Teachers first name is: " + tFirstName);
$.ajax({
type: "GET",
url: "../pgs/addATeacherInsert.php?tFirstName="+ tFirstName +"&tLastName="+ tLastName,
success: function(html){
alert(html); // alerts the html code returned.
$("#Ajax_response").html(html);
alert("Exiting myJQFunctions..."); // Ajax function ends here only.
}
});
}
You could use the jQuery GET method
function AddATeachers() {
.get('url/phpPage.php', {tFirstName: $('#teachers_first_name').attr('value'), tLastName: $('#teachers_surname').attr('value')}, function(returnData){
$("#Ajax_response").html(returnData);
});
}
Answer for ur Question Only
$.ajax({
type: "GET",
url: "Enter Full file path",
data: "tFirstName="+ tFirstName +"& tLastName="+ tLastName,
success: function(html){
$("#Ajax_response").html(html);}
});
tyr this dude...

Categories